/**! * @license FusionCharts JavaScript Library * Copyright FusionCharts Technologies LLP * License Information at * * @version 3.13.3-sr.1 * * @attributions (infers respective third-party copyrights) * Raphael 2.1.0 (modified as 'Red Raphael') * JSON v2 * Firebug Lite 1.3.0 */ // Pollyfill for Object.assign if (typeof Object.assign !== 'function') { Object.assign = function (target) { // .length of function is 2 'use strict'; var to, index, nextSource, nextKey; if (target == null) { // TypeError if undefined or null throw new TypeError('Cannot convert undefined or null to object'); } to = Object(target); for (index = 1; index < arguments.length; index++) { nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null for (nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; }; } // Pollyfill for Function.bind. if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { 'use strict'; var aArgs, fToBind, // eslint-disable-next-line no-empty-function fNOP, fBound; if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } aArgs = Array.prototype.slice.call(arguments, 1); fToBind = this; // eslint-disable-next-line no-empty-function fNOP = function () {}; fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; } (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["FusionCharts"] = factory(); else root["FusionCharts"] = factory(); })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + ({"1":"fusioncharts.charts","2":"fusioncharts.common","3":"fusioncharts.timeseries","4":"fusioncharts.powercharts","5":"fusioncharts.widgets","6":"fusioncharts.zoomline","7":"fusioncharts.gantt","8":"fusioncharts.treemap","9":"fusioncharts.zoomscatter","10":"fusioncharts.msstackedcolumn2dsplinedy","11":"fusioncharts.overlappedbar2d","12":"fusioncharts.overlappedcolumn2d","13":"fusioncharts.maps","14":"fusioncharts.vml"}[chunkId]||chunkId) + ".js" /******/ } /******/ /******/ // 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; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // 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, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // 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 = ""; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonpFusionCharts"] = window["webpackJsonpFusionCharts"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(92); __webpack_require__(116); module.exports = __webpack_require__(121); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(2); __webpack_require__(38); __webpack_require__(42); __webpack_require__(44); __webpack_require__(50); __webpack_require__(53); __webpack_require__(56); __webpack_require__(59); __webpack_require__(66); __webpack_require__(68); __webpack_require__(70); __webpack_require__(73); __webpack_require__(75); __webpack_require__(77); /* eslint no-extend-native: "off" */ if (!window.getComputedStyle) { // eslint-disable-next-line no-global-assign window.getComputedStyle = function (el) { this.el = el; this.getPropertyValue = function (prop) { var re = /(\-([a-z]){1})/g; if (prop === 'float') { prop = 'styleFloat'; } if (re.test(prop)) { prop = prop.replace(re, function () { return arguments[2].toUpperCase(); }); } return el.currentStyle[prop] ? el.currentStyle[prop] : null; }; return this; }; } // pollyfill for stopPropagation if (!Event.prototype.stopPropagation) { Event.prototype.stopPropagation = function () { this.cancelBubble = true; }; } /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(3); var $Object = __webpack_require__(7).Object; module.exports = function getOwnPropertyNames(it) { return $Object.getOwnPropertyNames(it); }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 Object.getOwnPropertyNames(O) __webpack_require__(4)('getOwnPropertyNames', function () { return __webpack_require__(23).f; }); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(5); var core = __webpack_require__(7); var fails = __webpack_require__(14); 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); }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(6); var core = __webpack_require__(7); var hide = __webpack_require__(8); var redefine = __webpack_require__(18); var ctx = __webpack_require__(21); 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) { // 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 /***/ }), /* 7 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.7' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(9); var createDesc = __webpack_require__(17); module.exports = __webpack_require__(13) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(10); var IE8_DOM_DEFINE = __webpack_require__(12); var toPrimitive = __webpack_require__(16); var dP = Object.defineProperty; exports.f = __webpack_require__(13) ? 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; }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(13) && !__webpack_require__(14)(function () { return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(14)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); var document = __webpack_require__(6).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) : {}; }; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(11); // 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"); }; /***/ }), /* 17 */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(6); var hide = __webpack_require__(8); var has = __webpack_require__(19); var SRC = __webpack_require__(20)('src'); var TO_STRING = 'toString'; var $toString = Function[TO_STRING]; var TPL = ('' + $toString).split(TO_STRING); __webpack_require__(7).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); }); /***/ }), /* 19 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 20 */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(22); 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); }; }; /***/ }), /* 22 */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(24); var gOPN = __webpack_require__(28).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)); }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(25); var defined = __webpack_require__(27); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(26); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 26 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /* 27 */ /***/ (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; }; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(29); var hiddenKeys = __webpack_require__(37).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(19); var toIObject = __webpack_require__(24); var arrayIndexOf = __webpack_require__(30)(false); var IE_PROTO = __webpack_require__(34)('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; }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(24); var toLength = __webpack_require__(31); var toAbsoluteIndex = __webpack_require__(33); 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; }; }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(32); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /* 32 */ /***/ (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); }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(32); 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); }; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(35)('keys'); var uid = __webpack_require__(20); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__(7); var global = __webpack_require__(6); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __webpack_require__(36) ? 'pure' : 'global', copyright: '© 2018 Denis Pushkarev (zloirock.ru)' }); /***/ }), /* 36 */ /***/ (function(module, exports) { module.exports = false; /***/ }), /* 37 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(39); var $Object = __webpack_require__(7).Object; module.exports = function getOwnPropertyDescriptor(it, key) { return $Object.getOwnPropertyDescriptor(it, key); }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(24); var $getOwnPropertyDescriptor = __webpack_require__(40).f; __webpack_require__(4)('getOwnPropertyDescriptor', function () { return function getOwnPropertyDescriptor(it, key) { return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(41); var createDesc = __webpack_require__(17); var toIObject = __webpack_require__(24); var toPrimitive = __webpack_require__(16); var has = __webpack_require__(19); var IE8_DOM_DEFINE = __webpack_require__(12); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(13) ? 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]); }; /***/ }), /* 41 */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(43); var $Object = __webpack_require__(7).Object; module.exports = function defineProperty(it, key, desc) { return $Object.defineProperty(it, key, desc); }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(5); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(13), 'Object', { defineProperty: __webpack_require__(9).f }); /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(45); var $Object = __webpack_require__(7).Object; module.exports = function create(P, D) { return $Object.create(P, D); }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(5); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: __webpack_require__(46) }); /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(10); var dPs = __webpack_require__(47); var enumBugKeys = __webpack_require__(37); var IE_PROTO = __webpack_require__(34)('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__(15)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__(49).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); }; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(9); var anObject = __webpack_require__(10); var getKeys = __webpack_require__(48); module.exports = __webpack_require__(13) ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(29); var enumBugKeys = __webpack_require__(37); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__(6).document; module.exports = document && document.documentElement; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(51); module.exports = __webpack_require__(7).Object.keys; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(52); var $keys = __webpack_require__(48); __webpack_require__(4)('keys', function () { return function keys(it) { return $keys(toObject(it)); }; }); /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(27); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(54); module.exports = __webpack_require__(7).Object.entries; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(5); var $entries = __webpack_require__(55)(true); $export($export.S, 'Object', { entries: function entries(it) { return $entries(it); } }); /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(48); var toIObject = __webpack_require__(24); var isEnum = __webpack_require__(41).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; }; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(57); module.exports = __webpack_require__(7).Array.indexOf; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $indexOf = __webpack_require__(30)(false); var $native = [].indexOf; var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(58)($native)), 'Array', { // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { return NEGATIVE_ZERO // convert -0 to +0 ? $native.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments[1]); } }); /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(14); module.exports = function (method, arg) { return !!method && fails(function () { // eslint-disable-next-line no-useless-call arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); }); }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(60); module.exports = __webpack_require__(7).Array.forEach; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $forEach = __webpack_require__(61)(0); var STRICT = __webpack_require__(58)([].forEach, true); $export($export.P + $export.F * !STRICT, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: function forEach(callbackfn /* , thisArg */) { return $forEach(this, callbackfn, arguments[1]); } }); /***/ }), /* 61 */ /***/ (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__(21); var IObject = __webpack_require__(25); var toObject = __webpack_require__(52); var toLength = __webpack_require__(31); var asc = __webpack_require__(62); 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; }; }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = __webpack_require__(63); module.exports = function (original, length) { return new (speciesConstructor(original))(length); }; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); var isArray = __webpack_require__(64); var SPECIES = __webpack_require__(65)('species'); module.exports = function (original) { var C; if (isArray(original)) { C = original.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return C === undefined ? Array : C; }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(26); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(35)('wks'); var uid = __webpack_require__(20); var Symbol = __webpack_require__(6).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; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(67); module.exports = __webpack_require__(7).Array.map; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $map = __webpack_require__(61)(1); $export($export.P + $export.F * !__webpack_require__(58)([].map, true), 'Array', { // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn /* , thisArg */) { return $map(this, callbackfn, arguments[1]); } }); /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(69); module.exports = __webpack_require__(7).Array.filter; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $filter = __webpack_require__(61)(2); $export($export.P + $export.F * !__webpack_require__(58)([].filter, true), 'Array', { // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn /* , thisArg */) { return $filter(this, callbackfn, arguments[1]); } }); /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(71); module.exports = __webpack_require__(7).Array.reduce; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $reduce = __webpack_require__(72); $export($export.P + $export.F * !__webpack_require__(58)([].reduce, true), 'Array', { // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: function reduce(callbackfn /* , initialValue */) { return $reduce(this, callbackfn, arguments.length, arguments[1], false); } }); /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var aFunction = __webpack_require__(22); var toObject = __webpack_require__(52); var IObject = __webpack_require__(25); var toLength = __webpack_require__(31); module.exports = function (that, callbackfn, aLen, memo, isRight) { aFunction(callbackfn); var O = toObject(that); var self = IObject(O); var length = toLength(O.length); var index = isRight ? length - 1 : 0; var i = isRight ? -1 : 1; if (aLen < 2) for (;;) { if (index in self) { memo = self[index]; index += i; break; } index += i; if (isRight ? index < 0 : length <= index) { throw TypeError('Reduce of empty array with no initial value'); } } for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { memo = callbackfn(memo, self[index], index, O); } return memo; }; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(74); module.exports = __webpack_require__(7).Array.isArray; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = __webpack_require__(5); $export($export.S, 'Array', { isArray: __webpack_require__(64) }); /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(76); module.exports = __webpack_require__(7).Array.some; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $export = __webpack_require__(5); var $some = __webpack_require__(61)(3); $export($export.P + $export.F * !__webpack_require__(58)([].some, true), 'Array', { // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn /* , thisArg */) { return $some(this, callbackfn, arguments[1]); } }); /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(78); __webpack_require__(85); module.exports = __webpack_require__(7).Array.from; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__(79)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(80)(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(32); var defined = __webpack_require__(27); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(36); var $export = __webpack_require__(5); var redefine = __webpack_require__(18); var hide = __webpack_require__(8); var Iterators = __webpack_require__(81); var $iterCreate = __webpack_require__(82); var setToStringTag = __webpack_require__(83); var getPrototypeOf = __webpack_require__(84); var ITERATOR = __webpack_require__(65)('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 = $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 && typeof IteratorPrototype[ITERATOR] != 'function') 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; }; /***/ }), /* 81 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__(46); var descriptor = __webpack_require__(17); var setToStringTag = __webpack_require__(83); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(8)(IteratorPrototype, __webpack_require__(65)('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(9).f; var has = __webpack_require__(19); var TAG = __webpack_require__(65)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(19); var toObject = __webpack_require__(52); var IE_PROTO = __webpack_require__(34)('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; }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ctx = __webpack_require__(21); var $export = __webpack_require__(5); var toObject = __webpack_require__(52); var call = __webpack_require__(86); var isArrayIter = __webpack_require__(87); var toLength = __webpack_require__(31); var createProperty = __webpack_require__(88); var getIterFn = __webpack_require__(89); $export($export.S + $export.F * !__webpack_require__(91)(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; } }); /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(10); 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; } }; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(81); var ITERATOR = __webpack_require__(65)('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $defineProperty = __webpack_require__(9); var createDesc = __webpack_require__(17); module.exports = function (object, index, value) { if (index in object) $defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(90); var ITERATOR = __webpack_require__(65)('iterator'); var Iterators = __webpack_require__(81); module.exports = __webpack_require__(7).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(26); var TAG = __webpack_require__(65)('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; }; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(65)('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; }; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(93); __webpack_require__(96); __webpack_require__(99); __webpack_require__(77); __webpack_require__(101); __webpack_require__(104); __webpack_require__(106); __webpack_require__(108); __webpack_require__(110); __webpack_require__(112); __webpack_require__(114); // Polyfill added for HTML elements of IE11 if (!Element.prototype.remove) { Element.prototype.remove = function () { this.parentNode && this.parentNode.removeChild(this); }; } /* eslint no-extend-native: "off" */ /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(94); module.exports = __webpack_require__(7).Math.sign; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { // 20.2.2.28 Math.sign(x) var $export = __webpack_require__(5); $export($export.S, 'Math', { sign: __webpack_require__(95) }); /***/ }), /* 95 */ /***/ (function(module, exports) { // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x) { // eslint-disable-next-line no-self-compare return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(97); module.exports = __webpack_require__(7).Array.findIndex; /***/ }), /* 97 */ /***/ (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__(61)(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__(98)(KEY); /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = __webpack_require__(65)('unscopables'); var ArrayProto = Array.prototype; if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(8)(ArrayProto, UNSCOPABLES, {}); module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(100); module.exports = __webpack_require__(7).Array.find; /***/ }), /* 100 */ /***/ (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__(61)(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__(98)(KEY); /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(102); module.exports = __webpack_require__(7).Array.fill; /***/ }), /* 102 */ /***/ (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__(103) }); __webpack_require__(98)('fill'); /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var toObject = __webpack_require__(52); var toAbsoluteIndex = __webpack_require__(33); var toLength = __webpack_require__(31); module.exports = function fill(value /* , start = 0, end = @length */) { var O = toObject(this); var length = toLength(O.length); var aLen = arguments.length; var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); var end = aLen > 2 ? arguments[2] : undefined; var endPos = end === undefined ? length : toAbsoluteIndex(end, length); while (endPos > index) O[index++] = value; return O; }; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(105); module.exports = __webpack_require__(7).Array.includes; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/Array.prototype.includes var $export = __webpack_require__(5); var $includes = __webpack_require__(30)(true); $export($export.P, 'Array', { includes: function includes(el /* , fromIndex = 0 */) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(98)('includes'); /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(107); module.exports = Math.pow(2, -52); /***/ }), /* 107 */ /***/ (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) }); /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(109); module.exports = -0x1fffffffffffff; /***/ }), /* 109 */ /***/ (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 }); /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(111); module.exports = 0x1fffffffffffff; /***/ }), /* 111 */ /***/ (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 }); /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(113); module.exports = __webpack_require__(7).Number.isFinite; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { // 20.1.2.2 Number.isFinite(number) var $export = __webpack_require__(5); var _isFinite = __webpack_require__(6).isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it) { return typeof it == 'number' && _isFinite(it); } }); /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(115); module.exports = __webpack_require__(7).Number.isNaN; /***/ }), /* 115 */ /***/ (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; } }); /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate, global) {!function(e,n){ true?n():undefined}(0,function(){"use strict";function e(){}function n(e){if(!(this instanceof n))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=undefined,this._deferreds=[],f(e,this)}function t(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,n._immediateFn(function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var i;try{i=n(e._value)}catch(f){return void r(t.promise,f)}o(t.promise,i)}else(1===e._state?o:r)(t.promise,e._value)})):e._deferreds.push(t)}function o(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var o=t.then;if(t instanceof n)return e._state=3,e._value=t,void i(e);if("function"==typeof o)return void f(function(e,n){return function(){e.apply(n,arguments)}}(o,t),e)}e._state=1,e._value=t,i(e)}catch(u){r(e,u)}}function r(e,n){e._state=2,e._value=n,i(e)}function i(e){2===e._state&&0===e._deferreds.length&&n._immediateFn(function(){e._handled||n._unhandledRejectionFn(e._value)});for(var o=0,r=e._deferreds.length;r>o;o++)t(e,e._deferreds[o]);e._deferreds=null}function f(e,n){var t=!1;try{e(function(e){t||(t=!0,o(n,e))},function(e){t||(t=!0,r(n,e))})}catch(i){if(t)return;t=!0,r(n,i)}}var u=setTimeout;n.prototype["catch"]=function(e){return this.then(null,e)},n.prototype.then=function(n,o){var r=new this.constructor(e);return t(this,new function(e,n,t){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof n?n:null,this.promise=t}(n,o,r)),r},n.prototype["finally"]=function(e){var n=this.constructor;return this.then(function(t){return n.resolve(e()).then(function(){return t})},function(t){return n.resolve(e()).then(function(){return n.reject(t)})})},n.all=function(e){return new n(function(n,t){function o(e,f){try{if(f&&("object"==typeof f||"function"==typeof f)){var u=f.then;if("function"==typeof u)return void u.call(f,function(n){o(e,n)},t)}r[e]=f,0==--i&&n(r)}catch(c){t(c)}}if(!e||"undefined"==typeof e.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(e);if(0===r.length)return n([]);for(var i=r.length,f=0;r.length>f;f++)o(f,r[f])})},n.resolve=function(e){return e&&"object"==typeof e&&e.constructor===n?e:new n(function(n){n(e)})},n.reject=function(e){return new n(function(n,t){t(e)})},n.race=function(e){return new n(function(n,t){for(var o=0,r=e.length;r>o;o++)e[o].then(n,t)})},n._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){u(e,0)},n._unhandledRejectionFn=function(e){void 0!==console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var c=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();c.Promise||(c.Promise=n)}); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(117).setImmediate, __webpack_require__(118))) /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || (typeof self !== "undefined" && self) || window; var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(scope, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(119); // On some exotic environments, it's not clear which object `setimmediate` was // able to install onto. Search each possibility in the same order as the // `setimmediate` library. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || (typeof global !== "undefined" && global.setImmediate) || (this && this.setImmediate); exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || (typeof global !== "undefined" && global.clearImmediate) || (this && this.clearImmediate); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(118))) /***/ }), /* 118 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1, eval)("this"); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a * * *
Chart loads here...
* * */ (0, _eventApi.triggerEvent)('ready', FusionCharts, { version: FusionCharts.version, // now: !wasReady now: true }); // readyNow = !wasReady; }, 1); }, slHandler = function slHandler() { FusionCharts.removeEventListener('initialized', slHandler); smartLabelManager = new _SmartlabelManager2['default'](document.body || document.getElementsByTagName('body')[0]); _createChart.globalStore.addToEnv('smartLabel', smartLabelManager); }; function getStateForDep() { return this.state; } function getMsgForDep() { return this.msg; } function getMsgStyleForDep() { return this.msgStyle; } function uniqueId() { return 'chartobject-' + (uniqueId.lastId += 1); } uniqueId.lastId = 0; /** * This method creates a clone object with all property names in lower case. This doesn't work for * nested object properties. * @param {Object} obj Object with all string type property value only * @return {Object} Cloned object. */ function objToLowerCase(obj) { var clone = {}, i = void 0; for (i in obj) { clone[i.toLowerCase()] = obj[i]; } return clone; } /** * Objects mapped to a hash key will only have string type value for all properties * @param {Object} obj Object with all string type property value only * @return {string} Derived hash key from the object */ function objToHash(obj) { var hashArr = [], i = void 0; for (i in obj) { hashArr.push(i + '_' + obj[i]); } hashArr.sort(); return hashArr.join(','); } // Deconstruct policies and update the arguments with latest copy of all variables by reverse // engineering the policies. function deconstructPolicySet(policies, options, obj) { var policy, prop; for (policy in policies) { // Set just the policy object in case of single-level policy. if (policies[policy] instanceof Array) { options[policies[policy][0]] = obj[policy]; } else { // Copy the source of multi-level policies for (prop in policies[policy]) { options[policies[policy][prop][0]] = obj[policy][prop]; } } } } /** * Parses the arguments of the chart data update call * * @param {Object} data The data that was supplied * @param {string | Object} jsonData The json data used by charts internally * @param {string} format The format of teh data given * @param {boolean} silent Indicates whether the updation of data whould raise events or not * @return {Object} The parsed arguments */ function _getParsedArgs(data, jsonData, format, silent) { var parsedArgs = {}; // Updated the result so that it can be passed as event argument. // Closure compiler gives error when using obj.native. Hence using // different notation. parsedArgs['native'] = format === NATIVE_FORMAT; // the data format given by the user parsedArgs.dataFormat = format; // the native format used by us parsedArgs.format = NATIVE_FORMAT; // the data used internally parsedArgs.data = jsonData; // the data given by the user parsedArgs.dataSource = data; // Save the silent instruction to arguments parsedArgs.silent = !!silent; return parsedArgs; } /** * Function to determine the script base uri for a script name */ function getScriptBaseUri(scriptNameRegex) { // Get a collection of all script nodes. var scripts = window.document.getElementsByTagName('script'), l = scripts.length, src, i; // Iterate through the script node collection and match whether its 'src' // attribute contains fusioncharts file name. for (i = 0; i < l; i += 1) { src = scripts[i].getAttribute('src'); if (!(typeof src === 'undefined' || src === null || src.match(scriptNameRegex) === null)) { return src.replace(scriptNameRegex, '$1'); } } } // Function that checks duplicate id in page. function isDuplicateId(lookupId, container) { // Get the lookup element from the ID sent via parameter. var lookupElement = document.getElementById(lookupId), // Get the ID of the container element. containerId = container.id || container.getAttribute('id'), children, i, ii; // Check whether the element exists or not. If it does not exist, it // implies that there cannot be any duplicate. if (lookupElement === null) { return false; } // In case chart's Id and container's Id is same then is duplicate. if (lookupId === containerId) { return true; } // Check whether the lookup element returned before is actually // inside container or not. children = container.getElementsByTagName('*'); for (i = 0, ii = children.length; i < ii; i++) { if (children[i] === lookupElement) { return false; } } // If the lookupElement is outside/before the container, it implies // that it is a duplicate. return true; } /** * Function that safely deletes all items in a DOM element. */ function purgeDOM(d) { var a = d.attributes, i, l, n; if (a) { for (i = a.length - 1; i >= 0; i -= 1) { n = a[i].name; if (typeof d[n] === 'function') { d[n] = null; } } } a = d.childNodes; if (a) { l = a.length; for (i = 0; i < l; i += 1) { purgeDOM(d.childNodes[i]); } } } function getdataLoadStartMessage(chartObj) { var chartOptions = chartObj.options, args = chartObj.args, image = void 0, message = void 0; image = { imageHAlign: (0, _lib.pluck)(args.dataLoadStartMessageImageHAlign, chartOptions.baseChartMessageImageHAlign).toLowerCase(), imageVAlign: (0, _lib.pluck)(args.dataLoadStartMessageImageVAlign, chartOptions.baseChartMessageImageVAlign).toLowerCase(), imageAlpha: (0, _lib.pluckNumber)(args.dataLoadStartMessageImageAlpha, chartOptions.baseChartMessageImageAlpha), imageScale: (0, _lib.pluckNumber)(args.dataLoadStartMessageImageScale, chartOptions.baseChartMessageImageScale) }; message = { fontFamily: args.dataLoadStartMessageFont || chartOptions.baseChartMessageFont, fontSize: args.dataLoadStartMessageFontSize || chartOptions.baseChartMessageFontSize, color: args.dataLoadStartMessageColor || chartOptions.baseChartMessageColor }; return { msg: chartOptions.dataLoadStartMessage, msgStyle: { image: image, message: message } }; } function getDataInvalidMessage(chartObj) { var chartOptions = chartObj.options, args = chartObj.args, image = void 0, message = void 0; // Set image as chart message styling image = { imageHAlign: (0, _lib.pluck)(args.dataInvalidMessageImageHAlign, chartOptions.baseChartMessageImageHAlign).toLowerCase(), imageVAlign: (0, _lib.pluck)(args.dataInvalidMessageImageVAlign, chartOptions.baseChartMessageImageVAlign).toLowerCase(), imageAlpha: (0, _lib.pluckNumber)(args.dataInvalidMessageImageAlpha, chartOptions.baseChartMessageImageAlpha), imageScale: (0, _lib.pluckNumber)(args.dataInvalidMessageImageScale, chartOptions.baseChartMessageImageScale) }; message = { fontFamily: args.dataInvalidMessageFont || chartOptions.baseChartMessageFont, fontSize: args.dataInvalidMessageFontSize || chartOptions.baseChartMessageFontSize, color: args.dataInvalidMessageColor || chartOptions.baseChartMessageColor }; return { msg: chartOptions.dataInvalidMessage, msgStyle: { image: image, message: message } }; } function getLoadChartMessage(chartObj) { var options = chartObj.options, args = chartObj.args, showChartLoadingMessage = chartObj.options.showChartLoadingMessage, image = void 0, message = void 0; // Set image as chart message styling image = { imageHAlign: args.loadMessageImageHAlign || options.baseChartMessageImageHAlign, imageVAlign: args.loadMessageImageVAlign || options.baseChartMessageImageVAlign, imageAlpha: args.loadMessageImageAlpha || options.baseChartMessageImageAlpha, imageScale: args.loadMessageImageScale || options.baseChartMessageImageScale }; // Set chart message styling for loading message message = { color: args.loadMessageColor || options.baseChartMessageColor, fontFamily: args.loadMessageFont || options.baseChartMessageFont, fontSize: args.loadMessageFontSize || options.baseChartMessageFontSize }; // Get chart loading message return { msg: showChartLoadingMessage ? options.PBarLoadingText || options.loadMessage : '', msgStyle: { message: message, image: image } }; } /** * Function to display chart not supported message */ function showUnsupportedChartMessage(chartObj) { var args = chartObj.args, options = chartObj.options, image, message; // Set image as chart message styling image = { imageHAlign: args.typeNotSupportedMessageImageHAlign || options.baseChartMessageImageHAlign, imageVAlign: args.typeNotSupportedMessageImageVAlign || options.baseChartMessageImageVAlign, imageAlpha: args.typeNotSupportedMessageImageAlpha || options.baseChartMessageImageAlpha, imageScale: args.typeNotSupportedMessageImageScale || options.baseChartMessageImageScale }; // Set chart message styling for chart type not supported message = { color: args.typeNotSupportedMessageColor || options.baseChartMessageColor, fontFamily: args.typeNotSupportedMessageFont || options.baseChartMessageFont, fontSize: args.typeNotSupportedMessageFontSize || options.baseChartMessageFontSize }; if (registerError) { options.messageURL = docLink; } return { msg: registerError ? registerErrorMessage : options.typeNotSupportedMessage, msgStyle: { image: image, message: message } }; } /** * Function to display chart not supported message */ function showUnsupportedBrowserMessage(chartObj) { var args = chartObj.args, options = chartObj.options, image, message; // Set image as chart message styling image = { imageHAlign: args.browserNotSupportedMessageImageHAlign || options.baseChartMessageImageHAlign, imageVAlign: args.browserNotSupportedMessageImageVAlign || options.baseChartMessageImageVAlign, imageAlpha: args.browserNotSupportedMessageImageAlpha || options.baseChartMessageImageAlpha, imageScale: args.browserNotSupportedMessageImageScale || options.baseChartMessageImageScale }; // Set chart message styling for chart type not supported message = { color: args.browserNotSupportedMessageColor || options.baseChartMessageColor, fontFamily: args.browserNotSupportedMessageFont || options.baseChartMessageFont, fontSize: args.browserNotSupportedMessageFontSize || options.baseChartMessageFontSize }; return { msg: options.browserNotSupportedMessage, msgStyle: { image: image, message: message } }; } function registerEvtHandler() { registerError = true; } /** * handles chart data fetching */ function _setChartData(_scope) { var _opts = this.opts, data = _opts.data, sanitisedFormat = _opts.sanitisedFormat, silent = _opts.silent, dataFormats = (0, _dependencyManager.getDepsByType)('transcoder'), transcoderObj = dataFormats[sanitisedFormat] && dataFormats[sanitisedFormat](), chartOptions = _scope.options, jsonData = void 0, dataComp = void 0, parseArgs = void 0, _getDataInvalidMessag = getDataInvalidMessage(_scope), msg = _getDataInvalidMessag.msg, msgStyle = _getDataInvalidMessag.msgStyle, status = void 0; _scope.__state.newDataArrived = true; if (transcoderObj) { if (transcoderObj.toJSON) { dataComp = transcoderObj.toJSON(data, _scope); status = dataComp.error ? { state: 1, msg: msg, msgStyle: msgStyle } : { state: 3 }; } else { dataComp = { error: new Error('Unable to convert data.') }; status = { state: 1, msg: msg, msgStyle: msgStyle }; } } else { dataComp = { error: new Error('Unable to convert data.') }; status = { state: 1, msg: msg, msgStyle: msgStyle }; } jsonData = dataComp.error ? dataComp : dataComp.data; chartOptions.dataErroneous = chartOptions.error = dataComp.error; chartOptions.dataSource = jsonData; chartOptions.dataFormat = sanitisedFormat; parseArgs = _getParsedArgs(data, jsonData, sanitisedFormat, silent); if (!chartOptions.dataErroneous) { (0, _eventApi.triggerEvent)('beforeDataUpdate', _scope, parseArgs, void 0, _updater.onDataUpdateSuccess, _updater.onDataUpdateCancel); } return status; } /** * handles chart url fetching */ function _setChartDataUrl(_scope) { var _opts2 = this.opts, _opts2$url = _opts2.url, url = _opts2$url === undefined ? '' : _opts2$url, format = _opts2.format, config = _opts2.config, callback = _opts2.callback, silent = _opts2.silent, dataFormats = (0, _dependencyManager.getDepsByType)('transcoder'), sanitisedFormat = void 0, _getdataLoadStartMess = getdataLoadStartMessage(_scope), msg = _getdataLoadStartMess.msg, msgStyle = _getdataLoadStartMess.msgStyle, transcoderObj = void 0; if (typeof format === 'undefined' || format === null || typeof format.toString !== 'function') { format = _scope.options.dataFormat; /** * When an invalid data format has been passed to {@link FusionCharts#setChartDataUrl} or * other data-url-setter functions, this warnig is raised. The chart continues to use the last * used data format in this situation. Ensure that you are using one of the data `url` * prefixed formats specified in {@link FusionCharts~dataFormats}. * * @typedef {ParameterException} Warning-03091609 * @memberOf FusionCharts.debugger * @group debugger-warning */ (0, _eventApi.raiseWarning)(_scope, '03091609', 'param', 'FusionCharts#setChartDataUrl', 'Invalid Data Format. Reverting to current data format - ' + format); } sanitisedFormat = sanitiseFormatStr(format); if (!URL_RE.test(sanitisedFormat)) { sanitisedFormat += 'url'; } transcoderObj = dataFormats[sanitisedFormat] && dataFormats[sanitisedFormat](); _scope.jsVars.stallLoad = true; if (transcoderObj) { if (transcoderObj.toJSON) { transcoderObj.toJSON(url, config, callback, silent, _scope); return { state: 2, msg: msg, msgStyle: msgStyle }; } else { return { state: 1, error: new Error('Unable to fetch data.') }; } } else { return { state: 1, error: new Error('Unable to fetch data.') }; } } function onChartTypeChange(_scope) { var state = _scope.__state, chartType = _scope.chartType(), lastRenderedChart = void 0, eiMethod = void 0, prevChartDefinition = (0, _dependencyManager.getDep)(state.lastRenderedType, 'chartapi') || (0, _dependencyManager.getDep)(state.lastRenderedType, 'maps'); // Delete the external interface methods of the last rendered chart if its type was // different than the current chart type. if (prevChartDefinition && state.lastRenderedType !== chartType) { /** * This event is fired when a change in chart type is triggered by calling * {@link FusionCharts#chartType} on a chart. The event is raised only when the chart * type has been explicitly changed from what was set earlier. * * This event is *not* fired when: * * - A chart is rendered using {@link FusionCharts.render}. * - A chart type is set for the first time on a chart, even using * {@link FusionCharts#chartType}. For example, if no `type` option is provided to * the FusionCharts constructor when creating the chart, and later on * {@link FusionCharts#chartType} is called on that chart instance for the first * time, this event is not triggered. * - If the chart type parameter sent to {@link FusionCharts#chartType} is the same as * the current chart type. * - If the new chart type provided is invalid. * * @see FusionCharts#chartType * * @event FusionCharts#chartTypeChanged * @group chart * * @param {string} previousType - The previously assigned chart type of the chart. * @param {string} newType - The new chart type that has been set on the chart. */ (0, _eventApi.triggerEvent)('chartTypeChanged', _scope, { previousType: state.lastRenderedType, newType: chartType }); lastRenderedChart = prevChartDefinition; if (lastRenderedChart) { for (eiMethod in lastRenderedChart) { delete _scope[eiMethod]; } } } // Updated last-rendererd type to current type. state.lastRenderedType = chartType; } function mapResolver(_scope) { var _getLoadChartMessage = getLoadChartMessage(_scope), msgStyle = _getLoadChartMessage.msgStyle, msg = _getLoadChartMessage.msg; Promise.all(/* import() | fusioncharts.maps */[__webpack_require__.e(2), __webpack_require__.e(13)]).then(__webpack_require__.t.bind(null, 1106, 7)).then(function (mapModule) { FusionCharts.addDep(mapModule['default']); onChartTypeChange(_scope); _scope._addChartDependency('mapModuleLoad', { resolve: function resolve() { return { state: 3 }; } }); /** * The `loaded` event is raised when the chart has finished downloading itself in the client * environment. * This event indicates that the all the resources required to render the chart are ready and the * chart can be drawn. * You can use this event to hide any loader components that you might have on your page. * @event FusionCharts#loaded * @param { string } type This is the type of chart that is being rendered. */ (0, _eventApi.triggerEvent)('loaded', _scope, { type: _scope.chartType(), renderer: 'javascript' }, [_scope.id]); _scope._setState(); })['catch'](function () { var _showUnsupportedChart = showUnsupportedChartMessage(_scope), msgStyle = _showUnsupportedChart.msgStyle, msg = _showUnsupportedChart.msg; _scope._addChartDependency('mapModuleLoad', { resolve: function resolve() { return { state: 1, msgStyle: msgStyle, msg: msg }; } }); (0, _eventApi.raiseError)(FusionCharts, '12052314141', 'run', 'JavaScriptRenderer~Maps', new Error('FusionCharts\' maps file is required to render the visualization.')); _scope._setState(); /** * whenever the chartType is invalid this event is fired */ (0, _eventApi.triggerEvent)('charttypeinvalid', _scope, {}, [_scope.id]); }); return { state: 2, msgStyle: msgStyle, msg: msg }; } function handleChartModuleLoading(_scope) { var chartType = this.opts.value, fileLoadPromise = FusionCharts.getDep(chartType, 'dependency') || FusionCharts.getDep(chartType, 'chartapi') || FusionCharts.getDep(chartType, 'maps'); registerError = false; if (fileLoadPromise) { if (fileLoadPromise.then) { FusionCharts.addEventListener('register', registerEvtHandler); fileLoadPromise.then(function (module) { if (_scope.disposed) { return; } if (module.__esModule) { var isMapsAPI = (0, _dependencyManager.getDep)(chartType, 'maps'); FusionCharts.addDep(module['default']); !(isMapsAPI && MAP_NEEDED) && onChartTypeChange(_scope); _scope._addChartDependency('chartModuleLoad', { resolve: function resolve() { if (isMapsAPI && MAP_NEEDED) { _scope._addChartDependency('mapModuleLoad', { scopeOf: _scope, resolve: mapResolver }); } else { /** * The `loaded` event is raised when the chart has finished downloading itself in the client * environment. * This event indicates that the all the resources required to render the chart are ready and the * chart can be drawn. * You can use this event to hide any loader components that you might have on your page. * @event FusionCharts#loaded * @param { string } type This is the type of chart that is being rendered. */ (0, _eventApi.triggerEvent)('loaded', _scope, { type: chartType, renderer: 'javascript' }, [_scope.id]); } return { state: 3 }; } }); } else { _scope._addChartDependency('chartModuleLoad', { resolve: function resolve() { if ((0, _dependencyManager.getDep)(chartType, 'maps') && MAP_NEEDED) { _scope._addChartDependency('mapModuleLoad', { scopeOf: _scope, resolve: mapResolver }); } else { onChartTypeChange(_scope); /** * The `loaded` event is raised when the chart has finished downloading itself in the client * environment. * This event indicates that the all the resources required to render the chart are ready and the * chart can be drawn. * You can use this event to hide any loader components that you might have on your page. * @event FusionCharts#loaded * @param { string } type This is the type of chart that is being rendered. */ (0, _eventApi.triggerEvent)('loaded', _scope, { type: chartType, renderer: 'javascript' }, [_scope.id]); } return { state: 3 }; } }); } _scope._setState(); })['catch'](function () { if (_scope.disposed) { return; } var _showUnsupportedChart2 = showUnsupportedChartMessage(_scope), msgStyle = _showUnsupportedChart2.msgStyle, msg = _showUnsupportedChart2.msg; _scope._addChartDependency('chartModuleLoad', { resolve: function resolve() { return { state: 1, msgStyle: msgStyle, msg: msg }; } }); _scope._setState(); /** * whenever the chartType is invalid this event is fired */ (0, _eventApi.triggerEvent)('charttypeinvalid', _scope, {}, [_scope.id]); }); var _getLoadChartMessage2 = getLoadChartMessage(_scope), msgStyle = _getLoadChartMessage2.msgStyle, msg = _getLoadChartMessage2.msg; return { state: 2, msgStyle: msgStyle, msg: msg }; } else { if ((0, _dependencyManager.getDep)(chartType, 'maps') && MAP_NEEDED) { _scope._addChartDependency('mapModuleLoad', { scopeOf: _scope, resolve: mapResolver }); _scope._setState(); } else { onChartTypeChange(_scope); /** * The `loaded` event is raised when the chart has finished downloading itself in the client * environment. * This event indicates that the all the resources required to render the chart are ready and the * chart can be drawn. * You can use this event to hide any loader components that you might have on your page. * @event FusionCharts#loaded * @param { string } type This is the type of chart that is being rendered. */ (0, _eventApi.triggerEvent)('loaded', _scope, { type: chartType, renderer: 'javascript' }, [_scope.id]); } return { state: 3 }; } } else { var _showUnsupportedChart3 = showUnsupportedChartMessage(_scope), _msgStyle = _showUnsupportedChart3.msgStyle, _msg = _showUnsupportedChart3.msg; /** * whenever the chartType is invalid this event is fired */ (0, _eventApi.triggerEvent)('charttypeinvalid', this, {}, [this.id]); return { state: 1, msgStyle: _msgStyle, msg: _msg }; } } function handleRender(_scope) { var _opts3 = this.opts, containerElement = _opts3.containerElement, insertMode = _opts3.insertMode, callback = _opts3.callback, alt = void 0, ref = void 0, size = void 0, s = void 0; // Validate parameters for retrieving callback. The last parameter can be a callback if (!callback) { if (typeof insertMode === 'function') { callback = insertMode; insertMode = void 0; } else if (!insertMode && typeof containerElement === 'function') { callback = containerElement; containerElement = void 0; } } else if (typeof callback !== 'function') { callback = void 0; } // Create a blank element inside to mimic alternativecontent insertMode = (insertMode || _scope.options.insertMode).toLowerCase() || _lib.domInsertModes.REPLACE; // Procure containerElement from internal object options that has // been passed via parameters. if (typeof containerElement === 'undefined') { containerElement = _scope.options.containerElementId || _scope.options.containerElement; } // In case user sends the element id, we get the object from it if (typeof containerElement === 'string') { containerElement = document.getElementById(containerElement); } if (typeof containerElement === 'undefined' || containerElement === null) { /** * FusionCharts could not find the container DOM element while rendering chart. Ensure that a * DOM element exists which has an `id` attribute same as the one provided in `renderAt` * construction parameter or when passed to the {@link FusionCharts#render} function. * * @typedef {CompilationException} Error-03091456 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(_scope, '03091456', 'run', '.render()', new Error('Unable to find the container DOM element.')); (0, _eventApi.triggerEvent)('containernotfound', _scope, {}, [_scope.id]); return { state: 1 }; } // Check duplicate rendering with same id if (isDuplicateId(_scope.id, containerElement)) { /** * The `id` of the container element provided has more than one element with the same id. This * would cause problems in referring to the correct chart during its operation. * * Ensure that no other DOM element exists on the page with the same `id` attribute as of the * container element where the chart is supposed to be rendered. * * @typedef {CompilationException} Error-05102109 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(_scope, '05102109', 'run', '.render()', new Error('A duplicate object already exists with the specific Id: ' + _scope.id)); return { state: 1 }; } // In case of chart container is hidden, perform interval based tracking // And call the render function as soon as container gets visible if (isHidden(containerElement)) { _scope.containerHidden = true; handleContainerVisibility(_scope, containerElement, insertMode, callback); return { state: 2 }; } else { delete _scope.containerHidden; } // Dispose the renderer in case of re-render. This checks whether there // is any previous DOM element in case the chart is re-rendered and // correspondingly deletes it. (B#565) if ((ref = window[_scope.id]) && ref.FusionCharts && ref.FusionCharts === _scope || (ref = _scope.ref) && ref.FusionCharts && ref.FusionCharts === _scope) { _scope._dispose(); // For some browsers, the DOM element reference is still retained // in window scope and that has to be cleared. if (ref === window[_scope.id]) { window[_scope.id] = void 0; } } // Check IE-Safe variable name collision within Global Scope if (typeof window[_scope.id] !== 'undefined') { /** * FusionCharts raises this error to ensure that the charts function reliably on older * Internet Explorer browsers (IE 8 and below.) Ensure that you have unique name for your * chart id and that it does not correspond to any global variable, DOM element id or frame * name. * * @typedef {CompilationException} Error-25081843 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(_scope, '25081843', 'comp', '.render', new Error('#25081843:IECompatibility() Chart Id is same as a JavaScript variable name. ' + 'Variable naming error. Please use unique name for chart JS variable, chart-id and ' + 'container id.')); return { state: 1 }; } // Set the attribute of this element that will be replaced by swfobject alt = document.createElement(_scope.options.containerElementType || 'span'); alt.setAttribute('id', _scope.id); // Clear the contents of the containerElement and subsequently // append the new alt content. if (insertMode !== 'append' && insertMode !== 'prepend') { while (containerElement.hasChildNodes()) { containerElement.removeChild(containerElement.firstChild); } } // Check whether we are to prepend this item or append. if (insertMode === 'prepend' && containerElement.firstChild) { containerElement.insertBefore(alt, containerElement.firstChild); } else { containerElement.appendChild(alt); } // Update the present container details in object. _scope.options.containerElement = containerElement; _scope.options.containerElementId = containerElement.id; // Set the chart element style property to make it display as an // inline-block element. if (s = alt.style) { s.position = 'relative'; s.textAlign = 'left'; s.lineHeight = 'normal'; s.display = 'inline-block'; s.zoom = '1'; s['vertical-align'] = 'middle'; s.fontWeight = 'normal'; s.fontVariant = 'normal'; s.fontStyle = 'normal'; s.textDecoration = 'none'; s['*DISPLAY'] = 'inline'; s.padding = '0'; s.margin = '0'; s.border = 'none'; s.direction = 'ltr'; } _scope.options.containerClassName && (alt.className = _scope.options.containerClassName); // Fix percentage width issues size = (0, _lib.normalizeCSSDimension)(_scope.width, _scope.height, alt); // Record the render-time dimensions within state. This will be used // for reference calculations wrt original render-time dimensions in // other modules (such as annotations.) _scope.__state.renderedWidth = size.pixelWidth; _scope.__state.renderedHeight = size.pixelHeight; // Set state that the chart is rendering _scope.__state.rendering = true; // If the container is visible call then we can call render function _scope.renderOpts = { containerElement: alt, insertMode: insertMode, callback: callback }; return { state: 3 }; } /** * Create new instances of charts, gauges and maps using this function. * * The preferred way to draw charts, gauges and maps using FusionCharts is to pass the chart * configurations and data to this constructor and call `render()` on the returned instance. You * can provide all the properties, data and event bindings of charts through the parameters passed * to this function. * * You can call methods of the {@link FusionCharts} class on the returned instance. For all * practical purposes, this is the first step to creating a chart, gauges and maps using * FusionCharts. * * __Accessing existing charts using `FusionCharts()` constructor:__ * * The `FusionCharts` function has a dual behavior - other than creating new charts, it can also be * used to access already created charts. This is done by dropping the `new` operator and passing * only the chart `id` as a parameter. For example, `var salesChart = FusionCharts('sales-chart');` * will return the instance of the chart with the `id` "sales-chart". The previous code snippet is * equivalent to `var salesChart = FusionCharts.items['sales-chart'];`. Refer to * {@link FusionCharts.items} to know more. * * @class * @global * * @param {Object} options - While creating a new instance of FusionCharts, you can pass an * `options` object with all configuration parameters for that instance. All configurations passed * through this object are referred to as "construction parameters". Through these parameters, you * can customize the look and feel of a chart, pass data to the chart, configure its dimensions and * bind to events. * * Each of this object's properties correspond to a configuration option. * * @param {!string} [options.type] - Provide the name of the chart type to be rendered. Full list of * charts is available at {@tutorial setup-list-of-charts}. * * This parameter controls what chart will be rendered. The data passed to the chart has to be * compatible with the chart type specified here. * * Alternatively, you can also call {@link FusionCharts#chartType} on the chart instance to provide * the chart type. * * @param {!string} [options.id] - This name is used to refer to the current instance after the * chart has been created. The chart instance is available under this name in * {@link FusionCharts.items}. If no `id` is provided, FusionCharts automatically generates an `id` * for each chart. * * @param {numeric|percent} [options.width="400"] - Set the width in pixels or percent such as `640` * or `'50%'`. If width is in pixels, there is no need to provide the `px` unit suffix. You can call * {@link FusionCharts#resizeTo} function on the chart instance to set the width later on. * * @param {numeric|percent} [options.height="300"] - Set the height in pixels or percent such as * `640` or `'50%'`. If height is in pixels, there is no need to provide the `px` unit suffix. You * can call {@link FusionCharts#resizeTo} function on the chart instance to set the height later on. * * @param {string|DOMElement} [options.renderAt] - A chart needs reference to a DOM element on the * page where it will be rendered. You can provide the HTML ID of the element as a string to this * option, or you can pass a reference of the DOMElement itself where the chart needs to be * rendered. * * For example, if you have a DOMElement like `
`, * you can provide the value of the `div`'s `id` attribute to this option as a string. * Alternatively, you can pass direct reference to the DOMElement like: * `renderAt: document.getElementByClassName("chart-1")`. * * Instead of providing the DOMElement here, it can also be passed as the first parameter to the * {@link FusionCharts.render} function. Setting the DOMElement in {@link FusionCharts.render} * function overrides the value set here. * * @param {FusionCharts~dataFormats} [options.dataFormat] - This is the name of the format of data * passed to the `dataSource` option below. Currently, FusionCharts accepts only JSON and XML data. * The value for this option is one of the formats specified in {@link FusionCharts~dataFormats}. * * @param {string|object} [options.dataSource] - Provide the source of data and configuration of the * chart. FusionCharts accepts data in the formats specified in {@link FusionCharts~dataFormats}. * * This is the preferred way to set data and configuration of the chart. The data and configuration * can also be updated or set using the functions {@link FusionCharts#setChartData} and * {@link FusionCharts#setChartDataUrl}. * * @param {Object} [options.events] - You can bind multiple events to this particular chart instance * through this option. You need to pass an object to this option, where each key is an event name * fired by FusionCharts and value for that key is a callback in the format of * {@link FusionCharts~eventListener}. * * To bind multiple charts to the same event, you need to use {@link FusionCharts#addEventListener} * function instead. * * @param {Object} [options.link] - Provide LinkedCharts configuration. See * {@link FusionCharts#configureLink} for details. * * @param {boolean} [options.showDataLoadingMessage=false] - FusionCharts shows a message while it * is retrieving data from a `url` provided as `dataSource`. While displaying the message the chart * is grayed out and interaction on it is blocked. This can be prevented by setting this option to * `false`. * * @param {boolean} [options.showChartLoadingMessage=true] - Shows `Loading chart...` message in * `renderAt` container if the chart needs to load additional resource/JS files. This can be turned * off by setting this option to `false`. * * @param {string} [options.baseChartMessageFont='Verdana'] - Allows to set the common custom font * face for all chart messages. * * @param {string} [options.baseChartMessageFontSize='10'] - Allows to set the common custom font * size for all chart messages. * * @param {hexcolor} [options.baseChartMessageColor='#666666'] - Allows to set the common custom * font color for all chart messages. * * @param {string} [options.baseChartMessageImageHAlign='middle'] - Allows to set the common custom * horizontal alignment for all image as chart messages. * * @param {string} [options.baseChartMessageImageVAlign='middle'] - Allows to set the common custom * vertical alignment for all image as chart messages. * * @param {string} [options.baseChartMessageImageAlpha='100'] - Allows to set the common custom * alpha for all image as chart messages. * * @param {string} [options.baseChartMessageImageScale='100'] - Allows to set the common custom * scaling for all image as chart messages. * * @param {string} [options.dataLoadStartMessage='Retrieving data. Please wait.'] - Allows to set * the message to be displayed before the chart data begins loading. Additional properties like the * font face, size, and color can be set by suffixing the property name with the corresponding * message key, e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, * dataLoadStartMessageColor. If message keys are not specified, base cosmetics are used. * * @param {string} [options.dataLoadErrorMessage='Error in loading data.'] - Allows to set the * message to be displayed when there is an error loading the chart data. Additional properties like * the font face, size, and color can be set by suffixing the property name with the corresponding * message key, e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, * dataLoadStartMessageColor. If message keys are not specified, base cosmetics are used. * * @param {string} [options.dataInvalidMessage='Invalid data.'] - Allows to set the message to be * displayed when the data loaded for the chart is invalid. Additional properties like the font * face, size, and color can be set by suffixing the property name with the corresponding message * key, e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, dataLoadStartMessageColor. If * message keys are not specified, base cosmetics are used. * * @param {string} [options.dataEmptyMessage='No data to display.'] - Allows to set the message to * be displayed if data loaded for the chart is empty. Additional properties like the font face, * size, and color can be set by suffixing the property name with the corresponding message key, * e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, dataLoadStartMessageColor. If * message keys are not specified, base cosmetics are used. * * @param {string} [options.typeNotSupportedMessage='Chart type not supported.'] - Allows to set the * message to be displayed if specified chart type is not supported. Additional properties like the * font face, size, and color can be set by suffixing the property name with the corresponding * message key, e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, * dataLoadStartMessageColor. If message keys are not specified, base cosmetics are used. * * @param {string} [options.loadMessage='Loading chart. Please wait.'] - Allows to set the message * to be displayed when the chart begins to load. Additional properties like the font face, size, * and color can be set by suffixing the property name with the corresponding message key, e.g. * dataLoadStartMessageFont, dataLoadStartMessageFontSize, dataLoadStartMessageColor. If message * keys are not specified, base cosmetics are used. * * @param {string} [options.renderErrorMessage='Unable to render chart.'] - Allows to set the * message to be displayed if there was an error while rendering the chart. Additional properties * like the font face, size, and color can be set by suffixing the property name with the * corresponding message key, e.g. dataLoadStartMessageFont, dataLoadStartMessageFontSize, * dataLoadStartMessageColor. If message keys are not specified, base cosmetics are used. * * @param {hexcolor} [options.containerBackgroundColor="#ffffff"] - Sets the background color of the * chart's container HTML DOM element. It is not same as `bgColor` chart attribute. To see this * background color, a chart's own background alpha must be set to `0` by setting `bgAlpha` * attribute to `"0"` in chart attributes. * * @param {opacity} [options.containerBackgroundOpacity=1] - Sets the opacity of the container * element. Useful if the chart has underlying HTML elements or background image that needs to be * made visible. If opacity is reduced, you need to configure the chart itself to be transparent by * setting the `bgAlpha` chart attribute. * * @param {string} [options.containerClassName] - Sets the CSS class that will be set on the * container DOM element of the rendered chart. Default is `fusioncharts-container`. * * @example * * * * * *
FusionCharts will load here...
* * */ var FusionCharts = function () { function FusionCharts() { var _ref; _classCallCheck(this, FusionCharts); var opts = {}; /** * @var {Object} __state maintains internal state related information. * @private */ this.__state = {}; this.id = ''; this._deps = {}; // this._depsOrder = []; this.__state._unresolvedDeps = {}; this.__state.state = 4; // 4 - initialized state if (arguments.length === 1 && _typeof(arguments.length <= 0 ? undefined : arguments[0]) === 'object') { opts = arguments.length <= 0 ? undefined : arguments[0]; } // Incorporate the trailing object parameter as object-style parameter input overrides. if (arguments.length > 1 && _typeof((_ref = arguments.length - 1, arguments.length <= _ref ? undefined : arguments[_ref])) === 'object') { var _ref2; (0, _lib.extend2)(opts, (_ref2 = arguments.length - 1, arguments.length <= _ref2 ? undefined : arguments[_ref2]), false, true); } // Set autogenerated chart-id in case one is not specified this.id = typeof opts.id === 'undefined' ? uniqueId() : opts.id; this.args = opts; // Parse global policies to create default parameters for the chart Object. // Values are in format [sourceOption, defaultValue] // This helps in building the initial FusionCharts object when new instances // are created from user parameters. this._parsePolicies(_globalPolicies2['default']); this._attachDefaultEventListeners(); this.jsVars.fcObj = this; /** * Whenever a new instance of {@link FusionCharts} is created (as in `new FusionCharts(...)`, * this pre-initialization event is raised. This event triggers a number of modules that needs * to be setup on every instance of FusionCharts. One can listen to this event perform actions * that, on similar grounds, requires to be setup upn initialization of each chart. * * Since this event is fired upon instantiating a new FusionCharts object, it is virtually * impossible to listen to this event by adding event listener to that individual chart. That * is because, by the time one's event listener is attached using * {@link FusionCharts#addEventListener} on the subsequent lines post doing * `new FusionCharts(...)`, this event would have been already fired. Thus, the alternate ways * to listen to this event are: * * 1. Listen to FusionCharts global events using {@link FusionCharts.addEventListener} before * even creating a new instance. (The required instance can be identified by the `id` of * the chart using `eventObject.sender.id`.) * * 2. Pass the event listener as the FusionCharts constructor parameter itself. * * @event FusionCharts.beforeInitialize * @group chart * * @example * // Listening using global events * FusionCharts.addEventListener('beforeInitialize', function (opts) { * // Prints id of the chart being rendered * console.log("Chart with id " + opts.sender.id + " is about to be initialized."); * }); * * // Pass event listener in the FusionCharts constructor * var mychart = new FusionCharts({ * "type": "column2d", * "dataFormat": "json", * "dataSource": { * ... * }, * // Attach event handlers * "events": { * // Attach to beforeInitialize * "beforeInitialize": function () { * console.log("Initializing mychart..."); * } * } * }); * * @param {numeric|percent} height - Height of the chart in pixels or percentage. * @param {numeric|percent} width - Width of the chart in pixels or percentage. */ // @todo remove all unnecenssary listener from this event (0, _eventApi.triggerEvent)('beforeInitialize', this, opts); if (FusionCharts.items[this.id] instanceof FusionCharts) { /** * This error occurs when a new chart is created (instantiated) with the an `id` that has been * already assigned to an existing chart. Change the chart Id or dispose the other chart with * the duplicate id. * * @typedef {ParameterException} Error-06091847 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseWarning)(this, '06091847', 'param', '', new Error('A FusionCharts object with the specified id "' + this.id + '" already exists.' + ('Renaming it to ' + (this.id = uniqueId())))); } // Copy chart id to attributes this.attributes.id = this.id; // eslint-disable-next-line if (true) __webpack_require__.p = FusionCharts.getScriptBaseURI(); // Set initial chart type of charts this.chartType && this.chartType(opts.type || opts.swfUrl || ''); // initialize data for the first time from arguments this.setChartData(this.args.dataSource, this.args.dataFormat, void 0, void 0, true); // Add this object to the static list of FusionCharts instances. FusionCharts.items[this.id] = this; // Create alias for defaultOptions FusionCharts.defaultOptions = FusionCharts.options; /** * Once a new instance of {@link FusionCharts} is created and is ready to be operated upon, this * `initialized` event is fired. Note that initialization does not indicate that the chart has * been rendered. It denotes that the JavaScript object instance of FusionCharts is created (as * in `new FusionCharts(...)` done) and is now ready to be operated upon (like data being passed * onto it, it being rendered, etc.) * * @event FusionCharts.initialized * @group chart * * @param {numeric|percent} height - height of the chart in pixels or percentage . * @param {numeric|percent} width - width of the chart in pixels or percentage . * * @example * // Listening using global events * FusionCharts.addEventListener('initialized', function (opts) { * // Prints id of the chart that has initialized * console.log("Chart with id " + opts.sender.id + " has been initialized."); * }); * * // Pass event listener in the FusionCharts constructor * var mychart = new FusionCharts({ * "type": "column2d", * "dataFormat": "json", * "dataSource": { * ... * }, * // Attach event handlers * "events": { * // Attach to beforeInitialize * "initialized": function () { * console.log("Initialized mychart..."); * } * } * }); */ (0, _eventApi.triggerEvent)('initialized', this, opts); this._setState(); } /** * The function returns the `DOMElement` that is created inside chart container by FusionCharts. * The returned element is the same as accessing the {@link FusionCharts#ref} property. Note that * this is the `` element created by FusionCharts to render the chart. It is not the * container element that was specified during rendering the chart as the `renderAt` parameter. * * @param {string} id - The ID of the chart, whose `DOMElement` is to be referenced. * * @group framework * @since 3.1.1 * @deprecated 3.2.0 - This method has been deprecated as direct access to `DOMElement` of the * chart has become redundant. {@link FusionCharts#ref} property can be used in the rare case * where such access to the `DOMElement` of a chart is required. * * @return {DOMElement} * * @example * // Iterate on all charts rendered on a page and move them to a common location * var sidebar = document.getElementById('sidebar-html-div'), // assuming chart container name * chart; * * for (chart in FusionCharts.items) { * sidebar.appendChild(FusionCharts.getObjectReference(chart).parentNode); * } * * // The above can be done without using this deprecated getObjectReference method. * for (chart in FusionCharts.items) { * chart = FusionCharts.items[chart]; * chart.ref && sidebar.appendChild(chart.ref.parentNode); * } */ FusionCharts.getObjectReference = function getObjectReference() { var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; return FusionCharts.items[id] && FusionCharts.items[id].ref; }; /** * @deprecated 3.13.0 - This method is depricated as 'addDep' function is introduced to add dependency modules in FusionCharts * Raise error to notify and event for extensions to handle backward comaptibility */ FusionCharts.register = function register() { (0, _eventApi.triggerEvent)('register', FusionCharts, arguments, undefined, function () { (0, _eventApi.raiseError)(this, '0604111219', 'run', '.register()', new Error(registerErrorMessage)); }); }; /** * Render FusionCharts directly using the simplest one-line argument parameter. This function directly renders * FusionCharts into the container specified in arguments. * * Calling this function directly is same as creating a new instance of `FusionCharts` and calling `.render()` * on it, i.e., `var chart = FusionCharts.render({...});` is same as * `var chart = new FusionCharts({...}); chart.render();`. * * @group chart * * @param {object} options - Options required to create FusionCharts. The option must have the `renderAt` * parameter for the render to happen instantly. * * @param {FusionCharts~renderCallback=} [callback] - Upon successful render of a chart, a function passed to * this parameter is called. * * @fires FusionCharts#beforeRender * @fires FusionCharts#rendered * @fires FusionCharts#renderComplete * @fires FusionCharts#renderCancelled * * @return {FusionCharts} - Returns the newly created instance of {@link FusionCharts} object. * * @example * FusionCharts.ready(function () { * var chart = FusionCharts.render({ * type: "column2d", * renderAt: "chart-container-div", * dataSource: "data.json", * dataFormat: "jsonurl" * }); * }); */ FusionCharts.render = function render(options, callback) { // If a FusionCharts object is sent to it, it calls render method of it. if (options instanceof FusionCharts) { options.render(callback); return options; } // Render a new FusionCharts out of the parameters and return the object. return new FusionCharts(options).render(callback); }; FusionCharts.addDep = function addDep() { for (var _len = arguments.length, dep = Array(_len), _key = 0; _key < _len; _key++) { dep[_key] = arguments[_key]; } return _dependencyManager.addDep.call.apply(_dependencyManager.addDep, [this].concat(dep)); }; FusionCharts.getDep = function getDep(name, type) { return _dependencyManager.getDep.call(this, name, type); }; /** * Bind callbacks to events fired throughout FusionCharts. This method can be used to listen to * events across all FusionCharts instances on a page. * * An event listener is used to execute custom functions when an event is fired. FusionCharts * fires events at all stages of creating, updating, rendering or removing a chart. This function * lets you tap into any of these events and provide your own functions which will be called when * those events are triggered. * * An alternative to this function is to use {@link FusionCharts#addEventListener} method on a * chart instance to bind to an event fired by a specific chart. * * @param {string|array} type - The event name to listen to. The event name is not case sensitive. * In case you want to register an event to multiple events in the same registration call, provide * them as an array of event names. * @param {FusionCharts~eventListener} listener - Pass the function that is to be executed when * the event is fired. Upon an event, the listeners for that event are executed sequentially with * arguments that are specific to that event. See {@link FusionCharts~eventListener} for more * details on the arguments. * * @group event-handling:add * @example * // Show a message when a number of charts have been rendered on a page. * FusionCharts.ready(function { * var counter = 0, * threshold = 3; * * FusionCharts.addEventListener("rendered", function (eventObject) { * counter++; * if (counter > threshold) { * alert("More than " + threshold + "charts rendered!"); * } * }); * }); */ FusionCharts.addEventListener = function addEventListener(type, listener) { return (0, _eventApi.addListener)(type, listener); }; FusionCharts.on = function on(type, listener) { return FusionCharts.addEventListener(type, listener); }; /** * Removes an event that was originally added using {@link FusionCharts.addEventListener}. * @param {string} type - The event name whose listener needs to be removed/detached. * @param {function} listener - The listener function that needs to be removed. * * @group event-handling:remove */ FusionCharts.removeEventListener = function removeEventListener(type, listener) { return (0, _eventApi.removeListener)(type, listener); }; /** * This function allows to register callback functions to be executed when FusionCharts library is * ready to be used. In general, the framework is ready after `DOMContentLoaded` browser event has * been fired and all the initial dependent files/modules are available. One can attach multiple * callbacks by calling this function any number of time. * * The callback function is executed even when attached after FusionCharts is already ready! Thus, * it is recommended that all entry-point and initialization codes are written within this block. * This also helps in neatly organizing all codes within a script file or the page `` and as * such contextually separating code from HTML blocks. * * @param {FusionCharts~readyCallback} readyCallback - Pass a function that would be executed as * callback when FusionCharts framework is ready. * @param {*} [args={@link FusionCharts}] - Argument to be passed on to the callback function. * @param {function} [context={@link FusionCharts}] - In the situation where the function passed * via `fn` parameter needs to be executed in a different scope than the default * {@link FusionCharts} scope, pass the appropriate class object here. * * @example * // Render a chart within a chart container `div` element. * FusionCharts.ready(function (FusionCharts) { * var chart = new FusionCharts({ * type: "column2d", * renderAt: "chart-container-div", * dataSource: "my-chart-data.json", * dataFormat: "jsonurl" * }); * // Since we are in the `ready` block, the `chart-container-div` * // element should be available by now. * chart.render(); * }); */ FusionCharts.ready = function ready(readyCallback) { var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : FusionCharts; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : FusionCharts; var closure = function closure() { /** * The function passed as readyCallback is executed when FusionCharts library is ready. * Use {@link FusionCharts.ready} to request executing of your callback function. * @callback FusionCharts~callback * @param {FusionCharts|*} args - By default, the parameter passed to the callback * function is the FusionCharts library class unless specified otherwise in the `args` * parameter of {@link FusionCharts.ready} */ readyCallback.call(context, args); }; if (typeof readyCallback === 'function') { isReady ? setTimeout(closure, 0) : FusionCharts.addEventListener('ready', closure); } }; FusionCharts.formatNumber = function formatNumber(num) { var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var axisIndex = arguments[2]; config = objToLowerCase(config); var hashKey = objToHash(config), NF = void 0, formatedStr = void 0; if (NFStore[hashKey]) { NF = NFStore[hashKey]; } else { NFStore[hashKey] = NF = new _numberFormatter2['default'](config, { useScaleRecursively: true }); } NF.configure(config); formatedStr = NF.dataLabels(num, axisIndex); return formatedStr; }; FusionCharts.transcodeData = function transcodeData(data, source, target, advanced) { // Validate parameters. var dataFormats = (0, _dependencyManager.getDepsByType)('transcoder'), sanitisedTarget = sanitiseFormatStr(target), sanitisedSource = sanitiseFormatStr(source), jsonData = void 0, outputData = void 0, transcoderObjSource = void 0, transcoderObjTarget = void 0; if (!sanitisedSource || typeof sanitisedSource.toString !== 'function' || !sanitisedTarget || typeof sanitisedTarget.toString !== 'function' || typeof dataFormats[sanitisedTarget] === 'undefined' || typeof dataFormats[sanitisedSource] === 'undefined') { /** * This error is encountered when either the `source` or the `target` parameter of * {@link FusionCharts.transcodeData} receives a value that is not part of the list of data * formats in {@link FusionCharts~dataFormats}. Note that url-prefixed data formats are not * intended to be supplied to the transcoder function. * * @typedef {ParameterException} Error-14090217 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(this, '14090217', 'param', '.transcodeData()', 'Unrecognized data-format specified during transcoding.'); return; } transcoderObjSource = dataFormats[sanitisedSource](); transcoderObjTarget = dataFormats[sanitisedTarget](); if (transcoderObjSource.toJSON) { // only csv transcoder expects chart object as a parameter because // data is processed based on the chart jsonData = transcoderObjSource.toJSON(data, this); outputData = transcoderObjTarget.fromJSON(jsonData.data, this); } // Carry the error. if (!(jsonData.error instanceof Error)) { outputData.error = jsonData.error; } return advanced ? outputData : outputData.data; }; /** * This API is used to set global level animation rule by the user * @param {object} rule - user given animation rule */ FusionCharts.setAnimation = function setAnimation(rule) { !FusionCharts.options._globalAnimationRule && (FusionCharts.options._globalAnimationRule = []); FusionCharts.options._globalAnimationRule.push(rule); }; /** * This API is used to set new easing effect given by the user * @param {string} name easing effect name * @param {function} fn easing effect function */ FusionCharts.setEasingEffect = function setEasingEffect(name, fn) { // add new easing effect into redraphael FusionCharts.getDep('redraphael', 'plugin').easing_formulas[name] = fn; }; FusionCharts.getScriptBaseURI = function getScriptBaseURI() { return FusionCharts.options.scriptBaseUri; }; FusionCharts.setScriptBaseURI = function setScriptBaseURI(scriptBaseURI) { FusionCharts.options.scriptBaseUri = scriptBaseURI; // eslint-disable-next-line if (true) __webpack_require__.p = scriptBaseURI; }; FusionCharts.getChartFromId = function getChartFromId(id) { return FusionCharts.items[id]; }; FusionCharts.getVersion = function getVersion(name) { var verStr = { fcs: FCS, fc: FC, fw: FW, pc: PC, fm: FM, ft: FT }; return verStr[name] || verStr; }; /** * attach event listener to chart object so that some default job can be done when evens gets fired */ FusionCharts.prototype._attachDefaultEventListeners = function _attachDefaultEventListeners() { var chart = this, events = chart.options.events, key = void 0, item = void 0; if (events) { for (key in events) { if (typeof events[key] === 'function') { chart.addEventListener(key, events[key]); } } } // Desensitize the case of the parameter. chart.options.renderer = 'javascript'; // Attach event liseners of the renderer to this object. for (item in _rendererEvents2['default']) { chart.addEventListener(item, _rendererEvents2['default'][item]); } }; /** * This API manages the state of the chart instance * It traverse through all the remaining dependency state and finally decides * what state should be set to chart instance. * Once all the dependencies resolved (that ready state of dependencies) then it * proceed to the rendering job if and only if the render API is already invoked */ FusionCharts.prototype._setState = function _setState() { var chartInstance = this, deps = chartInstance._deps, dep = void 0, depState = void 0, prevChartState = chartInstance.__state.state, chartState = 4; for (var key in deps) { if (deps.hasOwnProperty(key)) { dep = deps[key]; depState = dep.getState(); // if current chart state is in lower priority state if (chartState > depState) { chartState = depState; chartInstance.__state.currChartMsg = dep.getMsg(); chartInstance.__state.currChartMsgStyle = dep.getMsgStyle(); } // dependency should be removed when it is resolved if (depState === 3) { chartInstance._removeChartDependency(key); } } } chartInstance.__state.prevState = prevChartState; chartInstance.__state.state = chartState; /** * whenever the state is changed chartInstance event is fired */ if (prevChartState !== chartState) { (0, _eventApi.triggerEvent)('stateChanged', chartInstance, { prevState: stateListOnPriority[prevChartState], state: stateListOnPriority[chartState] }, [chartInstance.id]); } if (!chartInstance.containerHidden) { if (chartState === 3 && chartInstance.__state.renderInvoked) { var _chartInstance$render = chartInstance.renderOpts, containerElement = _chartInstance$render.containerElement, callback = _chartInstance$render.callback; chartInstance._renderChart(containerElement, void 0, callback); this._clearPrevContext(); delete chartInstance.renderOpts.callback; } else if ((chartState === 2 || chartState === 1) && chartInstance.__state.renderInvoked && chartInstance._contextChanged() && !(chartInstance.__state.renderComplete && chartState === 2) // after rendering the chart waiting msg should not be shown ) { var _chartInstance$render2 = chartInstance.renderOpts, _containerElement = _chartInstance$render2.containerElement, _callback = _chartInstance$render2.callback; chartInstance._renderChart(_containerElement, 'base', chartState === 1 && _callback, chartInstance.__state.currChartMsg, chartInstance.__state.currChartMsgStyle); chartState === 1 && delete chartInstance.renderOpts.callback; } } }; FusionCharts.prototype._clearPrevContext = function _clearPrevContext() { this.__state.prevChartMsg = ''; this.__state.prevChartMsgStyle = {}; }; FusionCharts.prototype._contextChanged = function _contextChanged() { if (this.__state.currChartMsg !== this.__state.prevChartMsg) { this.__state.prevChartMsg = this.__state.currChartMsg; this.__state.prevChartMsgStyle = this.__state.currChartMsgStyle; return true; } var prevImageStyle = this.__state.prevChartMsgStyle && this.__state.prevChartMsgStyle.image, currImageStyle = this.__state.currChartMsgStyle && this.__state.currChartMsgStyle.image, prevMsgStyle = this.__state.prevChartMsgStyle && this.__state.prevChartMsgStyle.message, currMsgStyle = this.__state.currChartMsgStyle && this.__state.currChartMsgStyle.message; if (prevImageStyle && (prevImageStyle.imageHAlign !== currImageStyle.imageHAlign || prevImageStyle.imageVAlign !== currImageStyle.imageVAlign || prevImageStyle.imageAlpha !== currImageStyle.imageAlpha || prevImageStyle.imageScale !== currImageStyle.imageScale || prevMsgStyle.color !== currMsgStyle.color || prevMsgStyle.fontFamily !== currMsgStyle.fontFamily || prevMsgStyle.fontSize !== currMsgStyle.fontSize)) { this.__state.prevChartMsg = this.__state.currChartMsg; this.__state.prevChartMsgStyle = this.__state.currChartMsgStyle; return true; } return false; }; /** * set state with no checking * use this api with caution (it does not check dependency) * uses of this api is discouraged * @param {number} state - state value */ FusionCharts.prototype._sudoSetState = function _sudoSetState(state) { this.__state.prevState = this.__state.state; this.__state.state = state; (0, _eventApi.triggerEvent)('stateChanged', this, { prevState: stateListOnPriority[this.__state.prevState], state: stateListOnPriority[this.__state.state] }, [this.id]); }; /** * return current and previous state of chart obj */ FusionCharts.prototype._getState = function _getState() { return stateListOnPriority[this.__state.state]; }; /** * add a new dependency to chart, to go ready state chart has to resolve all the dependency * @param {String} dep dependency name * @param {Object} _dep necessary options to resolve a dependency */ FusionCharts.prototype._addChartDependency = function _addChartDependency(name, _dep) { this._deps[name] && this._removeChartDependency(name); this._deps[name] = _dep; _dep.getState = getStateForDep; _dep.getMsg = getMsgForDep; _dep.getMsgStyle = getMsgStyleForDep; Object.assign(_dep, _dep.resolve(_dep.scopeOf)); }; FusionCharts.prototype._removeChartDependency = function _removeChartDependency(name) { if (this._deps[name]) { this._deps[name].removed = true; delete this._deps[name]; } }; /** * Parse global policies to create default parameters for the chart Object. * Values are in format [sourceOption, defaultValue] * This helps in building the initial FusionCharts object when new instances * are created from user parameters. * @param {Object} policies */ FusionCharts.prototype._parsePolicies = function _parsePolicies(policies) { var options = this.args, policy = void 0, value = void 0, prop = void 0; // Iterate through the data policy and correspondingly create the // three stacks of parameters, attributes and flashVars for (policy in policies) { // Set just the policy object in case of single-level policy. if (_globalPolicies2['default'][policy] instanceof Array) { value = options[policies[policy][0]]; this[policy] = typeof value === 'undefined' ? policies[policy][1] : value; } else { // Define objects that would hold parameters for swfobject. Also // populate with variables from the parameters if (_typeof(this[policy]) !== 'object') { this[policy] = {}; } // Set every sub-object for two-level policy for (prop in policies[policy]) { value = options[policies[policy][prop][0]]; this[policy][prop] = typeof value === 'undefined' ? policies[policy][prop][1] : value; } } } }; /** * Returns whether a chart has been successfully rendered or not. * @group chart * @see FusionCharts#render * @see FusionCharts#event:beforeRender * @see FusionCharts#event:renderComplete * @see FusionCharts#event:renderCancelled * @see FusionCharts#event:rendered * @return {boolean} */ FusionCharts.prototype.hasRendered = function hasRendered() { return !!(this.jsVars.hcObj && this.jsVars.hcObj.hasRendered); }; /** * Sets the chart's container background color as transparent. This is not the chart's background. * It is the background of the container DOM element within which the chart has been rendered. * * @group chart * @deprecated 3.4.0 - The container transparency can now be controlled using the * `containerBackgroundOpacity` parameter while creating a new instance of {@link FusionCharts}. * * @param {boolean} transparency - Passing `true` implies that the chart is transparent. * @return {boolean} */ FusionCharts.prototype.setTransparent = function setTransparent(transparency) { var vars; if (!(vars = this.jsVars)) { return; } // Sets chart to transparent mode when isTransparent (wMode) is true // (default). When no parameter is passed, we assume transparent to // be true. if (typeof transparency !== 'boolean' && transparency !== null) { transparency = true; } // Set the property. vars.transparent = transparency === null ? false : transparency === true; }; /** * Listen to events fired by an individual chart. For more information on the available events, * refer to the events section. * * @param {string|string[]} type - The event name that needs to be listened to. The event name is * not case sensitive. In case you want to register an event to multiple events in the same * registration call, provide them as an array of event names. * @param {FusionCharts~eventListener} listener - Pass the function that is to be executed when * the event is fired. Upon an event, the listeners for that event are executed sequentially * with arguments that are specific to that event. See {@link FusionCharts~eventListener} for more * details on the arguments. * * @group event-handling:add */ FusionCharts.prototype.addEventListener = function addEventListener(type, listener) { return (0, _eventApi.addListener)(type, listener, this); }; FusionCharts.prototype.on = function on(type, listener) { return this.addEventListener(type, listener); }; /** * Removes an event that was originally added using {@link FusionCharts#addEventListener}. * @param {string} type - The event name whose listener needs to be removed/detached. * @param {function} listener - The listener function that needs to be removed. * * @group event-handling:remove */ FusionCharts.prototype.removeEventListener = function removeEventListener(type, listener) { return (0, _eventApi.removeListener)(type, listener, this); }; /** * FusionCharts formats input number based on configurations passed in chart attributes. It may * be needed to similarly format other non-chart elements on page using same algorithm. This * function is available to be used globally on {@link FusionCharts} object or on a specific * instance of FusionCharts Suite XT. * * When called on the FusionCharts object (`FusionCharts.formatNumber()`,) the default number * configuration settings are utilised. These can be overridden by passing additional number * format configuration settings as the second parameter. Refer to chart attributes for various * number format configurations. * * When called on an instance of a chart, gauge or map, the number formatting as set by the * data of the chart is used. As such, the second parameter (`type`) accepts `xAxisValues`, * `yAxisValues` or `dataLabels` to allow formatting to be done specific to them. * * @group framework * * @param {number} num - The number that needs to be formatted. * * @param {string=} [type=datalabels] - A chart can be configured to format numbers differently * depending upon where it is being used. The formatting of data values can be different than * that of x-axis labels. As such, passing `yaxisvalues`, `xaxisvalues` or `datalabels` as a * value of this parameter returns the formatted number accordingly. __Note that this parameter * is not available when `formatNumber` is executed on `FusionCharts` object instead of chart * instances. * * @param {Object=} [config] - One can optionally pass additional number formatting attributes * as the `config` parameter to override the default number formatting options of a chart. * While calling `formatNumber` on `FusionCharts` object, this becomes the second parameter. * * @param {number} yAxisIndex - index of the yAxis * @return {string} - formatted number (as string) * * @example * console.log(FusionCharts.formatNumber(1234.5)); // logs "1.2K" * * console.log(FusionCharts.formatNumber(1234.5, { * numberPrefix: "$" * })); // logs "$1.2K" * * @example * // Calling number formatter on a chart instance when `renderComplete` event is fired. * FusionCharts.ready(function () { * // Render a chart within a chart container `div` element. * var chart = new FusionCharts({ * type: 'column2d', * renderAt: 'chart-container-div', * dataFormat: 'json', * dataSource: { * chart: { * caption: "Quarterly sales summary", * numberPrefix: "$", * decimals: "2", * forceDecimals: "1" * } * data: [ * { label: "Q1", value: "213345"}, * { label: "Q2", value: "192672"}, * { label: "Q3", value: "201238"}, * { label: "Q4", value: "209881"}, * ] * }, * * events: { * renderComplete: function (eventObj) { * // Call the formatNumber function of the specific chart we rendered. * console.log(eventObj.sender.formatNumber(1234.5)); // logs "$1.23K" * } * } * }); * chart.render(); * }); */ FusionCharts.prototype.formatNumber = function formatNumber(num, type, config, yAxisIndex) { var chartObj = this, chart = chartObj.apiInstance || {}, numberFormatter = chart.numberFormatter, dataObj = void 0, dataChartTagJSON = void 0, configHashKey = void 0, hashKey = void 0, NF = void 0, formatedStr = void 0; configHashKey = objToHash(config); config = config && objToLowerCase(config) || {}; if (configHashKey === '') { if (numberFormatter) { NF = numberFormatter; } else { dataObj = chartObj.options.dataSource; dataChartTagJSON = dataObj.chart || {}; hashKey = objToHash(dataChartTagJSON); if (NFStore[hashKey]) { NF = NFStore[hashKey]; } else { NFStore[hashKey] = NF = new _numberFormatter2['default'](chart, dataChartTagJSON); } } } else { dataObj = chartObj.options.dataSource; dataChartTagJSON = dataObj.chart || {}; dataChartTagJSON = (0, _lib.extend2)((0, _lib.extend2)({}, dataChartTagJSON), config); hashKey = objToHash(dataChartTagJSON); if (NFStore[hashKey]) { NF = NFStore[hashKey]; } else { NFStore[hashKey] = NF = new _numberFormatter2['default'](chart, dataChartTagJSON); } } switch ((type && type.toLowerCase ? type : '').toLowerCase()) { case 'yaxisvalues': formatedStr = NF.yAxis(num, yAxisIndex); break; case 'xaxisvalues': formatedStr = NF.xAxis(num); break; case 'scale': formatedStr = NF.scale(num); break; default: formatedStr = NF.dataLabels(num, yAxisIndex); break; } return formatedStr; }; /** * Use this function to create a copy of a chart instance. Cloning a chart object results in * creation of a new chart with identical construction properties of the chart being cloned. A * cloned chart is not rendered by default and needs to be provided a container DOM element to be * rendered into. A cloned chart gets one auto-generated chart Id assigned. * * @group chart * * @param {?object=} [overrides] - This parameter can be very useful in instructing what changes * needs to be done while cloning a chart. It accepts all the construction parameters of a new * {@link FusionCharts} instance. * * For example, passing `pieChart.clone({type: 'column2d'});` will clone the pie chart, but set * its chart-type as `column2d`. * @param {boolean=} [argsOnly=false] - Setting this to `true` does not return a new FusionCharts * object. Instead, it causes the function to return a serializable object that can be later * passed on while creating a new FusionCharts and as such create a clone. * * @return {FusionCharts|object} */ FusionCharts.prototype.clone = function clone(overrides, argsOnly) { // Create a copy of arguments of this object. var typeofParams = typeof overrides === 'undefined' ? 'undefined' : _typeof(overrides), crcObjects = {}, options = (0, _lib.extend2)({}, this.args, false, true); // Recreate construction parameters by reverse calculating the global policies. deconstructPolicySet(_globalPolicies2['default'], options, this); // Remove any specific parameters that if cloned will create issues. delete options.id; delete options.animate; delete options.stallLoad; crcObjects.link = options.link; // link was removed as it prevents deep cloning // Now, deep clone the entire object to separate both instances options = (0, _lib.extend2)({}, options, false, true); // restore crc Objects options.link = crcObjects.link; switch (typeofParams) { // Override any of the options by parameters sent by user case 'object': (0, _lib.extend2)(options, overrides, false, true); break; // In case user sends only one boolean param marking not to // create new chart. case 'boolean': argsOnly = overrides; break; } // Create new FusionCharts object from the computed options return argsOnly ? options : new FusionCharts(options); }; /** * Denotes whether a chart is "active" or not after being rendered. This is primarily relevant for * Flash variant of the charts since they tend to loose functionality when hidden or scrolled away * as a measure to save system resources. * * For JavaScript charts, this returns `false` when a chart has not been rendered. As such, using * the function {@linkFusionCharts#hasRendered} is more relevant. * * @group chart * @deprecated 3.4.0 - The removal of Flash variant of the charts discards the use of this * function since JavaScript are always "active" and does not loose its functionalities when out * of viewport of the browser. * * @return {boolean} - Returns `true` if a Flash chart is visible and can communicate with the * rest of the page using its internal JavaScript API. For JavaScript charts, this returns `false` * when a chart has not been rendered. */ FusionCharts.prototype.isActive = function isActive() { if (!this.ref || window.document.getElementById(this.id) !== this.ref) { return false; } try { return SIGNATURE_MATCH_RE.test('FusionCharts'); } catch (e) { return false; } }; /** * Gets or sets the chart type of an instance of FusionCharts. * * To change the chart type, pass the new chart type as the first parameter to this function. The * chart is automatically re-rendered when a new chart type is set. To get the current chart type, * call this function without any parameters. * * When the chart type is changed using this method, the chart is re-rendered and the * {@link FusionCharts#event:chartTypeChanged} event is fired. * * @since 3.4.0 * @group chart * * @param {string=} value - Sets the new chart type. * * @param {object=} options - During modifying the chart type using this method, additional * options can be passed on to update chart data and re-render the chart at the same time. Note * that these options are ignored if you do not provide a `value` (first) parameter. * * @param {string|object=} options.dataSource - Provide a new source of data during the change of * chart type. * @param {FusionCharts~dataFormats=} options.dataFormat - Specify the data format of the new * `dataSource` provided during chart-type update. If this is not provded, then it is assumed that * the `dataSource` provided is same as the existing or default `dataFormat`. If `dataSource` is * not provided, this parameter is ignored. * * @return {string} The current chart type is returned. * * @fires FusionCharts#chartTypeChanged * @see FusionCharts.render * * @example * // Render a column chart and on click of a button toggle it from column to pie and vice versa. * FusionCharts.ready(function () { * var chart = new FusionCharts({ * type: 'column2d', * renderAt: 'chart-container', * dataSource: 'weekly-sales.json', * dataFormat: 'jsonurl' * }).render(); * * // Assign the functionality of toggling chart type when clicked on * // a button (with an id toggle-chart-type). * document.getElementById('toggle-chart-type').onclick = function () { * if (chart.chartType() === 'column2d') { * chart.chartType('pie2d'); * } * else { * chart.chartType('column2d'); * } * }; * }); */ FusionCharts.prototype.chartType = function chartType(value, options) { var chartObj = this, opts = chartObj.options, src = void 0; if (typeof value === 'string' && value !== '') { options = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {}; // We remove query string from `src`. Similar processing is in core. src = value.replace(/[\?\#][\s\S]*$/g, ''); // remove path for type opts.chartType = src.replace(/^[\s\S]*\//gi, ''); opts.chartTypeSourcePath = src.indexOf('/') === -1 ? options.chartTypeSourcePath || FusionCharts.options.chartTypeSourcePath || '' : src.replace(/[^\/]*?$/gi, ''); if (opts.chartType === 'zoomscatter' && !document.createElement('canvas').getContext) { var _showUnsupportedBrows = showUnsupportedBrowserMessage(chartObj), msgStyle = _showUnsupportedBrows.msgStyle, msg = _showUnsupportedBrows.msg; this._addChartDependency('chartModuleLoad', { scopeOf: this, opts: { value: opts.chartType }, resolve: function resolve() { return { state: 1, msgStyle: msgStyle, msg: msg }; } }); this._setState(); return; } // When chart type is timeseries and browser is internet explorer (<11) if (opts.chartType === 'timeseries' && _lib.isIE) { var _showUnsupportedBrows2 = showUnsupportedBrowserMessage(chartObj), _msgStyle2 = _showUnsupportedBrows2.msgStyle, _msg2 = _showUnsupportedBrows2.msg; this._addChartDependency('chartModuleLoad', { scopeOf: this, opts: { value: opts.chartType }, resolve: function resolve() { return { state: 1, msgStyle: _msgStyle2, msg: _msg2 }; } }); this._setState(); return; } /* * To load the dynamic modules when changing chart type */ (0, _eventApi.triggerEvent)('resourceRequested', chartObj); this._addChartDependency('chartModuleLoad', { scopeOf: this, opts: { value: opts.chartType }, resolve: handleChartModuleLoading }); // Handle special internal case of setting chart type without rendering. if (typeof options.dataSource !== 'undefined' && options.dataSource !== null) { this.setChartData(options.dataSource, options.dataFormat, options.dataConfiguration); } this._setState(); } else if (value !== undefined) { var _showUnsupportedChart4 = showUnsupportedChartMessage(this), _msgStyle3 = _showUnsupportedChart4.msgStyle, _msg3 = _showUnsupportedChart4.msg; this._addChartDependency('chartModuleLoad', { resolve: function resolve() { return { state: 1, msgStyle: _msgStyle3, msg: _msg3 }; } }); this._setState(); /** * whenever the chartType is invalid this event is fired */ (0, _eventApi.triggerEvent)('charttypeinvalid', this, {}, [this.id]); return; } return (opts.chartType || '').toLowerCase(); }; FusionCharts.prototype.setChartDataUrl = function setChartDataUrl() { var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var format = arguments[1]; var config = arguments[2]; var callback = arguments[3]; var silent = arguments[4]; this._addChartDependency('data', { scopeOf: this, opts: { url: url, format: format, config: config, callback: callback, silent: silent }, resolve: _setChartDataUrl }); this._setState(); }; FusionCharts.prototype.setChartData = function setChartData(dataSource, format, config, callback) { var silent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var chartObj = this, options = chartObj.options, sanitisedFormat = void 0; // Set intitial data if present if (typeof dataSource !== 'undefined' && dataSource !== null) { // If data format was not specified during construction, try auto-detection. if (typeof format !== 'string') { switch (typeof dataSource === 'undefined' ? 'undefined' : _typeof(dataSource)) { case 'function': dataSource = dataSource.call(chartObj, options.dataConfiguration); format = chartObj.args.dataFormat = 'JSON'; break; case 'string': format = chartObj.args.dataFormat = /^\s*?\{[\s\S]*\}\s*?$/g.test(format) ? 'JSON' : 'XML'; break; case 'object': format = chartObj.args.dataFormat = 'JSON'; break; } } } else { format = NATIVE_FORMAT; } sanitisedFormat = sanitiseFormatStr(format); if (URL_RE.test(sanitisedFormat)) { chartObj.setChartDataUrl(dataSource, sanitisedFormat, config, callback, silent); } else { this._addChartDependency('data', { opts: { data: dataSource, sanitisedFormat: sanitisedFormat, config: config, callback: callback, silent: silent }, scopeOf: chartObj, resolve: _setChartData }); !chartObj.disposed && this._setState(); } }; FusionCharts.prototype.getChartData = function getChartData() { var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NATIVE_FORMAT; var advanced = arguments[1]; var update = arguments[2]; // Variable to store a reference to the data-handler. var chartObj = this, dataFormats = (0, _dependencyManager.getDepsByType)('transcoder'), sanitisedFormat = sanitiseFormatStr(format), transcoderObj = dataFormats[sanitisedFormat](), chartOptions = chartObj.options, api = chartObj.apiInstance, cData, chartData = !update && (cData = api && api.getCollatedData && api.getCollatedData(chartOptions.dataSource)) ? cData : chartOptions.dataSource, formattedData; if (transcoderObj) { if (transcoderObj.fromJSON) { formattedData = transcoderObj.fromJSON(chartData, chartObj); } else { formattedData = { error: new Error('Unable to convert data.') }; } } else { formattedData = { error: new Error('Data format not recognized.') }; } if (!formattedData.error && chartOptions.error) { formattedData.error = chartOptions.error; } return advanced ? formattedData : formattedData.data; }; /** * Determines whether a chart will render properly with the data set on it. * This includes data that is set using the setChartData() or setChartDataUrl() methods. * @param {Boolean} available - Setting this parameter to true returns the status of the data, * irrespective of its compatibility with the chart type. In * that case, this function will return false if data provided to * the chart triggers the dataLoadError or dataInvalid events */ FusionCharts.prototype.dataReady = function dataReady(available) { return available ? this.__state.dataAvailable : this.__state.dataReady; }; /** * Updates a chart's data attributes with the new attribute-value pair. In other words, it * updates a chart's data definition root. That would be `` node in case data is in `XML` * format or the `chart {}` object in case it is in `JSON` format. You must have the chart's * data being set for these attributes to take effect. * * This function is useful when updating a chart's configuration after it has been rendered * once. The function internally retrieves the last data set on the chart * (using {@link FusionCharts#getJSONData}). It then updates the `{ chart: {} }` object of the * data using the new attributes provided and then sets this data back to the chart. * * > Setting the value of a parameter to `null` causes the attribute to be removed (unset) and * > restored to it's default value. * * @group data * * @param {Object|string} attributes - The set of attributes to be is passed on as key-value * pair of an object. In case of updating a single attribute, the key can be passed as a * `string` and the value as the second parameter. * * @param {?string=} [value] - In case the first parameter is a single attribute as string, the * second parameter (i.e. this parameter) must be provided as the value of that key. * * @example * // Here we would render a chart in a DOM element with an id, say "chart-container", and upon * // clicking the chart, we would toggle the visibility of its legend. * FusionCharts.ready(function () { * FusionCharts.render({ * id: 'salesChart', * type: 'pie2d', * renderAt: 'chart-container', * * dataSource: { * chart: { * caption: 'Revenue distribution' * }, * data: [ * { value: '22', label: 'Redistribution' }, * { value: '54', label: 'Internal Circulation' }, * { value: '24', label: 'Sale' }, * ] * }, * * events: { * chartClick: function (event) { * var chart = event.sender, * // Check whether legend is currently visible by fetching the showLegend * // attribute * legendVisible = !!+chart.getChartAttribute('showLegend'); * * // Set the opposite of the current state of the legend's visibility. * chart.setChartAttribute('showLegend', legendVisible ? '0' : '1'); * } * } * }); * }); */ FusionCharts.prototype.setChartAttribute = function setChartAttribute(attributes, value) { var json, prop, attList, temp, i; // In case attribute is sent as separate arguments, combine them to one object. if (typeof attributes === 'string') { temp = arguments[0]; attributes = {}; attributes[temp] = value; } else if (attributes === null || (typeof attributes === 'undefined' ? 'undefined' : _typeof(attributes)) !== 'object') { // In case user sends invalid parameters for attributes. return; } i = 0; json = this.getChartData(NATIVE_FORMAT); attList = json && (json.chart || json.graph || json.map); if (!attList) { /** * {@link FusionCharts#setChartAttribute} was called while chart data was not set or while * chart data had an error. Check whether {@link FusionCharts.event:dataLoaded} had been * successfully fired before {@link FusionCharts.event:renderComplete} and that none of the * data load error events such as {@link FusionCharts.event:dataLoadError} or * {@link FusionCharts.event:invalidData} has been fired. * * @typedef {RuntimeException} Error-2105141421 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(this, '2105141421', 'run', '#setChartAttribute()', 'Could not retrieve attribute list. Is data ready?'); return; } // Iterate through attributes and update them. for (prop in attributes) { i += 1; if (attributes[prop] === null) { delete attList[prop.toLowerCase()]; continue; } attList[prop.toLowerCase()] = attributes[prop]; } // Update chart's XML. if (i > 0) { // In case animation is not specified, then turn it off. if (typeof attList.animation === 'undefined') { attList.animation = '0'; } this.setChartData(json, NATIVE_FORMAT); } }; /** * Fetch value of chart attributes (configurations) that have been explicitly applied to root * level `chart`. This function can be used to return value of a single attribute or a list of * attributes or all attributes have been applied to the chart. * * - To fetch a single attribute, pass the name of the attribute as a string. * - To fetch a list of selected attributes, pass an array of attribute names. This will return * an object with items in the order in which they are provided in the array. * - To fetch a list of all attributes, do not pass a parameter to this function. * * If any attribute requested is not set on the chart, the value for that attribute is returned * as `undefined`. This will be `undefined` even for values that are internally computed but not * explicitly set. For example, for Multi-series Column2D charts, `showLegend` defaults to * `"1"`. But, if `showLegend` is not provided as part of chart configuration, requesting the * value of `showLegend` through this function will return `undefined`. * * @group data * * @param {string|string[]} [attribute] - The attribute or an array of attributes that is to be * fetched. If this parameter is not provided, then all available chart attributes are returned. * * @return {string|Object} The value of the attribute in form of a string in case a single * attribute was requested. Otherwise, an object containing a set of key value pairs. */ FusionCharts.prototype.getChartAttribute = function getChartAttribute(attribute) { // Get chart attributes. var json = this.getChartData(NATIVE_FORMAT), attList = json && (json.chart || json.graph || json.map), // Create a variable that will store reference to the parameter that // contains attributes. This helps in case user sends one attribute // as string, we covert it to an array witj one element. value, i; // In case no argument is passed, we return the entire set of // chart attributes object. if (arguments.length === 0 || typeof attribute === 'undefined' || typeof attList === 'undefined') { return attList; } // Convert single attribute to array with one element or directly // send the value as return. if (typeof attribute === 'string') { value = attList[attribute.toString().toLowerCase()]; } else if (attribute instanceof Array) { // In case user sends an array of attributes, we compile an object // for the same and return. value = {}; for (i = 0; i < attribute.length; i += 1) { value[attribute[i]] = attList[attribute[i].toString().toLowerCase()]; } } else { // If all above conditions fail, there must be some issue with the // parameters. /** * {@link FusionCharts#getChartAttribute} accepts only a string or an array of attribute * names as its paramater. Check whether your call to the function involved passing some * other type of parameter. * * @typedef {RuntimeException} Error-25081429 * @memberOf FusionCharts.debugger * @group debugger-error */ (0, _eventApi.raiseError)(this, '25081429', 'param', '~getChartAttribute()', 'Unexpected value of "attribute"'); } // We return 'value' variable here as because it is equivalent to // sending '{}' in case above conditions fail. return value; }; /** * Creating a chart using `new FusionCharts()` merely creates a JavaScript instance of the chart. * The chart is not yet made visible on the page. In order to render it in a location on the page, * this function needs to be called. Usually, when the chart is instantiated, the `renderAt` * construction parameter specifies the element on the page inside which the chart will be * rendered. If the `renderAt` parameter is not provided during construction of the page, then the * same can be provided as the first parameter of this function. * * This function renders a chart inside a container element on a page. If a chart is already * rendered, it can be re-rendered inside the same container DOM element or some other element. * * @group chart * * @param {string|DOMElement=} [containerElement] - A reference or `id` of the `DOMElement` inside * which the chart is to be rendered. If this argument is not provided, it is assumed that the * `renderAt` option is provided during creation of the chart. * * @param {FusionCharts~DOMInsertModes} [insertMode=replace] - This parameter specifies the method * using which the chart's DOM element will be inserted within the `containerElement`. For more * information regarding DOM insert modes, see {@link FusionCharts~DOMInsertModes} * * @param {FusionCharts~renderCallback=} [callback] - This parameter is a callback function that * is called after the chart is successfully rendered. The last parameter to `render()` is always * treated as a callback if it is a function. * * @fires FusionCharts#beforeRender * @fires FusionCharts#rendered * @fires FusionCharts#renderComplete * @fires FusionCharts#renderCancelled */ FusionCharts.prototype.render = function render(containerElement, insertMode, callback) { if (!this.disposed) { this.__state.beforeRenderFired = false; // If the container is visible call the render function this._addChartDependency('chartContainer', { scopeOf: this, opts: { containerElement: containerElement, insertMode: insertMode, callback: callback }, resolve: handleRender }); this.__state.renderInvoked = true; } this._setState(); return this; }; FusionCharts.prototype._renderChart = function _renderChart(containerElement, chartType, callback, message, style) { var silent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; if (this.disposed) { return; } var that = this, eventArgs, successFn = function successFn() { if (that.disposed === true) { return; } // Call the current renderer. that._render(containerElement, chartType, callback && function () { // Sandbox the error from causing script to break. Throw error on a different thread. if (callback) { try { /** * This callback is part of {@link FusionCharts#render} function. When a function is * passed as a parameter of {@link FusionCharts#render}, it is executed when the * rendering process is complete (along with {@link FusionCharts#event:renderComplete} * event.) This callback is executed with the scope of the instance of `FusionCharts` * and as such the `this` variable within this function refers to the chart whose * rendering process is complete. * * @callback FusionCharts~renderCallback * * @this FusionCharts * * @param {DOMElement} container - This parameter returns a reference to the container * element within which the chart, gauge or map has been rendered. * * @example * // In this example, we are going to use the render callback * // function to activate a set of buttons that are needed only * // after a chart has been rendered (say, exporting the chart.) * FusionCharts.ready(function () { * var chart = new FusionCharts({ * type: "Column2D", * dataFormat: "jsonurl", * dataSource: "sample-data-source.json", * renderAt: "chart-container" // assuming an element with this id exists * }).render(function () { * // Assuming a disabled button with a specific id already exists. * var button = document.getElementById("export-button"); * button.removeAttribute("disabled"); * }); * }); */ callback.call(that, that.options.containerElement); } catch (e) { setTimeout(function () { throw e; }); } } }, message, style); }; if (!silent && !this.__state.beforeRenderFired) { this.__state.beforeRenderFired = true; /** * This event is raised before a chart is to be rendered. Doing an * `eventObject.preventDefault()` on this event will cancel the rendering process. The rendering * process is triggered when {@link FusionCharts#render} is called on the chart instance. * * @param {DOMElement} container - This contains the reference to the container `HTMLDOMElement` * within which the chart is to be rendered. * @param {numeric|percent} width - Width of the chart in percent or pixels. * @param {numeric|percent} height - Height of the chart in percent or pixels. * * @event FusionCharts#beforeRender * @group chart * @see FusionCharts#render * @see FusionCharts#hasRendered * @see FusionCharts#event:renderComplete * @see FusionCharts#event:renderCancelled * @see FusionCharts#event:rendered * * @example * // Listening using global events * FusionCharts.addEventListener('beforeRender', function (eventObj, argsObj) { * // Prints id of the chart being rendered * console.log("Chart with id " + eventObj.sender.id + " is about to be rendered."); * }); * * // Pass event listener in the FusionCharts constructor * var mychart = new FusionCharts({ * "type": "column2d", * "dataFormat": "json", * "dataSource": { * ... * }, * // Attach event handlers * "events": { * // Attach to beforeRender * "beforeRender": function (eventObj, argsObj) { * console.log("Beginning render of " + eventObj.sender.id); * } * } * }); */ (0, _eventApi.triggerEvent)('beforeRender', this, eventArgs = { container: that.options.containerElement, width: this.width, height: this.height, renderer: this.options.renderer }, void 0, successFn, function () { /** * This event as a result of cancellation of default behavior of * {@link FusionCharts#event:beforeRender} event via it's `eventObject.preventDefault()` * method. * * @see FusionCharts#render * @see FusionCharts#hasRendered * @see FusionCharts#event:beforeRender * @see FusionCharts#event:renderComplete * @see FusionCharts#event:rendered * * @event FusionCharts#renderCancelled * @group chart * * @example * // Listening using global events * FusionCharts.addEventListener('renderCancelled', function (eventObj, argsObj) { * // Prints id of the chart whose rendering was cancelled * console.log("Rendering of chart with id " + eventObj.sender.id + " was cancelled."); * }); * * // Pass event listener in the FusionCharts constructor * var mychart = new FusionCharts({ * "type": "column2d", * "dataFormat": "json", * "dataSource": { * ... * }, * // Attach event handlers * "events": { * // Attach to renderCancelled * "renderCancelled": function (eventObj, argsObj) { * console.log("Cancelled rendering of " + eventObj.sender.id); * } * } * }); * * @param {DOMElement} container - This contains the refernce to the container * `HTMLDOMElement` whithin which the chart is to be rendered. * @param {numeric|percent} width - Width of the chart in percent or pixels. * @param {numeric|percent} height - Height of the chart in percent or pixels. */ (0, _eventApi.triggerEvent)('renderCancelled', that, eventArgs); this.__state.renderInvoked = false; }); } else { successFn(); } return this; }; FusionCharts.prototype._render = function _render(container, chartType, callback, message, msgStyle) { var chartObj = this; chartObj.apiInstance && chartObj.apiInstance.removeJob('resizeScheduled'); if (!chartObj.__state.beforedrawFired) { (0, _eventApi.triggerEvent)('beforedraw', chartObj, {}, void 0, function () { (0, _createChart2['default'])(FusionCharts, chartObj, container, chartType, callback, message, msgStyle); }, function () { /** * This event as a result of cancellation of default behavior of * {@link FusionCharts#event:beforedraw} event via it's `eventObject.preventDefault()` * method. * * * @event FusionCharts#drawCancelled * @group chart * * @example * // Listening using global events * FusionCharts.addEventListener('drawCancelled', function (eventObj, argsObj) { * // Prints id of the chart whose drawing was cancelled * console.log("Drawing of chart with id " + eventObj.sender.id + " was cancelled."); * }); * * // Pass event listener in the FusionCharts constructor * var mychart = new FusionCharts({ * "type": "column2d", * "dataFormat": "json", * "dataSource": { * ... * }, * // Attach event handlers * "events": { * // Attach to drawCancelled * "drawCancelled": function (eventObj, argsObj) { * console.log("Cancelled drawing of " + eventObj.sender.id); * } * } * }); * * @param {DOMElement} container - This contains the refernce to the container * `HTMLDOMElement` whithin which the chart is to be rendered. * @param {numeric|percent} width - Width of the chart in percent or pixels. * @param {numeric|percent} height - Height of the chart in percent or pixels. */ (0, _eventApi.triggerEvent)('drawCancelled', chartObj); }); } else { (0, _createChart2['default'])(FusionCharts, chartObj, container, chartType, callback, message, msgStyle); chartObj.__state.beforedrawFired = true; } }; /** * Calling this function on a chart instance resizes the chart to the specified width or height. * This function is only available for charts that have already rendered. * * Similar to setting the width and height of a chart through the `new FusionCharts()` * constructor, the values for width and height can be passed in number or percentage for this * function. Setting a percentage causes the chart to partially redraw itself when chart container * is resized. * * Calling this function without a value for either width or height will return the current value * of the width or height respectively. * * For example, this function is useful in controlling the dimension of chart based on the change * in dimension of a resizable dialog box. It is also useful in resizing charts for responsive * layouts, based on device orientation change. * * > When dimension is set in percentage, the charts use a very low-profile polling at an interval * > of `300ms` to check whether the chart container has effectively resized. It ignores repeated * > resizes. * * @group chart:resize * * @param {numeric|percent=} [width] - Set the width of the chart in pixels or percent. * @param {numeric|percent=} [height] - Set the height of the chart in pixels or percent. * * @fires FusionCharts#beforeResize * @fires FusionCharts#resized * @fires FusionCharts#resizeCancelled */ FusionCharts.prototype.resizeTo = function resizeTo(width, height, silent) { var chart = this, prevW = chart.width, prevH = chart.height, state = chart.__state, config = chart.apiInstance && chart.apiInstance.config || {}; config.resize = true; if ((typeof width === 'undefined' ? 'undefined' : _typeof(width)) === 'object') { silent = height; height = width.h; width = width.w; } width = width === null || typeof width === 'undefined' ? prevW : width.toString().replace(LENGTH_CLEANUP_RE, ''); height = height === null || typeof height === 'undefined' ? prevH : height.toString().replace(LENGTH_CLEANUP_RE, ''); if (silent !== true) { /** * This event is fired before a chart is to be resized. It is fired either from * {@link FusionCharts#resizeTo} or fired due to change in dimension of the chart's container * element while the dimensions were in percentage format. * * @see FusionCharts#event:resized * @see FusionCharts#resizeTo * @see FusionCharts#event:resizeCancelled * @event FusionCharts#beforeResize * @group chart:resize * * @param {numeric|percent} currentWidth - Current width of the chart in pixels or percentage * @param {numeric|percent} currentHeight Current height of the chart in pixels or percentage * @param {numeric|percent} newWidth - new width of the chart in pixels or percentage * @param {numeric|percent} newHeight - new height of the chart in pixels or percentage */ (0, _eventApi.triggerEvent)('beforeresize', chart, { currentWidth: prevW, currentHeight: prevH, newWidth: width, newHeight: height }, void 0, function () { chart.width = width; chart.height = height; chart.scheduleResize({ width: width, height: height }); /** * Denotes when the chart has been resized either from calling * {@link FusionCharts#resizeTo} or caused due to change in dimension of the chart's * container element while the dimensions were in percentage format. * * @see FusionCharts#event:beforeResize * @see FusionCharts#resizeTo * @event FusionCharts#resized * @group chart:resize * * @param {numeric|percent} width - Width of the chart after being resized * @param {numeric|percent} height - Height of the chart after being resized * @param {numeric|percent} prevWidth - The width of the chart previous to being resized * @param {numeric|percent} prevHeight - The height of the chart previous to being resized * @param {number} originalWidth - Width of the chart in pixels provided when chart was * rendered using {@link FusionCharts#render}. * @param {number} originalHeight - Original render-time height of the chart in pixels. */ chart.apiInstance && chart.apiInstance.addJob('resized' + count++, function () { (0, _eventApi.triggerEvent)('resized', chart, { id: chart.id, width: chart.width, height: chart.height, prevWidth: prevW, prevHeight: prevH, pixelWidth: chart.ref && chart.ref.offsetWidth || 0, pixelHeight: chart.ref && chart.ref.offsetHeight || 0, originalWidth: state.renderedWidth, originalHeight: state.renderedHeight }); }, _schedular.priorityList.postRender); }, function () { /** * This event is triggered when `event.preventDefault()` is called from * {@link FusionCharts#event:beforeResize}. This resuls in cancelling of instructions * received from the {@link FusionCharts#resizeTo} function. * * @see FusionCharts#event:beforeResize * @see FusionCharts#resizeTo * @event FusionCharts#resizeCancelled * @group chart:resize * * @param {numeric|percent} currentWidth - Current width of the chart in pixels or * percentage. * @param {numeric|percent} currentHeight - Current height of the chart in pixels or * percentage. * @param {numeric|percent} cancelledTargetWidth - The width of the chart that was * requested to be set, but was cancelled. * @param {numeric|percent} cancelledTargetHeight - The height of the chart that was * requested to be set, but was cancelled. */ (0, _eventApi.triggerEvent)('resizecancelled', chart, { currentWidth: prevW, currentHeight: prevH, cancelledTargetWidth: width, cancelledTargetHeight: height }); }); } return this; // chain }; /** * Calling this function on an instance of FusionCharts disposes the chart completely. This * removes it from the DOM tree and also clears the entire chart object. Upon successful disposal, * `chartInstance.disposed` is set to `true`. * * > It is recommended that you dispose unused charts to save memory and avoid memory leaks in * > your application or dashboard. * @group chart:dispose * * @fires FusionCharts#beforeDispose * @fires FusionCharts#disposed * @fires FusionCharts#disposeCancelled */ FusionCharts.prototype.dispose = function dispose() { var chart = this, eventArgs = {}; /** * This event is raised when a chart is about to be disposed, i.e., deleted and cleaned from * memory. Usually, this event is triggered by {@link FusionCharts#dispose}. It can also be * internally raised when an already rendered chart is forced to re-render or if a child chart * in a chain of *LinkedCharts* is about to be closed. * * @see FusionCharts#dispose * @see FusionCharts#event:disposed * @see FusionCharts#event:disposeCancelled * @event FusionCharts#beforeDispose * @group chart:dispose */ (0, _eventApi.triggerEvent)('beforeDispose', chart, eventArgs, void 0, function () { chart._addChartDependency('dispose', { scopeOf: chart, resolve: function resolve(_scope) { // Call dispose on the renderer. Renderer should dispose between // the beforeDispose and disposed event. _scope._dispose(); _scope._addChartDependency('dispose', { resolve: function resolve() { return { state: 0 }; } }); _scope._setState(); /** * This event is raised when a chart has been disposed, i.e., deleted and cleaned from * memory. * * Usually, this event is triggered by {@link FusionCharts#dispose}. It can also be * internally raised when an already rendered chart has been forced to re-render or if a * child chart in a chain of *LinkedCharts* is closed. * * > You should dispose unused charts to avoid memory-leaks within your application or * > dashboard. * * @see FusionCharts#dispose * @see FusionCharts#event:beforeDispose * @event FusionCharts#disposed * @group chart:dispose */ (0, _eventApi.triggerEvent)('disposed', _scope, eventArgs); // Dispose all local events (0, _eventApi.disposeEvents)(_scope); // Delete the reference of the item delete FusionCharts.items[_scope.id]; // Remove all variables within this object, making this variable not usable. for (var prop in _scope) { if (_scope.hasOwnProperty(prop)) { delete _scope[prop]; } } // Flag it as disposed _scope.disposed = true; return { state: 0 }; } }); }, function () { /** * This event is cancelled when `eventObject.preventDefault()` is on the event * {@link FusionCharts#event:beforeDispose}. This results in cancelling of dispose of * charts, which is usually issued by {@link FusionCharts#dispose}. * * @see FusionCharts#dispose * @see FusionCharts#event:beforeDispose * @event FusionCharts#disposeCancelled * @group chart:dispose */ (0, _eventApi.triggerEvent)('disposeCancelled', chart, eventArgs); }); }; FusionCharts.prototype._dispose = function _dispose() { var chartObj = this, container, vars = chartObj.jsVars; // do chartAPI instance cleanup if (chartObj.apiInstance) { chartObj.apiInstance.removeJob('resizeScheduled'); chartObj.apiInstance.remove({ instant: true }); delete chartObj.apiInstance; delete vars.instanceAPI; } // Proceed with disposal only when the HTML element exists. if (container = window[chartObj.id]) { purgeDOM(container); // Delete DOM element if (container.parentNode) { container.parentNode.removeChild(container); } } vars.container = null; }; FusionCharts.prototype._config = function _config(items, optionalValue) { var item, chart = this, vars = chart.jsVars, msgs = vars.msgStore, cfg = vars.cfgStore, options = chart.options, chartMessageOldNewMap; chartMessageOldNewMap = { LoadingText: 'loadMessage', ChartNotSupported: 'typeNotSupportedMessage', RenderChartErrorText: 'renderErrorMessage', XMLLoadingText: 'dataLoadStartMessage', ChartNoDataText: 'dataEmptyMessage', LoadDataErrorText: 'dataLoadErrorMessage', InvalidXMLText: 'dataInvalidMessage' }; // If 'items' is not an object, convert it to object. if (typeof items === 'string' && arguments.length > 1) { item = items; items = {}; items[item] = optionalValue; } // store data at respective places. for (item in items) { // if the config is part of chart messages, we store it there. if (typeof msgs[item] !== 'undefined') { msgs[item] = items[item]; } else { // otherwise we store it to the config store. cfg[item.toLowerCase()] = items[item]; } // Update message in constructor parameter. if (chartMessageOldNewMap[item]) { options[chartMessageOldNewMap[item]] = items[item]; } else { options[item] = items[item]; } } }; /** * FusionCharts displays various status messages while rendering a chart. For example, while a * chart's data is being fetched from a remote URL, the chart will display "Retrieving data. * Please wait." These messages can be configured using this function. * * @since 3.2.0 * @group chart * * @param {FusionCharts~chartStatusMessages} option - The option can either be a string specifying * the property that is to be configured, in which case, the second parameter must be provided. * Otherwise, this can be an object having key-value pair of all configuration options. * * @param {string=} [value] - In case the first parameter is a single key as string, this * parameter must be provided as value of that configuration key. */ FusionCharts.prototype.configure = function configure(option, value) { var hash; if (!option) { return; } else if (typeof option === 'string') { hash = {}; hash[option] = value; } else { hash = option; } // Why pass this to an instance method? this._config(hash); }; /** * You can use this function to print individual charts. This function hides all elements on the * page except the chart in concern and then invokes the page printing function * (`window.print ()`). * * > This function works only for charts that have rendered completely, i.e. after * { @link FusionCharts#event:renderComplete } event has fired. * * @param { Object= } [options] - Printing options * @param { boolean= } [options.hideButtons=true] - Hides all buttons on the chart. * @return { boolean } Indicates a failure in the printing process * @group export * @example * // In this snippet of code, we will render a chart on a page and * // call the print method on the chart on click of a button. * FusionCharts.ready (function () { * FusionCharts.render ( { * type: 'column2d', * dataFormat: 'jsonurl', * dataSource: 'data.json', * * // assuming an HTML div element exists on the page * renderAt: 'chart-container-div' * * events: { * renderComplete: function (event) { * // assuming a button exists on page with a specific id * var button = document.getElementById ('print-button'); * button.onclick = function () { * event.sender.print (); * }; * } * } * * }); * }); * * @fires FusionCharts#beforePrint * @fires FusionCharts#printComplete * @fires FusionCharts#printCancelled */ FusionCharts.prototype.print = function print(options) { var chart = this.apiInstance, args = (0, _lib.extend2)({}, options); // Block the button while in printing mode if (chart.config.isPrinting || !chart.config.hasRendered) { return false; } /** * This event is fired before printing has started after calling {@link FusionCharts#print} on a * chart. * The {@link FusionCharts#print} method is used to print individual charts on a page. * @see FusionCharts#event:printComplete * @see FusionCharts#event:printCancelled * @see FusionCharts#print * @event FusionCharts#beforePrint * @group export */ (0, _eventApi.triggerEvent)('BeforePrint', this, args, void 0, function () { var container = chart.getFromEnv('chart-container'), // Temp code to be changed latter. origDisplay = [], origParent = container.parentNode, body = document.body || document.getElementsByTagName('body')[0], childNodes = body.childNodes, length, lists, list, i, chartMenuBar; chart.config.isPrinting = true; // hide all body content (0, _lib.fcEach)(childNodes, function (node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = 'NONE'; } }); // hide print and export buttons before capturing export data if (args.hideButtons !== false) { // todo chartMenuBar = chart.getChildren('chartMenuBar'); // If chartMenuBar is present, hide the menu container if (chartMenuBar) { lists = chartMenuBar[0].getChildren('tool'); for (i = 0, length = lists.length; i < length; i++) { lists[0].getChildren('listContainer')[0].hide(); } } } // pull out the chart body.appendChild(container); // print window.print(); // allow the browser to prepare before reverting setTimeout(function () { // todo // show print and export buttons before capturing export data list && (list.config.container.style.display = 'visible'); // put the chart back in origParent.appendChild(container); // restore all body content (0, _lib.fcEach)(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); if (args.hideButtons !== false) { // todo list && (list.config.container.style.display = 'visible'); } chart.config.isPrinting = false; /** * This event is fired after user accepts or cancels the browser's print dialog box that * was originally triggered by calling {@link FusionCharts#print} on the chart. The * {@link FusionCharts#print} method is used to print individual charts on a page. * @see FusionCharts#event:beforePrint * @see FusionCharts#event:printCancelled * @see FusionCharts#print * @event FusionCharts#printComplete * @group export */ (0, _eventApi.triggerEvent)('PrintComplete', chart.getFromEnv('chartInstance'), args); }, 1000); }, function () { /** * This event is fired when the printing request from a chart has been * __programmatically__ cancelled by calling `eventObject.preventDefault()` from the * {@link FusionCharts#events:beforePrint} event. * * > Note that this event is not fired when user clicks on the "cancel" button of the * browser-triggered print dialog box resulting from calling the {@link FusionCharts#print} * function. * @see FusionCharts#event:beforePrint * @see FusionCharts#event:printComplete * @see FusionCharts#print * @event FusionCharts#printCancelled * @group export */ (0, _eventApi.triggerEvent)('PrintCancelled', chart.getFromEnv('chartInstance'), args); }); }; /** * Fetch the SVG of a chart as a string. This function returns the SVG that has been created by * FusionCharts when rendering the chart. * > Note that this function is only available for a chart that has already been rendered. * * @group export * * @return { string } - SVG string */ FusionCharts.prototype.getSVGString = function getSVGString(callback, config) { var chartContainer = this, chart = chartContainer.apiInstance, keepImages, paper = chart && chart.getFromEnv('paper'); if (config && config.keepImages) { keepImages = true; } if (typeof callback === 'function') { chart.addJob('getSVG', function () { callback(paper && paper.toSVG && paper.toSVG(keepImages)); }, _schedular.priorityList.postRender); } else { if (paper && paper.toSVG) { return paper.toSVG(keepImages); } else { return ''; } } }; /** * Controls a chart's automatic resizing ability when its dimension is in percentage. * * This function has to be called before a chart has rendered. * Using { @link FusionCharts#hasRendered } can be useful here. * * If this function is called without parameter, it returns the current state of resize lock. * * @group chart:resize * * @param { boolean= } [state] - Sending `true` for this parameter causes the automatic percentage * based resize to be turned off. If resize is already locked, sending `false` unlocks it. * * @return { boolean } - Returns whether the chart's automatic resize feature has been locked or * not. */ FusionCharts.prototype.lockResize = function lockResize(state) { if (typeof state !== 'boolean') { return !!this.jsVars.resizeLocked; } return this.jsVars.resizeLocked = state; }; /** * Shows a text message on a chart. * * @param { string } text The text message that needs to be displayed. * @param { boolean= } [modal=false] Boolean value whether to show the * message on an overlay or on the chart. Defaults to `false`. * @param { boolean= } [cancelable=false] Boolean value applicable only if modal is `true`. If set * to true the modal can be closable on click. Defaults to `false`. * @param { object } [customAttrs] For styling the message text. It takes font, fontSize, color * and alpha as object keys. */ FusionCharts.prototype.showChartMessage = function showChartMessage(text, modal, cancelable) { var customAttrs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var chartInstance = this, chart = chartInstance.apiInstance, showMessageFn = function showMessageFn() { chartInstance._showChartMessage(text, modal, cancelable, customAttrs); }; chart && (chart.getName() === 'base' ? chartInstance.addEventListener('renderComplete', showMessageFn) : showMessageFn()); return text; }; /** * helper fn to showChartMessage */ FusionCharts.prototype._showChartMessage = function _showChartMessage(text, modal, cancelable) { var customAttrs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var chartInstance = this, vars = chartInstance.jsVars, chart = chartInstance.apiInstance, options = chartInstance.options, attrs = void 0, _helperFn = function _helperFn() { if (modal && chart && chart.config.hasRendered) { chart._show && chart._show(); chartInstance.showMessage(text, attrs, cancelable); } else { chart._hide && chart._hide(); chart.setChartMessage(text, { _chartMessageStyle: attrs }); chart.drawChartMessage(); } }; chart._hideChartMessage(); if (typeof text === 'undefined') { chartInstance.hideChartMessage(); return; } attrs = { fontFamily: (0, _lib.pluck)(customAttrs.font, options.baseChartMessageFont, 'Verdana,sans'), fontSize: (0, _lib.pluck)(customAttrs.fontSize, options.baseChartMessageFontSize, 10), color: (0, _lib.pluck)(customAttrs.color && (0, _lib.convertColor)(customAttrs.color, customAttrs.alpha), options.baseChartMessageColor) }; if (vars.msgStore[text]) { text = vars.msgStore[text]; } chart.addJob('showMsg', _helperFn, _schedular.priorityList.postRender); }; FusionCharts.prototype._resize = function _resize() { var vars = this.jsVars, instanceAPI = this.apiInstance, container = vars.container; this.__state.resize = true; if (instanceAPI) { // used by getMouseCoordinate instanceAPI.config.elScroll = false; // Use setState API to set the state of chart instanceAPI.getFromEnv('animationManager').setAnimationState('resize'); // set the charts width and height in the env instanceAPI.addToEnv('chartWidth', container.offsetWidth); instanceAPI.addToEnv('chartHeight', container.offsetHeight); // instanceAPI.asyncDraw(); this._addChartDependency('resize', { resolve: function resolve() { return { state: 3 }; } }); } else { // todo: remove this legacy code // @todo: have to validate if it is needed // createChart(FusionCharts, vars.fcObj, container, vars.type, void 0, void 0, false, true); this._addChartDependency('resize', { resolve: function resolve() { return { state: 1 }; } }); } this._setState(); this.__state.resize = false; }; FusionCharts.prototype.hideChartMessage = function hideChartMessage() { var chartObj = this, chart = chartObj.apiInstance; chart._hideChartMessage(); chart._show && chart._show(); }; FusionCharts.prototype.showMessage = function showMessage() { var msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var attrs = arguments[1]; var cancelable = arguments[2]; var chart = this.apiInstance, config = chart.config, messageLayer, messageLayerDummy, paper = chart.getFromEnv('paper'), smartLabel = chart.getFromEnv('smartLabel'), animationManager = chart.getFromEnv('animationManager'), messageText = chart.getGraphicalElement('messageText'), messageVeil = chart.getGraphicalElement('messageVeil'), w = paper.width, h = paper.height, text; // Create/reuse message group messageLayerDummy = chart.getChildContainer('messageGroup'); animationManager.setAnimationState('showmessage'); messageLayer = animationManager.setAnimation({ el: messageLayerDummy || 'group', attr: { name: 'messageGroup' }, component: chart, label: 'group' }); messageLayer.show().toFront(); // If messageLayer not presently previously if (!messageLayerDummy) { chart.addChildContainer('messageGroup', messageLayer); } // create the layer at the first call messageVeil = animationManager.setAnimation({ el: messageVeil || 'rect', attr: { x: 0, y: 0, width: w, height: h, fill: 'rgba(0,0,0,0.2)', stroke: 'none' }, container: messageLayer, component: chart, label: 'rect' }); messageVeil.off('fc-click', messageLayer.hide); messageVeil.show().toFront().attr('cursor', cancelable ? _lib.POINTER : 'default'); cancelable && messageVeil.on('fc-click', chart._hideChartMessage, chart); chart.addGraphicalElement('messageVeil', messageVeil); smartLabel.setStyle(attrs); text = smartLabel.getSmartText(msg, w - (config.marginRight || 0) - (config.marginLeft || 0), h - (config.marginTop || 0) - (config.marginBotton || 0)); // Create/reuse messageText messageText = animationManager.setAnimation({ el: messageText || 'text', attr: { 'font-size': attrs.fontSize, 'font-family': attrs.fontFamily, fill: attrs.color, text: text.text, 'line-height': 14, x: w / 2, y: h / 2 }, container: messageLayer, component: chart, label: 'text' }); messageText.attr('cursor', cancelable ? _lib.POINTER : 'default')[cancelable ? 'click' : 'unclick'](chart._hideChartMessage, chart).show().toFront(); chart.addGraphicalElement('messageText', messageText); }; FusionCharts.prototype.scheduleResize = function scheduleResize(size) { var chartObj = this, container = chartObj.ref, cssSize, chart = chartObj.apiInstance; // Set the sizes of the DOM elements for the resize and fire related // commands needed for resize. if (!container) { return; } chartObj._addChartDependency('resize', { resolve: function resolve() { return { state: 2 }; } }); // resize chart async so that consecutive resizes can be blocked chart.addJob('resizeScheduled', function () { cssSize = (0, _lib.normalizeCSSDimension)(size.width, size.height, container); if (typeof size.width !== 'undefined') { container.style.width = cssSize.width; } if (size.height !== 'undefined') { container.style.height = cssSize.height; } chartObj._resize(); }, _schedular.priorityList.instant); }; return FusionCharts; }(); FusionCharts.id = 'FusionCharts'; FusionCharts.options = { html5ScriptNameSuffix: '.js', html5ScriptNamePrefix: 'fusioncharts.', /* export options */ 'export': { /* whether svgDeCanvo module will be used for client side export or not */ useCanvas: false }, /** * @deprecated Since 3.13.0 - Use FusionCharts.setScriptBaseURI and FusionCharts.getScriptBaseURI * instead. */ scriptBaseUri: function () { var baseUri = getScriptBaseUri(SCRIPT_NAME_RE); if (typeof baseUri === 'undefined') { /** * FusionCharts JavaScript Library automatically determines the location where it was loaded * from within the server. This it does by probing the ` * * * * * * * *
*
* * */ outputTo: function outputTo(debuggerCallback) { // Check whether the logger is a function or not. If it is a // function, we set a reference to it to be used later as the // logger function. if (typeof debuggerCallback === 'function') { /** * The parameters passed on to the debugger callback function is in line with the value of * {@link FusionCharts.debugger~outputFormats} specified via {@link FusionCharts.debugger.outputTo}. * @callback FusionCharts.debugger~debuggerCallback * * @param {...*} outputFormatParameters - The parameters passed to the callback depend upon the * debugger output format set. The details regarding the different variants of parameter is at * {@link FusionCharts.debugger~outFormats}. */ logger.outputTo = debuggerCallback; } else if (debuggerCallback === null) { // In case user sends 'null' as the value of the logger function, // we can assume that user wants not to log any output. // _global.core[DEBUGGER].enable(false); FusionCharts[DEBUGGER].enable(false); delete logger.outputTo; } }, /** * The FusionCharts debugger is not enabled by default. This method allows us to enable the debugger and * also optionally provide basic debugger configuration. * * The debugger works in conjunction with the browser's JavaScript console or any other special console-like * implementation that you may have. To enable the debugger, call this function and pass a callback that * outputs the message to the JavaScript console. The code would log the activities of every chart and the * entire framework. * * ``` * FusionCharts['debugger'].enable(true, function (message) { * console.log(message); * }); * ``` * * If you have added this code right after including the `fusioncharts.js` script in a page that renders a * single chart with id "myChart", your output would look somewhat like: * * ``` * #1 [FusionCharts] fired "ready" event. * #2 [myChart] fired "beforeinitialize" event. * #3 [myChart] fired "beforedataupdate" event. * #4 [myChart] fired "dataupdated" event. * #5 [myChart] fired "initialized" event. * #6 [myChart] fired "beforerender" event. * #7 [myChart] fired "internal.loaded" event. * #8 [myChart] fired "internal.drawstart" event. * #9 [myChart] fired "dataloaded" event. * #10 [myChart] fired "internal.domelementcreated" event. * #11 [myChart] fired "loaded" event. * #12 [myChart] fired "drawcomplete" event. * #13 [myChart] fired "rendercomplete" event. * ``` * * The output clearly shows that FusionCharts declared itself as `ready` and then the chart followed the * routine of initialising itself, loading data, loading dependencies and then completing the rendering * process. Had there been any error, it would have reflected in the output. * * > The debugger is not intended to be kept enabled on a production server since it has performance and * > memory requirement overhead. It is meant for pre-production debugging only. * * @param {boolean} state - Specifies whether to enable logging of debug information. * * @param {FusionCharts.debugger~debuggerCallback=} [outputTo] - The function to which the debugger output * will be passed on. * * @param {FusionCharts.debugger~outputFormats=} [outputFormat="text"] - Can be one of the accepted format * names such as "text", "verbose", "event". * * @return {boolean} The current 'enable' state of the debugger. */ enable: function enable(state, outputTo, outputFormat) { // Allow object to be sent as configuration parameter. var config; // In case the first parameter is object and the only parameter, // we copy its contents to various linear parameters and save // a copy of the object for later use. if ((typeof state === 'undefined' ? 'undefined' : _typeof(state)) === 'object' && arguments.length === 1) { config = state; state = config.state; outputTo = config.outputTo; outputFormat = config.outputFormat; } // In case user send in only one parameter and that too a // function, we can assume that he wants to use it as a logger // function and also enable logging. if (typeof state === 'function') { if (typeof outputTo === 'string' && (arguments.length === 2 || config)) { outputFormat = outputTo; } outputTo = state; state = true; } // In case user sends in a valid parameter to change the current // state of the debugger, we update the debugger state. if (typeof state === 'boolean' && state !== logger.enabled) { logger.enabled = state; if (logger.enabled) { (0, _eventApi.addListener)('*', logger.outputHandler); } else { (0, _eventApi.removeListener)('*', logger.outputHandler); } } // If user sends in a parameter for the logger parameter, we // set it to the logger function reference. if (typeof outputTo === 'function') { logger.outputTo = outputTo; } // Set output format if needed. // _global.core[DEBUGGER].outputFormat(outputFormat); FusionCharts[DEBUGGER].outputFormat(outputFormat); // Finally send the current debugger state to the user. return logger.enabled; } }; }, name: 'Debugger', type: 'extension', requiresFusionCharts: true }; /***/ }), /* 264 */ /***/ (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; }; /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var _centerLabelExtension = __webpack_require__(265); var _centerLabelExtension2 = _interopRequireDefault(_centerLabelExtension); var _lib = __webpack_require__(125); var _schedular = __webpack_require__(136); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Checks if component is of type chart * @param {Object} component - Checks if paramter is of type chart * @return {boolean} Returns if component is of type chart */ var isDoughnut2D = function isDoughnut2D(component) { return component.getName() === 'Doughnut2D'; }, isMultiLevelPie = function isMultiLevelPie(component) { return component.getName() === 'MultilevelPie'; }, isChartAPI = function isChartAPI(component) { return component.getType() === 'chartAPI'; }, isDataset = function isDataset(component) { return component.getType() === 'dataset'; }, count = 0, UNDEF = void 0; /** * Sets the center label in Dougnut 2D chart. The label cosmetics are configurable via the second * optional parameter, which accepts a host of related properties. * * > Available on `doughnut` chart only. * * @group chart:pie-center-label * * @param {string} labelText - The text to be displayed at doughnut center. * @param {Object} [options] - The optional parameter that holds a host of configurable params * with most them being cosmetic properties of the center label. The properties are case sensitive. * * {string} [options.font] - Sets the font face of the label. * {string} [options.fontSize] - Defines the font size of the label. * {boolean} [options.bold] - Specifies of whether the label be bold. * {boolean} [options.italic] - Specifies of whether the label be in italic. * {hexcolor} [options.color] - Sets the color of the label text. * {alpha} [options.alpha] - Sets the opacity of the label text. * {hexcolor} [options.hoverColor] - Sets the hover color of the label text. * {alpha} [options.hoverAlpha] - Sets the hover opacity of the label text. * {hexcolor} [options.bgColor] - Sets the color of the label background. * {alpha} [options.bgAlpha] - Sets the opacity of the label background. * {hexcolor} [options.borderColor] - Sets the color of the label background border. * {alpha} [options.borderAlpha] - Sets the opacity of the label background border. * {number} [options.borderThickness] - Sets the thickness of the label background border. * {number} [options.borderRadius] - Sets the radius for rounded label background. * {number} [options.padding] - The padding between extremities of the label and inner periphery * of the doughnut. For rectangular label background, it's relative to any of the 4 corners. While for * circular background, it's the gap between the 2 concentric circles, background border and inner * periphery. * {number} [options.textPadding] - For rectangular label background, it's the gutter between * the text and the background border. While for circular background, it's the minimum space between * the background border and the containing circle of the text. * {string} [options.toolText] - Sets the tooltext for the label. * * @fires FusionCharts#centerLabelChanged * * @example * // Render a doughnut 2d chart and set center label with some * // configuring params on click of a button * FusionCharts.ready(function () { * var chart = new FusionCharts({ * type: "doughnut2d", * renderAt: "chart-container", * dataSource: "data.json", * dataFormat: "jsonurl" * }).render(); * * // Assign the functionality of setting the center label when clicked on * // a button (with an id set-center-label). * document.getElementById("set-center-label").onclick = function () { * chart.centerLabel("The central label", {bold: true, toolText: "center label tooltext"}); * }; * }); */ function centerLabel(labelText, options) { var chart = this.apiInstance, dataset = chart.getChildren('dataset')[0], children = dataset.getChildren(), centerLabelComp = children.centerLabel && children.centerLabel[0], chartConfig = chart.config, _helperFn = function _helperFn() { var seriesData = chart.getDatasets()[0], config = seriesData.config, piePlotOptions = config.piePlotOptions, innerSize = piePlotOptions.innerSize, centerLabelConfig, key; centerLabelConfig = centerLabelComp.config; if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') { options = centerLabelConfig; } else { // Create the config cosmetics object from those obtained // from argument and default values for (key in centerLabelConfig) { options[key] === UNDEF && (options[key] = centerLabelConfig[key]); } centerLabelConfig = Object.assign(centerLabelConfig, options); } options.label = labelText; centerLabelConfig.label = labelText; seriesData.centerLabelConfig = centerLabelConfig; innerSize && centerLabelComp && centerLabelComp.draw(labelText || ''); }; if (centerLabelComp === UNDEF) { (0, _lib.componentFactory)(dataset, _centerLabelExtension2['default'], 'centerLabel', 1, [chartConfig]); centerLabelComp = children.centerLabel && children.centerLabel[0]; } chart.addJob('eiMethods-center-lebel' + count++, _helperFn, _schedular.priorityList.postRender); } exports['default'] = { extension: function extension(FusionCharts) { var isApplicableChart; FusionCharts.addEventListener('instantiated', function (event) { var component = event.sender; !isApplicableChart && (isApplicableChart = isChartAPI(component) && (isDoughnut2D(component) || isMultiLevelPie(component))); if (isApplicableChart && isDataset(component)) { component.registerFactory('centerLabel', function () { var chartConfig = component.getFromEnv('chartConfig'), chartInstance = component.getFromEnv('chartInstance'), hasCenterLabel = !!(chartConfig.centerlabel || chartConfig.defaultcenterlabel); chartInstance.centerLabel = centerLabel; (0, _lib.componentFactory)(component, _centerLabelExtension2['default'], 'centerLabel', hasCenterLabel ? 1 : 0, [chartConfig]); isApplicableChart = UNDEF; }); } }); }, name: 'CenterLabelExtension', type: 'extension', requiresFusionCharts: true }; /***/ }), /* 265 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _centerLabel = __webpack_require__(266); var _centerLabel2 = _interopRequireDefault(_centerLabel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, HIDDEN = 'hidden', VISIBLE = 'visible'; function replaceMacros(text, macrosArr, valuesArr) { if (text) { var i = macrosArr.length || 0, regExpression; while (i--) { regExpression = new RegExp(macrosArr[i], 'gi'); text = text.replace(regExpression, valuesArr[i]); } } return text; } (0, _dependencyManager.addDep)({ name: 'centerLabelAnimation', type: 'animationRule', extension: _centerLabel2['default'] }); var CenterLabel = function (_ComponentInterface) { _inherits(CenterLabel, _ComponentInterface); function CenterLabel() { _classCallCheck(this, CenterLabel); return _possibleConstructorReturn(this, _ComponentInterface.apply(this, arguments)); } /** * Sets the name of the component * @return {string} name */ CenterLabel.prototype.getName = function getName() { return 'centerLabel'; }; /** * Sets the type of the component * @return {string} type */ CenterLabel.prototype.getType = function getType() { return 'centerLabel'; }; CenterLabel.prototype.configure = function configure(config) { var chartAttr = this.getFromEnv('chart-attrib'), numberFormatter = this.getFromEnv('number-formatter'), dataLabelStyle = config.dataLabelStyle, centerLabel = this; centerLabel.config = { label: (0, _lib.parseUnsafeString)((0, _lib.pluck)(chartAttr.defaultcenterlabel, '')), font: (0, _lib.pluck)(chartAttr.centerlabelfont, dataLabelStyle.fontFamily), fontSize: (0, _lib.pluckNumber)(chartAttr.centerlabelfontsize, parseInt(dataLabelStyle.fontSize, 10)), color: (0, _lib.getFirstColor)((0, _lib.pluck)(chartAttr.centerlabelcolor, chartAttr.valuefontcolor, config.style.inCanvasStyle.color, '555555')), alpha: (0, _lib.pluckNumber)(chartAttr.centerlabelalpha, 100), bold: (0, _lib.pluckNumber)(chartAttr.centerlabelbold, dataLabelStyle.fontWeight), italic: (0, _lib.pluckNumber)(chartAttr.centerlabelitalic, dataLabelStyle.style), bgColor: (0, _lib.pluck)(chartAttr.centerlabelbgcolor, ''), bgAlpha: (0, _lib.pluckNumber)(chartAttr.centerlabelbgalpha, 100), borderColor: (0, _lib.pluck)(chartAttr.centerlabelbordercolor, dataLabelStyle.borderColor), borderAlpha: (0, _lib.pluckNumber)(chartAttr.centerlabelborderalpha, 100), borderThickness: (0, _lib.pluckNumber)(chartAttr.centerlabelborderthickness, dataLabelStyle.borderThickness), borderRadius: (0, _lib.pluckNumber)(chartAttr.centerlabelborderradius, dataLabelStyle.borderRadius), textPadding: (0, _lib.pluckNumber)(chartAttr.centerlabeltextpadding, dataLabelStyle.borderPadding), padding: (0, _lib.pluckNumber)(chartAttr.centerlabelpadding, 2), bgOval: (0, _lib.pluckNumber)(chartAttr.centerlabelbgoval, 0), shadow: (0, _lib.pluckNumber)(chartAttr.showcenterlabelshadow, 0), // getFirstColor(pluck(chartAttr.centerlabelhovercolor, chartAttr.centerlabelcolor, '555555')), hoverColor: chartAttr.centerlabelhovercolor && (0, _lib.getFirstColor)((0, _lib.pluck)(chartAttr.centerlabelhovercolor)), hoverAlpha: (0, _lib.pluckNumber)(chartAttr.centerlabelhoveralpha), toolText: (0, _lib.parseUnsafeString)((0, _lib.pluck)(chartAttr.centerlabeltooltext, _lib.BLANKSTRING)) }; centerLabel.addExtEventListener('datasetrollover', function (event) { var dataJSON = event.sender.getFromEnv('dataSource'), data = event.data, label = (0, _lib.pluck)(replaceMacros(dataJSON.chart.centerlabel, ['\\$value', '\\$percentValue', '\\$displayValue', '\\$label'], [numberFormatter.scale(data.value), data.pValue, data.displayValue, data.label]), ''); centerLabel.draw(label, false); }, this.getFromEnv('chart').getDatasets()[0]); centerLabel.addExtEventListener('datasetrollout', function (event) { var centerlabel = event.sender.config.label, label = (0, _lib.pluck)(centerlabel, ''); centerLabel.draw(label, false); }, this.getFromEnv('chart').getDatasets()[0]); }; /** * function to draw label on given co-ordinate. * it may take optional label text if it is required. * In case of specific label text when it is needed; for example: * custom label text on hover on a plot we can set optional label text * @param {string} labelText String to show as centerlabel */ CenterLabel.prototype.draw = function draw(labelText) { var centerLabel = this, chart = centerLabel.getFromEnv('chart'), cx = chart.config.canvasLeft + chart.config.canvasWidth * 0.5, cy = chart.config.canvasTop + chart.config.canvasHeight * 0.5, dx = chart.getDatasets()[0].config.innerSize, dy = chart.getDatasets()[0].config.innerSize, dataSet = chart.getDatasets()[0], seriesData = dataSet.config, labelConfig = this.config, animationManager = centerLabel.getFromEnv('animationManager'), smartLabel = centerLabel.getFromEnv('smartLabel'), centerLabelGraphicsDummy = this.getGraphicalElement('centerLabel'), centerLabelGraphics = centerLabelGraphicsDummy, centerLabelBgGraphics = this.getGraphicalElement('centerLabelBg'), grp = chart.getChildContainer('plotGroup'), labelPadding = labelConfig.padding, textpadding = labelConfig.textPadding * 2, cssObj = { fontFamily: labelConfig.font, fontSize: labelConfig.fontSize + 'px', lineHeight: 1.2 * labelConfig.fontSize + 'px', fontWeight: labelConfig.bold ? 'bold' : '', fontStyle: labelConfig.italic ? 'italic' : '' }, txtW = (dx * 0.5 - labelPadding) * 1.414 - textpadding, txtH = (dy * 0.5 - labelPadding) * 1.414 - textpadding, smartLabelObj, toolTipController = centerLabel.getFromEnv('toolTipController'); labelText = (0, _lib.pluck)(labelText, labelConfig.label); smartLabel.setStyle(cssObj); smartLabel.useEllipsesOnOverflow(chart.config.useEllipsesWhenOverflow); smartLabelObj = smartLabel.getSmartText(labelText, txtW, txtH); if (labelText) { if (labelConfig.bgOval) { centerLabelBgGraphics = animationManager.setAnimation({ el: centerLabelBgGraphics || 'circle', attr: { cx: cx, cy: cy, r: dx * 0.5 - labelPadding, visibility: VISIBLE, container: grp, fill: (0, _lib.hashify)(labelConfig.bgColor), 'fill-opacity': labelConfig.bgAlpha / 100, stroke: (0, _lib.hashify)(labelConfig.borderColor), 'stroke-width': labelConfig.borderThickness, 'stroke-opacity': labelConfig.borderAlpha / 100 }, component: centerLabel }); } centerLabelGraphics = animationManager.setAnimation({ el: centerLabelGraphicsDummy || 'text', component: centerLabel, container: grp, css: cssObj, attr: { x: cx, y: cy, text: smartLabelObj.text, visibility: VISIBLE, direction: chart.config.textDirection, // title: labelConfig.toolText ? '' : smartLabelObj.tooltext || '', fill: (0, _lib.toRaphaelColor)({ FCcolor: { color: labelConfig.color, alpha: labelConfig.alpha } }), 'text-bound': labelConfig.bgOval ? 'none' : [(0, _lib.toRaphaelColor)({ FCcolor: { color: labelConfig.bgColor, alpha: labelConfig.bgAlpha } }), (0, _lib.toRaphaelColor)({ FCcolor: { color: labelConfig.borderColor, alpha: labelConfig.borderAlpha } }), labelConfig.borderThickness, labelConfig.textPadding, labelConfig.borderRadius] }, label: 'text' }); toolTipController.enableToolTip(centerLabelGraphics, labelConfig.toolText || smartLabelObj.tooltext); } else { centerLabelGraphics && animationManager.setAnimation({ el: centerLabelGraphics, attr: { 'visibility': HIDDEN }, component: centerLabel }); centerLabelBgGraphics && animationManager.setAnimation({ el: centerLabelBgGraphics, attr: { 'visibility': HIDDEN }, component: centerLabel }); } if (!centerLabelGraphicsDummy) { centerLabel.addEventListener('fc-mouseover', function () { centerLabel._centerLabelRollover(chart); }); centerLabel.addEventListener('fc-mouseout', function () { centerLabel._centerLabelRollout(chart); }); centerLabel.addEventListener('fc-click', function () { centerLabel._centerLabelClick(chart); }); centerLabel.addGraphicalElement('centerLabel', centerLabelGraphics); centerLabel.addGraphicalElement('centerLabelBg', centerLabelBgGraphics); } else { centerLabelGraphics.attr('text') !== labelText && centerLabel.centerLabelChange(labelText); } seriesData.lastCenterLabelConfig = labelConfig; seriesData.centerLabelConfig = labelConfig; }; /** * helper function to draw * when element is present but text is changed then this function is excuted * @param {text} labelText label text */ CenterLabel.prototype.centerLabelChange = function centerLabelChange(labelText) { var centerLabelapi = this, chart = centerLabelapi.getFromEnv('chart'), chartConfig = chart.config, chartInstance = centerLabelapi.getFromEnv('chartInstance'), eventArgs = { height: chartConfig.height, width: chartConfig.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: chartInstance.id, renderer: chartInstance.args.renderer, container: chartInstance.options.containerElement, centerLabelText: labelText }; /** * This event is fired on change of label at center of doughnut 2D. * * > Available on `doughnut` chart only. * * @group chart:pie-center-label * @event FusionCharts#centerLabelChanged * * @param {string} centerLabelText - is the text for display at center label * @param {number} chartX - is the relative X-Cordinate to chart container where the chart was clicked * @param {number} chartY - is the relative Y-Cordinate to chart container where the chart was clicked. * @param {string} container - is the DOM element where the chart is being rendered. * @param {numeric|percent} height - height of the chart * @param {numeric|percent} width - width of the chart * @param {string} id - is the chart id * @param {number} pageX - is the relative X-Cordinate to screen where the chart is clicked * @param {number} pageY - is the relative Y-Cordinate to screen where the chart is clicked * @param {number} pixelHeight - is the height of the DOM element where the chart is being rendered in * pixels * @param {number} pixelWidth - is the width of the DOM element where the chart is being rendered in * pixels * @param {string} renderer - tells if the chart is rendered using JavaScript or Flash */ chart.fireChartInstanceEvent('centerLabelChanged', eventArgs); }; /** * callback function on mouse over event * @param {Object} chart - Takes chart object as input */ CenterLabel.prototype._centerLabelRollover = function _centerLabelRollover(chart) { var chartConfig = chart.config, chartInstance = chart.getFromEnv('chartInstance'), labelConfig = this.config, cLabel = this, eventArgs = { height: chartConfig.height, width: chartConfig.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: chartInstance.id, renderer: chartInstance.args.renderer, container: chartInstance.options.containerElement, centerLabelText: labelConfig && labelConfig.label }; /** * This event is fired on mouse rollover on label at center of doughnut 2D. * * > Available on `doughnut` chart only. * * @group chart:pie-center-label * @event FusionCharts#centerLabelRollover * * @param {string} centerLabelText - is the text for display at center label * @param {number} chartX - is the relative X-Cordinate to chart container where the chart was clicked * @param {number} chartY - is the relative Y-Cordinate to chart container where the chart was clicked. * @param {string} container - is the DOM element where the chart is being rendered. * @param {numeric|percent} height - height of the chart * @param {numeric|percent} width - width of the chart * @param {string} id - is the chart id * @param {number} pageX - is the relative X-Cordinate to screen where the chart is clicked * @param {number} pageY - is the relative Y-Cordinate to screen where the chart is clicked * @param {number} pixelHeight - is the height of the DOM element where the chart is being rendered in * pixels * @param {number} pixelWidth - is the width of the DOM element where the chart is being rendered in * pixels * @param {string} renderer - tells if the chart is rendered using JavaScript or Flash */ this.getFromEnv('paper').attr('text') && chart.fireChartInstanceEvent('centerLabelRollover', eventArgs, UNDEF, cLabel.hoverOnCenterLabel.bind(cLabel, chart)); }; /** * callback function on mouse out event * @param {Object} chart - Takes chart object as input */ CenterLabel.prototype._centerLabelRollout = function _centerLabelRollout(chart) { var chartConfig = chart.config, cLabel = this, chartInstance = chart.getFromEnv('chartInstance'), labelConfig = this.config, eventArgs = { height: chartConfig.height, width: chartConfig.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: chartInstance.id, renderer: chartInstance.args.renderer, container: chartInstance.options.containerElement, centerLabelText: labelConfig && labelConfig.label }; /** * This event is fired on mouse rollout from label at center of * doughnut 2D. * * > Available on `doughnut` chart only. * * @group chart:pie-center-label * @event FusionCharts#centerLabelRollout * * @param {string} centerLabelText - is the text for display at center label * @param {number} chartX - is the relative X-Cordinate to chart container where the chart was clicked * @param {number} chartY - is the relative Y-Cordinate to chart container where the chart was clicked. * @param {string} container - is the DOM element where the chart is being rendered. * @param {numeric|percent} height - height of the chart * @param {numeric|percent} width - width of the chart * @param {string} id - is the chart id * @param {number} pageX - is the relative X-Cordinate to screen where the chart is clicked * @param {number} pageY - is the relative Y-Cordinate to screen where the chart is clicked * @param {number} pixelHeight - is the height of the DOM element where the chart is being rendered in * pixels * @param {number} pixelWidth - is the width of the DOM element where the chart is being rendered in * pixels * @param {string} renderer - tells if the chart is rendered using JavaScript or Flash */ this.getFromEnv('paper').attr('text') && chart.fireChartInstanceEvent('centerLabelRollout', eventArgs, UNDEF, cLabel.hoverOffCenterLabel.bind(cLabel, chart)); }; /** * callback function on mouse click event * @param {Object} chart - Takes chart object as input */ CenterLabel.prototype._centerLabelClick = function _centerLabelClick(chart) { var chartConfig = chart.config, chartInstance = chart.getFromEnv('chartInstance'), eventArgs = { height: chartConfig.height, width: chartConfig.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: chartInstance.id, renderer: chartInstance.args.renderer, container: chartInstance.options.containerElement }, labelConfig = void 0; labelConfig = this.config; eventArgs.centerLabelText = labelConfig && labelConfig.label; /** * This event is fired on click on label at center of doughnut 2D. * * > Available on `doughnut` chart only. * * @group chart:pie-center-label * @event FusionCharts#centerLabelClick * * @param {string} centerLabelText - is the text for display at center label. * @param {number} chartX - is the relative X-Cordinate to chart container where the chart was clicked. * @param {number} chartY - is the relative Y-Cordinate to chart container where the chart was clicked. * @param {string} container - is the DOM element where the chart is being rendered. * @param {numeric|percent} height - height of the chart * @param {numeric|percent} width - width of the chart * @param {string} id - is the chart id * @param {number} pageX - is the relative X-Cordinate to screen where the chart is clicked * @param {number} pageY - is the relative Y-Cordinate to screen where the chart is clicked * @param {number} pixelHeight - is the height of the DOM element where the chart is being rendered in * pixels * @param {number} pixelWidth - is the width of the DOM element where the chart is being rendered in * pixels * @param {string} renderer - tells if the chart is rendered using JavaScript or Flash */ this.getFromEnv('paper').attr('text') && chart.fireChartInstanceEvent('centerLabelClick', eventArgs); }; /** * callback function to centerLabelRollover event * @param {Object} chart - Takes chart object as input */ CenterLabel.prototype.hoverOnCenterLabel = function hoverOnCenterLabel(chart) { var dataSet = chart.getChildren('dataset')[0], seriesData = dataSet.config, labelConfig = seriesData.lastCenterLabelConfig; if (labelConfig.hoverColor || labelConfig.hoverAlpha) { this.getGraphicalElement('centerLabel').attr({ fill: (0, _lib.toRaphaelColor)({ FCcolor: { color: labelConfig.hoverColor || labelConfig.color, alpha: labelConfig.hoverAlpha || labelConfig.alpha } }) }); } }; /** * callback function to centerLabelRollout event * @param {Object} chart - Takes chart object as input */ CenterLabel.prototype.hoverOffCenterLabel = function hoverOffCenterLabel(chart) { var dataSet = chart.getChildren('dataset')[0], seriesData = dataSet.config, labelConfig = seriesData.lastCenterLabelConfig; if (labelConfig.hoverColor || labelConfig.hoverAlpha) { this.getGraphicalElement('centerLabel').attr({ fill: (0, _lib.toRaphaelColor)({ FCcolor: { color: labelConfig.color, alpha: labelConfig.alpha } }) }); } }; return CenterLabel; }(_componentInterface.ComponentInterface); exports['default'] = CenterLabel; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { 'initial.centerLabel.centerLabel.text.appearing': function initialCenterLabelCenterLabelTextAppearing(json) { if (json.attr) { return [{ initialAttr: { x: json.attr.x, y: json.attr.y } }]; } } }; /***/ }), /* 267 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _crossline = __webpack_require__(268); var _crossline2 = _interopRequireDefault(_crossline); var _crosslineManagerBandCategoryAxis = __webpack_require__(270); var _crosslineManagerBandCategoryAxis2 = _interopRequireDefault(_crosslineManagerBandCategoryAxis); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var CANVAS = 'canvas', CHARTAPI = 'chartAPI', CROSSLINEMANAGER = 'crossline-manager', chartExclusionList = { 'dragnode': true, 'hlineargauge': true, 'column3d': true, 'mscolumn3d': true, 'bar3d': true, 'pareto3d': true, 'msbar3d': true, 'stackedcolumn3d': true, 'stackedbar3d': true, 'mscombi3d': true, 'mscolumnline3d': true, 'stackedcolumn3dline': true, 'mscolumn3dlinedy': true, 'stackedcolumn3dlinedy': true, 'realtimearea': true, 'realtimecolumn': true, 'realtimeline': true, 'realtimestackedarea': true, 'realtimestackedcolumn': true, 'angulargauge': true, 'realtimelinedy': true, 'kagi': true, 'scrollcolumn2d': true, 'scrollline2d': true, 'scrollarea2d': true, 'scrollstackedcolumn2d': true, 'scrollcombi2d': true, 'scrollcombidy2d': true, 'scrollcombi2dspline': true, 'treemap': true, 'heatmap': true, 'boxandwhisker2d': true, 'scatter': true, 'timeseries': true, 'bubble': true, 'errorscatter': true, 'sparkwinloss': true, 'zoomscatter': true, 'zoomline': true, 'zoomlinedy': true }; /* eslint require-jsdoc: 'error', valid-jsdoc: 'error' */ exports['default'] = { extension: function extension(Fusioncharts) { Fusioncharts.addEventListener('preconfigure', function (event) { if (event.sender.getType() === CHARTAPI) { var chart = event.sender, chartObj = chart.getFromEnv('chartInstance'); chartObj.drawCrossline = function (value) { chartObj.drawConsolidatedToolTip(value); chart.iterateComponents(function (component) { if (component.getType() === CROSSLINEMANAGER) { if (value !== undefined) { component.show({ value: value }); } else { component.hide(); } } }); }; } }); Fusioncharts.addEventListener('instantiated', function (event) { if (event.sender.getName() === CANVAS) { var canvas = event.sender, crosslineManagerBand = void 0, handlerAPI = void 0; canvas.registerFactory('crossLineManager', function () { var chart = event.sender.getFromEnv('chart'), chartName = chart && chart.getName(); if (chartName && !chartExclusionList[chartName.toLowerCase()]) { (0, _lib.componentFactory)(canvas, _crosslineManagerBandCategoryAxis2['default'], 'crosslineManagerBand'); crosslineManagerBand = canvas.getChildren('crosslineManagerBand')[0]; handlerAPI = crosslineManagerBand._handlerAPI; crosslineManagerBand.configure(); (0, _lib.componentFactory)(crosslineManagerBand, _crossline2['default'], 'crossline'); // attach mouse event handlers crosslineManagerBand.addExtEventListener('fc-mouseover', handlerAPI.onhover, canvas); crosslineManagerBand.addExtEventListener('fc-mousemove', handlerAPI.onhover, canvas); crosslineManagerBand.addExtEventListener('fc-mouseout', handlerAPI.onhoverout, canvas); } }); } }); }, name: 'crossline-manager', type: 'extension', requiresFusionCharts: true }; /***/ }), /* 268 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _crossline = __webpack_require__(269); var _crossline2 = _interopRequireDefault(_crossline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var M = 'M', L = 'L', DEFAULTCOLOR = '#EEEEEE', DEFAULTALPHA = 50, BAND = 'band'; /** * class definition of crossline. * Its a basic draw padding it can draw crossline based on the data it is fed. * It can be scalable depending on the requirement */ var CrossLine = function (_ComponentInterface) { _inherits(CrossLine, _ComponentInterface); /** * This is the constructor of CrossLine */ function CrossLine() { _classCallCheck(this, CrossLine); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); (0, _dependencyManager.addDep)({ name: 'crosslineAnimation', type: 'animationRule', extension: _crossline2['default'] }); return _this; } /** * This method returns the name of the component * @return {string} name of the component */ CrossLine.prototype.getName = function getName() { return 'crossline'; }; /** * This method returns the type of the component * @return {string} type of the component */ CrossLine.prototype.getType = function getType() { return 'crossline'; }; /** * This will be invoked when crossline needs to be shown * @param {Object} config configuration of the crossline */ CrossLine.prototype.show = function show() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var crossline = this, onTop = !!config.onTop, type = config.type, prevRenderedOnTop = crossline.config.prevRenderedOnTop; !(onTop === prevRenderedOnTop) && crossline.hide(); !crossline[type] && (type = BAND); crossline[type](config); crossline.config.prevRenderedOnTop = onTop; }; /** * it can draw a simple band with some given thickness and color and position * @param {Object} config contains config for rendering band */ CrossLine.prototype.band = function band() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var crossline = this, managerId = config.managerId, x1 = config.x1, y1 = config.y1, x2 = config.x2, y2 = config.y2, thickness = config.thickness, onTop = !!config.onTop, fillcolor = (0, _lib.pluck)(config.fillcolor, DEFAULTCOLOR), alpha = (0, _lib.pluckNumber)(config.alpha, DEFAULTALPHA), fcColor = (0, _lib.toRaphaelColor)({ color: fillcolor, alpha: alpha }), crosslineElem = void 0, containerBellow = crossline.getLinkedParent().getChildContainer('crosslineBottom'), containerTop = crossline.getLinkedParent().getChildContainer('crosslineTop'), container = void 0; // choose the container as per the configuration // if crossline is going to render on top of the dataset then crosslineTop group will be chosen // otherwise crosslineBottom group will be chosen container = onTop ? containerTop : containerBellow; crosslineElem = crossline.getGraphicalElement('crosslineBand' + managerId); if (!crosslineElem) { // @TODO right now our animation manager does not support independent overlap animation // - for elements. So this fallback solution is applied. crossline.addGraphicalElement('crosslineBand' + managerId, crossline.getFromEnv('paper').path({ path: [M, x1, y1, L, x2, y2], stroke: fcColor, fill: fcColor, 'stroke-width': thickness, 'stroke-linecap': 'butt' }, container)); } else { // @TODO right now our animation manager does not support independent overlap animation // - for elements. So this fallback solution is applied. config.animDuration ? crosslineElem.animate({ path: [M, x1, y1, L, x2, y2] }, config.animDuration, 'ease-in') : crosslineElem.attr({ path: [M, x1, y1, L, x2, y2] }); } }; /** * removes all the graphic elems */ CrossLine.prototype.hide = function hide() { var graphicElems = this.getGraphicalElement(), keys = Object.keys(graphicElems); for (var i = keys.length - 1; i > -1; i--) { graphicElems[keys[i]].stop(undefined, true, true); graphicElems[keys[i]].remove(); delete graphicElems[keys[i]]; } }; return CrossLine; }(_componentInterface.ComponentInterface); exports['default'] = CrossLine; /***/ }), /* 269 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { crossline: { crossline: { path: { updating: function updating(input) { var path = input.attr.path; return [{ initialAttr: { path: input.el.attr('path') }, finalAttr: { path: path } }]; } } } } }; /***/ }), /* 270 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var DEFAULTCOLOR = '#EEEEEE', DEFAULTALPHA = 50, UNDEF = void 0, crispFixer = _lib.hasSVG ? 0 : 0.5, /** * get crisped edges * @param {number} x - edge value * @param {number} s - stroke width * @return {number} - crisped edge */ crisping = function crisping(x, s) { return Math.round(x + (s % 2 / 2 + crispFixer)) - (s % 2 / 2 + crispFixer); }, handlers = function handlers(crossLineManagerBand) { return { 'onhover': function onhover(event, o) { crossLineManagerBand.show(o.axes ? { 'axesInfo': o.axes } : { event: event }); }, 'onhoverout': function onhoverout(event) { crossLineManagerBand.hide({ event: event }); } }; }, /** * Helper function to create a RedRaphael group. * @param {string} groupName Name of the group to be created. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} manager The crossline manager * @return {Element} The group that was created. */ createRaphaelGroup = function createRaphaelGroup(groupName, parentContainer, manager) { var animationManager = manager.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: { name: groupName }, container: parentContainer, state: 'appearing', component: manager, label: 'group' }); }; /** * class definition of band crossline manager * it draws crossline for a category axis */ var CrossLineManagerBand = function (_ComponentInterface) { _inherits(CrossLineManagerBand, _ComponentInterface); /** * constructor fn */ function CrossLineManagerBand() { _classCallCheck(this, CrossLineManagerBand); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this._handlerAPI = handlers(_this); return _this; } /** * function to return required informations of attached X-axis and value for a mouse event * @param {Object} event event ref * @return {Object} attached axis info */ CrossLineManagerBand.prototype.getAttachedAxisInfo = function getAttachedAxisInfo() { var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manager = this, canvas = manager.getLinkedParent(), listOfAxes = canvas.getAxes(), i = void 0, axis = void 0, isY = void 0, isVertical = void 0, coordinate = event.originalEvent && (0, _lib.getMouseCoordinate)(manager.getFromEnv('chart-container'), event.originalEvent, manager.getFromEnv('chart')), chartX = coordinate && coordinate.chartX || 0, chartY = coordinate && coordinate.chartY || 0; for (i = listOfAxes.length - 1; i >= 0; i--) { axis = listOfAxes[i].axis; isY = listOfAxes[i].isY; if (!isY) { isVertical = !!axis.config.isVertical; return { 'value': isVertical ? axis.getValue(chartY) : axis.getValue(chartX), 'axis': axis, 'isVertical': isVertical, 'isY': false }; } } }; /** * function to configure this component based on the compoenent requirement and chart configurations */ CrossLineManagerBand.prototype.configure = function configure() { var manager = this, conf = manager.config, chartConfig = manager.getFromEnv('chartConfig'), chartAttr = manager.getFromEnv('chart-attrib'), fillcolor = (0, _lib.pluck)(chartAttr.crosslinecolor, chartConfig.crosslinecolor, DEFAULTCOLOR), thickness = (0, _lib.pluckNumber)(chartConfig.defaultcrosslinethickness), crosslineanimation = (0, _lib.pluckNumber)(chartAttr.crosslineanimation, 0), // @TODO this crosslineanimationduration attribute will be deprecated from next version animduration = crosslineanimation && (0, _lib.pluckNumber)(chartAttr.crosslineanimationduration, 0.09) * 1000, onTop = (0, _lib.pluckNumber)(chartAttr.drawcrosslineontop, chartConfig.drawcrosslineontop, 0), alpha = (0, _lib.pluckNumber)(chartAttr.crosslinealpha, chartConfig.crosslinealpha, DEFAULTALPHA); conf.drawCrossLine = (0, _lib.pluckNumber)(chartAttr.drawcrossline, chartConfig.drawcrossline, 0); conf.bandStyle = { 'fillcolor': fillcolor, 'alpha': alpha, 'thickness': thickness, 'managerId': manager.getId(), 'onTop': onTop, 'cursor': 'pointer', 'animDuration': animduration }; }; /** * function to create child group */ CrossLineManagerBand.prototype.createGroup = function createGroup() { var manager = this, crosslineBottom = manager.getLinkedParent().getChildContainer('crosslineBottom'), crosslineTop = manager.getLinkedParent().getChildContainer('crosslineTop'); !manager.getChildContainer('crosslineTop') && manager.addChildContainer('crosslineTop', createRaphaelGroup('crosslineTop', crosslineTop, manager)); !manager.getChildContainer('crosslineBottom') && manager.addChildContainer('crosslineBottom', createRaphaelGroup('crosslineBottom', crosslineBottom, manager)); }; /** * This function both the cases * 1. in a case of interaction on canvas with which it is attached to * 2. in a case of when multi-canvas crossline manager invoked this API * with informations of attached axes with some other crossline manager * that means in a case of multi-canvas chart when interaction happened * on a some other canvas then the crossline manager informs multi-canvas * crossline manager will be informed then manager invoked this API and * pass informations * It is capable to inform multi-canvas crossline manager so that * multi-canvas crossline manager could inform other crossline managers can * be able draw crosslines on canvas with which they are elated to. * @param {Object} info depending on the invocation of this method info * contain information. In a case of the interaction * on canvas that attached to it then info contains * event. when it invoked from manageMultiCanvasCrossline * [basically, multi-canvas crossline manager] then * it contains information of axes. */ CrossLineManagerBand.prototype.show = function show() { var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manager = this, event = info.event, conf = manager.config; conf.attachedCanvasAxisInfo = manager.getAttachedAxisInfo(event); manager._setAptAxesInfo(info.axesInfo, info.value); manager._show(event); }; /** * this function decides which axes are applicable for this manager if axesInfo is provided * in a case, if value is provided then the attached axis value will replaced by the provided value * from axes information of other crossline managers * @param {Array} extAttachedAxesInfo - attached axes info of other canvas available passed from * multi-canvas crossline manager in a case there is multiple * canvas * @param {number} value - axis value (basically category index in this case) */ CrossLineManagerBand.prototype._setAptAxesInfo = function _setAptAxesInfo() { var extAttachedAxesInfo = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var value = arguments[1]; var manager = this, infoLength = extAttachedAxesInfo.length, extAttachedAxis = void 0, attachedCanvasAxisInfo = manager.config.attachedCanvasAxisInfo, i = void 0; if (extAttachedAxesInfo.length) { for (i = 0; i < infoLength; i++) { extAttachedAxis = extAttachedAxesInfo[i]; if (extAttachedAxis.axis === attachedCanvasAxisInfo.axis) { attachedCanvasAxisInfo.value = extAttachedAxis.value; break; } } } if (value !== UNDEF) { attachedCanvasAxisInfo.value = value; } }; /** * function to inform crossline component to show crossline with calculated attributes * @param {Event} event - event mouse interaction */ CrossLineManagerBand.prototype._show = function _show(event) { var manager = this, conf = manager.config, chartConfig = manager.getFromEnv('chartConfig'), crossline = manager.getChildren('crossline')[0], attachedCanvasAxisInfo = conf.attachedCanvasAxisInfo, axisValue = attachedCanvasAxisInfo.value, activeAxis = attachedCanvasAxisInfo.axis, isVertical = attachedCanvasAxisInfo.isVertical, endPad = activeAxis.config.endPad, limit = activeAxis.getVisibleConfig().maxValue - endPad, xAxisIndex = Math.round(axisValue), xAxisPos = attachedCanvasAxisInfo.axis.getPixel(xAxisIndex), xAxisZeroPos = void 0, xAxisOnePos = void 0, thickness = void 0, bandAttrs = Object.assign({}, conf.bandStyle), crispedValue = void 0, canvasConfig = manager.getFromEnv('canvasConfig'), canvasTop = canvasConfig.canvasTop, canvasLeft = canvasConfig.canvasLeft, canvasWidth = canvasConfig.canvasWidth, canvasHeight = canvasConfig.canvasHeight, canvasBottom = canvasTop + canvasHeight, drawCrossLine = conf.drawCrossLine; if (xAxisIndex < 0 || xAxisIndex > limit) { return; } if (manager.config.lastIndex !== xAxisIndex && drawCrossLine) { if ((thickness = bandAttrs.thickness) === UNDEF) { // for mscombi charts, thickess of the crossline depends on presence of column dataset. if (chartConfig._hascolumn === false) { thickness = 1; } else { xAxisZeroPos = activeAxis.getPixel(0); xAxisOnePos = activeAxis.getPixel(1); thickness = Math.abs(xAxisOnePos - xAxisZeroPos); } } crispedValue = crisping(xAxisPos, thickness); manager.createGroup(); bandAttrs.thickness = thickness; if (isVertical) { bandAttrs = Object.assign(bandAttrs, { 'x1': canvasLeft, 'y1': crispedValue, 'x2': canvasLeft + canvasWidth, 'y2': crispedValue }); } else { bandAttrs = Object.assign(bandAttrs, { 'x1': crispedValue, 'y1': canvasTop, 'x2': crispedValue, 'y2': canvasBottom }); } crossline.show(bandAttrs); manager.getFromEnv('chart').fireChartInstanceEvent('onChangeCrossLine', { currentIndex: xAxisIndex, lastIndex: manager.config.lastIndex, source: event ? 'mouse interaction' : 'public API' }); manager.config.lastIndex = xAxisIndex; } }; /** * it informs crossline to hide * @param {Object} info contains event info, in a case of the interaction * on canvas that attached to it then info contains * event. */ CrossLineManagerBand.prototype.hide = function hide() { var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manager = this, canvas = manager.getLinkedParent(), event = info.event, coordinate = event && event.originalEvent && (0, _lib.getMouseCoordinate)(canvas.getFromEnv('chart-container'), event && event.originalEvent, canvas.getFromEnv('chart')), chartX = coordinate && coordinate.chartX || 0, chartY = coordinate && coordinate.chartY || 0; if (!canvas.isWithinCanvas(chartX, chartY)) { manager.getFromEnv('chart').fireChartInstanceEvent('onChangeCrossLine', { lastIndex: manager.config.lastIndex, source: event ? 'mouse interaction' : 'public API' }); delete this.config.lastIndex; this.getChildren('crossline')[0].hide(); } }; /** * returns component type * @return {string} component type */ CrossLineManagerBand.prototype.getType = function getType() { return 'crossline-manager'; }; /** * return component name * @return {string} component name */ CrossLineManagerBand.prototype.getName = function getName() { return 'crossline-manager-band-category-axis'; }; return CrossLineManagerBand; }(_componentInterface.ComponentInterface); exports['default'] = CrossLineManagerBand; /***/ }), /* 271 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var inclusionList = { 'candlestick': true }; /** * class definition * this class communicates between multiple crossline manager across the different canavss */ var manageMultiCanvasCrossline = function (_ComponentInterface) { _inherits(manageMultiCanvasCrossline, _ComponentInterface); /** * constructor fn */ function manageMultiCanvasCrossline() { _classCallCheck(this, manageMultiCanvasCrossline); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this._handlers = function (manager) { return { 'onhover': function onhover(event) { event.originalEvent && manager.show(event); }, 'onhoverout': function onhoverout(event) { event.originalEvent && manager.hide(event); } }; }(_this); return _this; } /** * function to return required informations of attached X-axis and value for a mouse event * @param {Object} event event ref * @param {Component} targetCanvas target canvas on which interaction occured * @return {Object} attached axes info of the target canvas */ manageMultiCanvasCrossline.prototype.getAxesInfo = function getAxesInfo() { var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var targetCanvas = arguments[1]; var manager = this, listOfAxes = targetCanvas.getAxes(), i = void 0, info = [], axis = void 0, isY = void 0, isVertical = void 0, coordinate = (0, _lib.getMouseCoordinate)(manager.getFromEnv('chart-container'), event.originalEvent, manager.getFromEnv('chart')), chartX = coordinate.chartX || 0, chartY = coordinate.chartY || 0; for (i = listOfAxes.length - 1; i >= 0; i--) { axis = listOfAxes[i].axis; isY = listOfAxes[i].isY; isVertical = !!axis.config.isVertical; info.push({ 'value': isVertical ? axis.getValue(chartY) : axis.getValue(chartX), 'axis': axis, 'isVertical': isVertical, 'isY': isY }); } return info; }; /** * return component name * @return {string} component name */ manageMultiCanvasCrossline.prototype.getName = function getName() { return 'multiCanvasCrosslineManager'; }; /** * returns component type * @return {string} component type */ manageMultiCanvasCrossline.prototype.getType = function getType() { return 'multiCanvasCrosslineManager'; }; /** * fire an event with attached axes info of the interacted canvas to other canvases to show crossline * mousemove is fired for other non-interacted canvas * @param {Object} event event obj reference */ manageMultiCanvasCrossline.prototype.show = function show(event) { var targetCanvas = event.sender, attachedAxesInfo = void 0, chart = this.getFromEnv('chart'); attachedAxesInfo = this.getAxesInfo(event, targetCanvas); chart.iterateComponents(function (component) { if (component.getName() === 'canvas' && component !== targetCanvas) { component.fireEvent('fc-mousemove', { 'axes': attachedAxesInfo }); } }); }; /** * fire an event to hide crossline for non-interacted canvases * mouseout is fired for other non-interacted canvas * @param {Object} event event obj reference */ manageMultiCanvasCrossline.prototype.hide = function hide(event) { var targetCanvas = event.sender, coordinate = (0, _lib.getMouseCoordinate)(targetCanvas.getFromEnv('chart-container'), event && event.originalEvent, targetCanvas.getFromEnv('chart')), chartX = coordinate.chartX, chartY = coordinate.chartY; if (!targetCanvas.isWithinCanvas(chartX, chartY)) { this.getFromEnv('chart').iterateComponents(function (component) { if (component.getName() === 'canvas' && component !== targetCanvas) { component.fireEvent('fc-mouseout'); } }); } }; return manageMultiCanvasCrossline; }(_componentInterface.ComponentInterface); exports['default'] = { extension: function extension(Fusioncharts) { Fusioncharts.addEventListener('instantiated', function (event) { if (event.sender.getType && event.sender.getType() === 'chartAPI' && inclusionList[event.sender.getName && event.sender.getName()]) { var chart = event.sender, manager = void 0, handlersAPI = void 0; chart.registerFactory('multiCanvasCrossline', function () { (0, _lib.componentFactory)(chart, manageMultiCanvasCrossline, 'multiCanvasCrosslineManager'); manager = chart.getChildren('multiCanvasCrosslineManager')[0]; handlersAPI = manager._handlers; chart.iterateComponents(function (child) { if (child.getName() === 'canvas') { // attach mouse event handlers child.addEventListener('fc-mouseover', handlersAPI.onhover); child.addEventListener('fc-mousemove', handlersAPI.onhover); child.addEventListener('fc-mouseout', handlersAPI.onhoverout); } }); }, ['canvas']); } }); }, name: 'multi-canvas-crossline-manager', type: 'extension', requiresFusionCharts: true }; /***/ }), /* 272 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.setConfig = exports.getConfig = undefined; var _index = __webpack_require__(273); var _index2 = _interopRequireDefault(_index); var _globalConfig = __webpack_require__(280); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _index2['default']; exports.getConfig = _globalConfig.getConfig; exports.setConfig = _globalConfig.setConfig; /***/ }), /* 273 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _datastore = __webpack_require__(274); var _datastore2 = _interopRequireDefault(_datastore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _datastore2['default']; /***/ }), /* 274 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _datatable = __webpack_require__(275); var _datatable2 = _interopRequireDefault(_datatable); var _eventHandler = __webpack_require__(319); var _datatableUtils = __webpack_require__(276); 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 DataStore = function () { /** * Create the DataStore * @constructor */ function DataStore(data, schema, config) { _classCallCheck(this, DataStore); // a key value pair of datatable id and datatable object this.dataTables = {}; // this basically points to the first data table that's created in the data store // this is needed for backward compatibility for existing samples // should be removed once the sample codes are changed this._defaultDataTable = null; // This is done for backward compatibility for samples if (data && schema && data.constructor === Array && schema.constructor === Array) { this.createDataTable(data, schema, config); } } /** * Create a data table from data, schema and configuration * @param {array} data - 2D array or array of JSON objects containing the data * @param {array} schema - array of JSON objects defining the schema * @param {object} config - object with additional configuration * @param {string} id - id of the table * @returns {DataTable} created DataTable */ DataStore.prototype.createDataTable = function createDataTable(data, schema, config, id) { if (!data || !schema) { throw new Error('Both data and schema must be provided to build DataTable'); } if (data.constructor !== Array) { throw new Error('Data must be provided in 2D array format or array of json objects'); } if (schema.constructor !== Array || schema.length === 0) { throw new Error('Input schema is not in a correct format - schema must be an array of column configurations'); } var configObj = {}, parsedRows = void 0, dataTable = void 0, tableIdArr = void 0; tableIdArr = Object.keys(this.dataTables); if (id) { if (tableIdArr.includes(id)) { throw new Error('A table with the id ' + id + ' already exists in the DataStore. Please use a different id.'); } } else { id = (0, _datatableUtils.createTableID)(tableIdArr); } Object.assign(configObj, { enableIndex: true, enableUTC: false }, config); parsedRows = (0, _datatableUtils.parseAndIndexData)(data, schema, configObj); dataTable = new _datatable2['default'](this, parsedRows, schema, configObj); if (tableIdArr.length === 0) { this._defaultDataTable = dataTable; } this.dataTables[id] = dataTable; return dataTable; }; /** * Append rows to a DataTable inside DataStore. All tables derived from the DataTable will be updated. * @param {array} rows - 2D array or array of JSON object containing the data * @param {string} id - id of the table where rows will be inserted */ DataStore.prototype.appendRows = function appendRows(rows, id) { var _dataTable$_data; // get the data table var dataTable = this.getDataTable(id), parsedRows = void 0, schema = void 0, dateColumnsAndFormatter = void 0; // get the schema schema = dataTable.getSchema(); // build date columns and formatter mapping dateColumnsAndFormatter = (0, _datatableUtils.buildDateColumnsFormatter)(schema); // parse the data parsedRows = (0, _datatableUtils.parseData)(rows, schema, dateColumnsAndFormatter); // insert the parsed rows in data table data (_dataTable$_data = dataTable._data).push.apply(_dataTable$_data, parsedRows); // perform indexing (0, _datatableUtils.indexData)(dataTable._data, schema, dataTable._config, dateColumnsAndFormatter); // propagate the event to all child data tables dataTable._appendRows(parsedRows); // fire tha itemAdded event this.trigger('itemsAdded', { rows: rows, tableID: id }); }; /** * Get instance of a DataTable object from it's id * @param {string} id - id of the table to fetch * @returns {DataTable} */ DataStore.prototype.getDataTable = function getDataTable(id) { if (id) { if (!this.dataTables[id]) { throw new Error('DataTable with id ' + id + ' is not found in the DataStore.'); } return this.dataTables[id]; } else { return this._defaultDataTable; } }; /** * Attach a handler function to an event * @param {string} eventName - name of the event to attach * @param {function} handlers - handler function to attach to the event */ DataStore.prototype.on = function on(eventName, handlers) { (0, _eventHandler.addHandler)(eventName, handlers, this); }; /** * Detach a handler function from an event * @param {string} eventName - name of the event to attach * @param {function} handlers - handler function to detach */ DataStore.prototype.off = function off(eventName, handlers) { (0, _eventHandler.removeHandler)(eventName, handlers, this); }; /** * Triggers an event, optionally with some data * @param {string} eventName - name of the event to trigger * @param {*} data - optional data to send with the event */ DataStore.prototype.trigger = function trigger(eventName, data) { (0, _eventHandler.triggerEvent)(eventName, this, data); }; /** * Disposes the DataStore and all DataTable contained in the DataStore or derived from any of the tables in DataStore */ DataStore.prototype.dispose = function dispose() { var instance = this; // call child datatable's dispose method for (var tableId in instance.dataTables) { instance.dataTables[tableId].dispose(); // remove the variable delete instance.dataTables[tableId]; } // remove the object containing data tables delete instance.dataTables; delete instance._defaultDataTable; // fire the disposed event this.trigger('disposed'); instance = null; }; DataStore.prototype._propagate = function _propagate(payload) { var instance = this; // trigger event payload received this.trigger('payloadReceived', payload); // call child datatables' _payloadReceiver method for (var tableId in instance.dataTables) { instance.dataTables[tableId]._payloadReceiver(payload); } }; return DataStore; }(); exports['default'] = DataStore; /***/ }), /* 275 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _datatableUtils = __webpack_require__(276); var _eventHandler = __webpack_require__(319); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DataTable = function () { function DataTable(dataStore, data, schema, config, parentTable, opsFunnel) { _classCallCheck(this, DataTable); /// Property declaration // the data table object from where the DataTable is generated this._dataStore = dataStore; // the parent table from which this data table is generated this._parentTable = parentTable; // the children tables generated from this table this._children = []; // set of operations which applied on the parent data table to create this data table this._opsFunnel = opsFunnel; // data for this data table, data will refer to the parent table's data if the funnel which generates this data table does not contain any schema changing operation and only updates the set of rows this._data = data || []; // schema of the data table this._schema = schema; // store the config object of the data table this._config = config; // the result set after executing the funnel/generatorFn this._result = null; } DataTable.prototype._appendRows = function _appendRows(rows) { var childrenLength = this._children && this._children.length || 0, schemaLength = this._result && this._result.schema.length || 0; // move calulated columns to _calcColumns if (schemaLength) this._calcColumns = []; for (var i = 0; i < schemaLength; i++) { if (this._result.schema[i].calcFn) { this._calcColumns.push(this._result.schema[i]); } } // if _result exists, clear it if (this._result) { delete this._result; } // call all children datatables' _appendRows for (var _i = 0; _i < childrenLength; _i++) { this._children[_i]._appendRows(rows); } }; /** * Number of rows in the data table * @returns {number} total number of rows in the data table */ DataTable.prototype.count = function count() { var result = this._executeFunnel(); return result.data.length; }; /** * Return the schema of the data table * @returns {array} array of column objects */ DataTable.prototype.getSchema = function getSchema() { var result = this._executeFunnel(); return result.schema; }; /** * Return the original data table object from which the data table is generated * @returns {object} */ DataTable.prototype.getDataStore = function getDataStore() { return this._dataStore; }; /** * Get data starting from offset index, and number of items returned is denoted by numberOfItems * * @param {number} offset - starting index of data to fetch, default is zero * @param {number} numberOfItems - number of items to fetch, default is all items * @returns {object} - an object containing both data and schema */ DataTable.prototype.getData = function getData(offset, numberOfItems) { // if no value is provided then offset is zero offset = offset || 0; // This check is only for numberOfItems is string, otherwise an undefined numberOfItems is a valid second argument in array slice method // Also null as second parameter is invalid for array slice, hence if null is passed it's converted to undefined numberOfItems = numberOfItems && (typeof numberOfItems === 'string' || numberOfItems instanceof String) || numberOfItems === null ? undefined : numberOfItems; // return value var result = this._executeFunnel(); return { data: result.data && result.data.slice(offset, numberOfItems && numberOfItems > 0 ? offset + numberOfItems : numberOfItems), schema: result.schema }; }; /** * Dispose the current data table and all tables derived from this data table */ DataTable.prototype.dispose = function dispose() { var instance = this, childrenLength = instance._children && instance._children.length || 0; delete instance._dataStore; delete instance._parentTable; delete instance._opsFunnel; delete instance._data; delete instance._schema; delete instance._config; delete instance._result; // call all children datatables' dispose for (var i = 0; i < childrenLength; i++) { instance._children[i].dispose(); } // and remove it delete instance._children; // fire the disposed event instance._trigger('disposed'); instance = null; }; /** * Get the min value of a column * @param {string} columnName - name of the column * @returns {number|object} returns the minimum number of the column. In case of interval columns - interval with earliest start timestamp */ DataTable.prototype.min = function min(columnName) { // retrieve the data // this step is necessary as this.data may contain the root data and only way to get valid data for the datatable is to call the getData method var dtData = this.getData(); return (0, _datatableUtils.columnMinValue)(columnName, dtData.data, dtData.schema); }; /** * Get the max value of a column * @param {string} columnName - name of the column * @returns {number|object} returns the maximum number of the column. In case of interval columns - interval with latest end timestamp */ DataTable.prototype.max = function max(columnName) { // retrieve the data // this step is necessary as this.data may contain the root data and only way to get valid data for the datatable is to call the getData method var dtData = this.getData(); return (0, _datatableUtils.columnMaxValue)(columnName, dtData.data, dtData.schema); }; /** * Get unique values from a column * @param {string} columnName - name of the column * @returns {any} returns the unique elements of the column */ DataTable.prototype.unique = function unique(columnName) { // retrieve the data // this step is necessary as this.data may contain the root data and only way to get valid data for the datatable is to call the getData method var dtData = this.getData(); return (0, _datatableUtils.columnUnique)(columnName, dtData.data, dtData.schema); }; /** * Get peak values - max & min from a column * @param {string} columnName - name of the column * @returns {object} - an object containing both min and max value of the column. In case of interval column min is the earliest start timestamp and max is the latest end time stamp */ DataTable.prototype.extents = function extents(columnName) { // retrieve the data // this step is necessary as this.data may contain the root data and only way to get valid data for the datatable is to call the getData method var dtData = this.getData(); return (0, _datatableUtils.columnExtents)(columnName, dtData.data, dtData.schema); }; /** * Adds one or more columns to data table * @param {...any} columnConfigs - array of columns to add */ DataTable.prototype.addColumns = function addColumns() { for (var _len = arguments.length, columnConfigs = Array(_len), _key = 0; _key < _len; _key++) { columnConfigs[_key] = arguments[_key]; } var columnConfigsLen = columnConfigs.length; if (columnConfigsLen > 0) { this._calcColumns = this._calcColumns || []; for (var i = 0; i < columnConfigsLen; i++) { if (!columnConfigs[i].name) throw new Error('name is required in column ' + (i + 1)); if (columnConfigs[i].calcFn && !(columnConfigs[i].calcFn instanceof Function)) throw new Error('calcFn must be a function in column ' + (i + 1)); if (!columnConfigs[i].calcFn) { columnConfigs[i].calcFn = function () { return undefined; }; } // to ensure deep clone this._calcColumns.push(Object.assign({}, columnConfigs[i])); } } // trigger updated event this._trigger('updated', columnConfigs); }; /** * Runs a single operation or a set of operations on the data table and creates a new data table * @param {any} operations - an operation or array of operations * @returns {DataTable} the derived DataTable created from the current DataTable */ DataTable.prototype.query = function query(operations) { if (operations && operations.constructor !== Array) { operations = [operations]; } // for the new derived data table, data, schema, config reference is same // we are not concatenating the parent's funnel here as in executeFunnel method we are always executing parent's funnel before executing it's own var dataTable = new DataTable(this._dataStore, this._data, this._schema, this._config, this, operations); // add the new child data table to the children list of current datatable this._children.push(dataTable); return dataTable; }; /** * Returns the 0 based index of the columnName in schema, if not found then -1 is returned * @param {*} columnName - name of the column * @returns {number} */ DataTable.prototype.indexOf = function indexOf(columnName) { var result = this._executeFunnel(); return (0, _datatableUtils.columnIndexOf)(columnName, result.schema); }; /** * Attach a handler function to an event * @param {string} eventName - name of the event to attach * @param {function} handlers - handler function to attach */ DataTable.prototype.on = function on(eventName, handlers) { (0, _eventHandler.addHandler)(eventName, handlers, this); }; /** * Detach a handler from an event * @param {string} eventName - name of the event * @param {function} handlers - handler function to attach */ DataTable.prototype.off = function off(eventName, handlers) { (0, _eventHandler.removeHandler)(eventName, handlers, this); }; DataTable.prototype._trigger = function _trigger(eventName, data) { (0, _eventHandler.triggerEvent)(eventName, this, data); }; /** * execute the data table's funnel and _calcColumns, and return data, schema, config * the result is cached for future use * if some operation invalidates the result then it must manually make the result field null */ DataTable.prototype._executeFunnel = function _executeFunnel() { if (!this._result) { if (this._opsFunnel) { var parentResult = void 0, data = void 0, schema = void 0, config = void 0, funnelLen = void 0; // run the parent funnel and then use the result for subsequent operations parentResult = this._parentTable._executeFunnel(); data = parentResult.data.slice(0); schema = parentResult.schema.slice(0); config = Object.assign({}, parentResult.config); funnelLen = this._opsFunnel.length; // loop through the funnel and execute each funnel for (var i = 0; i < funnelLen; i++) { if (this._opsFunnel[i] && this._opsFunnel[i].fn) { var result = this._opsFunnel[i].fn(data, schema, config); data = result.generatorFn ? result.generatorFn() : result.data; schema = result.schema; config = result.config; } } this._result = { data: data, schema: schema, config: config }; } else { this._result = { data: this._data, schema: this._schema, config: this._config }; } } // check if _calcColumns exists and if it has been executed if (this._calcColumns && this._calcColumns.length > 0) { // update the schema and data var _columnConfigs = (0, _datatableUtils.addColumnsSchema)(this._result.schema, this._calcColumns); this._result.schema = _columnConfigs.schema; // update the data this._result.data = (0, _datatableUtils.addColumnsData)(this._result.data, this._result.schema, _columnConfigs.calcColumns); // after all processing, remove the property delete this._calcColumns; } return this._result; }; DataTable.prototype._flushResult = function _flushResult() { var schemaLength = this._result && this._result.schema.length || 0; // move calulated columns to _calcColumns if (schemaLength) this._calcColumns = []; for (var i = 0; i < schemaLength; i++) { if (this._result.schema[i].calcFn) { this._calcColumns.push(this._result.schema[i]); } } if (this._result) { this._result = null; } for (var _i2 = 0; _i2 < this._children.length; _i2++) { this._children[_i2]._flushResult(); } this._trigger('resultFlushed'); }; /** * Propagate a payload to all data store * @param {object} payload - payload object to propagate */ DataTable.prototype.propagate = function propagate(payload) { // send payload and trigger info to datastore this.getDataStore()._propagate({ trigger: this, payload: payload }); }; DataTable.prototype._payloadReceiver = function _payloadReceiver(payload) { var childrenLength = this._children && this._children.length || 0; // ignore when trigger is itself (?) if (payload && payload.trigger && payload.trigger !== this) { // trigger event payloadReceived this._trigger('payloadReceived', payload); } // call child datatables' payloadReceivers for (var i = 0; i < childrenLength; i++) { this._children[i]._payloadReceiver(payload); } }; DataTable.prototype.getMinDiff = function getMinDiff(columnName) { // retrieve the data // this step is necessary as this.data may contain the root data and only way to get valid data for the datatable is to call the getData method var dtData = this.getData(); return (0, _datatableUtils.columnMinDiff)(columnName, dtData.data, dtData.schema, this._config.indexBy); }; /** * Get the enableUTC flag of the column or global. * @param {string} columnName name of the column */ DataTable.prototype.isUTCEnabled = function isUTCEnabled(columnName) { return (0, _datatableUtils.isUTCEnabled)(columnName, this.getSchema()); }; return DataTable; }(); exports['default'] = DataTable; /***/ }), /* 276 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.isUTCEnabled = exports.indexData = exports.parseData = exports.buildDateColumnsFormatter = exports.createTableID = exports.parseAndIndexData = exports.addColumnsData = exports.addColumnsSchema = exports.columnUnique = exports.columnExtents = exports.columnMinDiff = exports.columnMaxValue = exports.columnMinValue = exports.columnIndexOf = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeUtils = __webpack_require__(277); var _comparators = __webpack_require__(278); var _sort = __webpack_require__(279); var _sort2 = _interopRequireDefault(_sort); var _globalConfig = __webpack_require__(280); var _timeConverter = __webpack_require__(281); var _timeConverter2 = _interopRequireDefault(_timeConverter); var _set = __webpack_require__(296); var _set2 = _interopRequireDefault(_set); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Get 0 based index of a column from the schema * @param {string} columnName The name of the column to find * @param {array} schema The schema array */ function columnIndexOf(columnName, schema) { if (!schema || !columnName) return null; for (var i = 0; i < schema.length; i++) { if (schema[i] && schema[i].hasOwnProperty('name') && schema[i].name === columnName) { return i; } } return -1; } /** * Get the minimum value from a column * @param {string} columnName The name of the column to find * @param {array} data The data array * @param {array} schema The schema array */ function columnMinValue(columnName, data, schema) { var columnIndex = void 0, minVal = void 0; // get the column index columnIndex = columnIndexOf(columnName, schema); // check if column is found if (columnIndex === null || columnIndex === -1) { return null; } // check if data is valid if (data && data.length > 0) { var valToCheck = void 0; minVal = Number.POSITIVE_INFINITY; for (var i = 0; i < data.length; i++) { valToCheck = schema[columnIndex].type === 'interval' ? data[i][columnIndex] ? data[i][columnIndex].start : null : data[i][columnIndex]; if ((0, _typeUtils.isNumber)(valToCheck) && valToCheck < minVal) { minVal = valToCheck; } } } return minVal; } /** * Get the maximum value from a column * @param {string} columnName The name of the column to find * @param {array} data The data array * @param {array} schema The schema array */ function columnMaxValue(columnName, data, schema) { var columnIndex = void 0, maxVal = void 0; // get the column index columnIndex = columnIndexOf(columnName, schema); // check if column is found if (columnIndex === null || columnIndex === -1) { return null; } // check if data is valid if (data && data.length > 0) { var valToCheck = void 0; maxVal = Number.NEGATIVE_INFINITY; for (var i = 0; i < data.length; i++) { valToCheck = schema[columnIndex].type === 'interval' ? data[i][columnIndex] ? data[i][columnIndex].end : null : data[i][columnIndex]; if ((0, _typeUtils.isNumber)(valToCheck) && valToCheck > maxVal) { maxVal = valToCheck; } } } return maxVal; } /** * Get the min difference between values in a column * @param {string} columnName The name of the column to find * @param {array} data The data array * @param {array} schema The schema array * @param {string} indexBy The column name on which the data is indexed/sorted */ function columnMinDiff(columnName, data, schema, indexBy) { // proceed only if date or number, else throw error var columnIndex = void 0, dataClone = data, dataLength = data.length, minDiff = void 0; // get the column index columnIndex = columnIndexOf(columnName, schema); // check if column is found if (columnIndex === null || columnIndex === -1) { return null; } if (schema[columnIndex] && ['date', 'number'].indexOf(schema[columnIndex].type) < 0) throw new Error('Operation valid only on date or number columns'); // if column is not indexBy then sort it if (!indexBy || columnName !== indexBy) { // clone before sorting so as not to disturb the original data dataClone = data.slice(0); dataClone.sort(function (a, b) { return (0, _comparators.numberComparator)(a[columnIndex], b[columnIndex]); }); } // loop through the data, // calculate the difference between current and next elements, // if new difference less than current difference, update it if (dataClone && dataLength > 0) { var valToCheck = void 0, a = void 0, b = void 0; minDiff = Number.POSITIVE_INFINITY; for (var i = 0; i < dataClone.length - 1; i++) { a = dataClone[i][columnIndex]; b = dataClone[i + 1][columnIndex]; if ((0, _typeUtils.isNumber)(b) && (0, _typeUtils.isNumber)(a)) { // both are 0, then 0 // either/both greater than 0 and not same then subtract valToCheck = b - a; minDiff = (0, _typeUtils.isNumber)(valToCheck) && valToCheck >= 0 && valToCheck < minDiff ? valToCheck : minDiff; // difference will always be positive and the smallest value can be 0 if (minDiff === 0) break; } else { break; } } } return minDiff === Number.POSITIVE_INFINITY ? null : minDiff; } /** * Get both minimum and maximum from a column * @param {string} columnName The name of the column to find * @param {array} data The data array * @param {array} schema The schema array */ function columnExtents(columnName, data, schema) { var min = Number.POSITIVE_INFINITY, max = Number.NEGATIVE_INFINITY, columnIndex = columnIndexOf(columnName, schema), valToCheck = void 0; // get the column index // check if column is found if (columnIndex === null || columnIndex === -1) { return null; } // check if data is valid if (data && data.length > 0) { for (var i = 0; i < data.length; i++) { valToCheck = schema[columnIndex].type === 'interval' ? data[i][columnIndex] ? data[i][columnIndex].start : null : data[i][columnIndex]; if ((0, _typeUtils.isNumber)(valToCheck) && valToCheck < min) { min = valToCheck; } valToCheck = schema[columnIndex].type === 'interval' ? data[i][columnIndex] ? data[i][columnIndex].end : null : data[i][columnIndex]; if ((0, _typeUtils.isNumber)(valToCheck) && valToCheck > max) { max = valToCheck; } } } return { min: min, max: max }; } /** * Get unique values from a column * @param {string} columnName The name of the column to find * @param {array} data The data array * @param {array} schema The schema array */ function columnUnique(columnName, data, schema) { // get the column index var columnIndex = columnIndexOf(columnName, schema), uniqueVals = [], uniqueList = void 0; // check if column is found if (columnIndex === null || columnIndex === -1) { return []; } for (var i = 0; i < data.length; i++) { uniqueVals.push(data[i][columnIndex]); } if (data && data.length > 0) { uniqueList = Array.from(new _set2['default'](uniqueVals)); return uniqueList.length === 1 && typeof uniqueList[0] === 'undefined' ? [] : uniqueList; } return []; } /** * Returns the schema updated with new columns * * @param {array} schema The schema to be updated * @param {array} columnConfigs The columns to be added */ function addColumnsSchema(schema, columnConfigs) { var columnConfigsLen = columnConfigs.length, schemaCopy = schema.slice(0); for (var i = 0; i < columnConfigsLen; i++) { var schemaLen = schemaCopy.length; columnConfigs[i].originalName = columnConfigs[i].name; for (var j = 0; j < schemaLen; j++) { // if name already exists append increasing integer if (columnConfigs[i].name === schemaCopy[j].name) { columnConfigs[i].i = columnConfigs[i].i && ++columnConfigs[i].i || 1; columnConfigs[i].name = columnConfigs[i].originalName + ' ' + columnConfigs[i].i; } // if type is missing or not one of string, number and date, then use string if (!columnConfigs[i].type || ['string', 'number', 'date'].indexOf(columnConfigs[i].type) === -1) { columnConfigs[i].type = 'string'; } } // clear up temporary value delete columnConfigs[i].originalName; delete columnConfigs[i].i; // update the schemaCopy schemaCopy.push({ name: columnConfigs[i].name, type: columnConfigs[i].type || 'string' }); // save the calcFn, format, enableUTC as well if (columnConfigs[i].calcFn) { schemaCopy[schemaCopy.length - 1].calcFn = columnConfigs[i].calcFn; } if (columnConfigs[i].format) { schemaCopy[schemaCopy.length - 1].format = columnConfigs[i].format; } if (columnConfigs[i].enableUTC) { schemaCopy[schemaCopy.length - 1].enableUTC = columnConfigs[i].enableUTC; } // set the columnindex of the new column in the schemaCopy columnConfigs[i].columnIndex = schemaCopy.length - 1; } return { schema: schemaCopy, calcColumns: columnConfigs }; } /** * Returns the data updated with new columns * * @param {array} data The data to be updated * @param {array} schema The schema to be updated * @param {array} columnConfigs The columns to be added */ function addColumnsData(data, schema, columnConfigs) { var dataLen = data.length, columnConfigsLen = columnConfigs.length, schemaLen = schema.length, columns = {}, cellData, dateColumnsAndFormatter = buildDateColumnsFormatter(columnConfigs); // create the columns object which is basically a mapping between column name and index // as user will provide the filter fn as = (row, columns) => row[columns.Name] === 'val' for (var i = 0; i < schemaLen; i++) { columns[schema[i].name] = i; } // loop through the data for (var _i = 0; _i < dataLen; _i++) { // loop through the columns for (var j = 0; j < columnConfigsLen; j++) { // if calcFn, process it if (columnConfigs[j].calcFn) { cellData = columnConfigs[j].calcFn(data[_i], columns, _i); cellData = _parseCell(columnConfigs[j], cellData, dateColumnsAndFormatter); data[_i][columnConfigs[j].columnIndex] = cellData; } } } return data; } function _parseCell(colConfig, val, dateColumnsAndFormatter) { // if the column is date type and also the value is not a number type then parse the data if (dateColumnsAndFormatter[colConfig.name] !== undefined && val && isNaN(+val)) { if (dateColumnsAndFormatter[colConfig.name]) { return +dateColumnsAndFormatter[colConfig.name].parse(val); } else { return +new Date(val); } } else if (colConfig.type === 'number') { if ((0, _typeUtils.isNumber)(val)) { return val; } else if (!val) { return null; } else { return parseFloat(val); } } else { return val; } } /** * Parse and perform indexing. Returns the parsed & indexed data * @param {array} data 2D array or array of JSON object * @param {array} schema array of JSON object * @param {object} config configuration object * @returns {array} parsed and indexed data */ function parseAndIndexData(data, schema, config) { // build date column and formatter map object var dateColumnsAndFormatter = buildDateColumnsFormatter(schema), // parse the data parsedData = parseData(data, schema, dateColumnsAndFormatter); // perform indexing indexData(parsedData, schema, config, dateColumnsAndFormatter); // return the parsed data return parsedData; } /** * Build date column and formatter mapping * @param {array} schema schema object array */ function buildDateColumnsFormatter(schema) { var dateColumnsAndFormatter = {}; // loop through the schema and check all date type and store the column name formatter object for (var i = 0; i < schema.length; i++) { // check if all elements of input schema has name attribute // for now we are allowing blank values if (!schema[i].name) { throw new Error('Input schema is not in a correct format - each column must have a name'); } if (schema[i].type && schema[i].type === 'date') { // key will be the column name dateColumnsAndFormatter[schema[i].name] = schema[i].format ? // if format is not provided in schema just insert null, so that the value is parsed according to JS date object parsing rule (schema[i].enableUTC !== undefined ? schema[i].enableUTC : (0, _globalConfig.getConfig)('enableUTC')) ? _timeConverter2['default'].utcParser(schema[i].format) : _timeConverter2['default'].parser(schema[i].format) : null; } } return dateColumnsAndFormatter; } /** * Parse the data * @param {array} data 2D array or array of JSON * @param {array} schema array of schema objects * @param {object} dateColFormatter a key value pair containing date columns and formatter */ function parseData(data, schema, dateColFormatter) { var parsedData = []; // if any data is present only then perform parsing and indexing if (data.length > 0) { // store all date column and corresponding formatter object in a key value pair // we do not wish to create a formatter object every time we want to parse a date var dateColumnsAndFormatter = dateColFormatter, i = void 0; if (!dateColumnsAndFormatter) { dateColumnsAndFormatter = buildDateColumnsFormatter(schema); } // start parsing the data try { var columnLength = schema.length, arr = void 0, element = void 0, arrLen = void 0; for (var n = 0; n < data.length; n++) { // initialize the row array arr = []; // get the current row element = data[n]; // check if elements is an array if (element.constructor === Array) { // array length will be minimum of schema length and currently encountered row array length // so that extra values are discarded arrLen = Math.min(columnLength, element.length); // loop over the columns and parse data for (i = 0; i < arrLen; i++) { arr[i] = _parseCell(schema[i], element[i], dateColumnsAndFormatter); } } else if ((typeof element === 'undefined' ? 'undefined' : _typeof(element)) === 'object') { // if currently encountered row is an object then JSON parse for (i = 0; i < columnLength; i++) { if (element[schema[i].name]) { arr[i] = _parseCell(schema[i], element[schema[i].name], dateColumnsAndFormatter); } } } else continue; // this is done to ensure blank array is not pushed into the data i.e. if a single string or number appears in between rows then it will be skipped rather than throwing error parsedData.push(arr); } } catch (e) { throw new Error('Error while parsing the data - ' + e); } } return parsedData; } /** * Perform indexing on the parsed data * @param {array} parsedData 2D array of parsed data * @param {array} schema array of JSON objects * @param {object} config configuration object * @param {object} dateColFormatter date column and formatter mapping */ function indexData(parsedData, schema, config, dateColFormatter) { if (config.enableIndex) { var i = void 0, comparator = void 0, dateColumnsAndFormatter = void 0; // If indexing is enabled but no index column is specified then we will smartly pick one column for indexing if (!config.indexBy) { // determine the index by column smartly dateColumnsAndFormatter = dateColFormatter; if (!dateColumnsAndFormatter) { dateColumnsAndFormatter = buildDateColumnsFormatter(schema); } // if any date column is present then priority is the date column var dateColumns = Object.keys(dateColumnsAndFormatter); if (dateColumns.length > 0) { // for multiple date columns, pick the first one config.indexBy = dateColumns[0]; } else { // otherwise if number column is present then pick the first number column for (i = 0; i < schema.length; i++) { if (schema[i].type && schema[i].type === 'number') { config.indexBy = schema[i].name; break; } } // if number column is not present then just pick the first column as index column if (i === schema.length) { config.indexBy = schema[0].name; } } } for (i = 0; i < schema.length; i++) { if (schema[i] && schema[i].name === config.indexBy) { break; } } if (i === schema.length) { throw new Error('Index column is not found in schema'); } // determine which type of comparator to be used for the sorting switch (schema[i].type) { case 'number': case 'date': // we will not be dealing with interval column // interval is only an intermediate column and not exposed // and user will only be feeding exterbal data to data store // but for children data table we must deal with interval column comparator = _comparators.numberComparator; break; default: comparator = _comparators.stringComparator; break; } // sorts the data based on the index column (0, _sort2['default'])(parsedData, function (a, b) { return comparator(a[i], b[i]); }); } } /** * Checks the data store's internal storage and create a non conflicting table id * @param {array} tableIdArr string array of table id inside a data store * @returns {string} unique table id which is not present in the provided tableIdArr */ function createTableID(tableIdArr) { var tableIdLen = tableIdArr.length, counter = tableIdLen + 1; while (tableIdArr.includes('table-' + counter)) { counter++; } return 'table-' + counter; } /** * Get the enableUTC flag of the column or global. * @param {string} columnName The name of the column to find * @param {array} schema The schema array */ function isUTCEnabled(columnName, schema) { var columnIndex = void 0; // get the column index columnIndex = columnIndexOf(columnName, schema); // if column not found OR column is not of type date/interval if (columnIndex === null || columnIndex === -1 || schema[columnIndex].type !== 'date' && schema[columnIndex].type !== 'interval') { return null; } return schema[columnIndex].enableUTC !== undefined ? schema[columnIndex].enableUTC : (0, _globalConfig.getConfig)('enableUTC'); } exports.columnIndexOf = columnIndexOf; exports.columnMinValue = columnMinValue; exports.columnMaxValue = columnMaxValue; exports.columnMinDiff = columnMinDiff; exports.columnExtents = columnExtents; exports.columnUnique = columnUnique; exports.addColumnsSchema = addColumnsSchema; exports.addColumnsData = addColumnsData; exports.parseAndIndexData = parseAndIndexData; exports.createTableID = createTableID; exports.buildDateColumnsFormatter = buildDateColumnsFormatter; exports.parseData = parseData; exports.indexData = indexData; exports.isUTCEnabled = isUTCEnabled; /***/ }), /* 277 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * Returns true if the provided parameter is a number * * @param {*} x The parameter to be checked * * @return {Boolean} */ var isNumber = function isNumber(x) { return typeof x === 'number' && !isNaN(x - x); }; exports.isNumber = isNumber; /***/ }), /* 278 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.stringComparator = exports.numberComparator = undefined; var _typeUtils = __webpack_require__(277); var numberComparator = function numberComparator(a, b) { if (a === null || typeof a === 'undefined') { return b === a ? 0 : 1; } else if ((0, _typeUtils.isNumber)(b)) { return a - b; } else if (isNaN(a) && isNaN(b)) { return 0; } else { return -1; } }, stringComparator = function stringComparator(a, b) { if (a && a.localeCompare) { return a.localeCompare(b); } else { return String(a).localeCompare(b); } }; exports.numberComparator = numberComparator; exports.stringComparator = stringComparator; /***/ }), /* 279 */ /***/ (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"); } } // binary insertion sort is the best method for sorting small arrays: it does // few compares, but can do data movement quadratic in the number of // elements. // [lo, hi) is a contiguous slice of a list, and is sorted via // binary insertion. This sort is stable. // On entry, must have lo <= start <= hi, and that [lo, start) is already // sorted (pass start == lo if you don't know!). /** * Sort a relatively smaller array in a stable manner * By default this method will sort array of primitive types in ascending order if comparer is not provided * For non primitive type, comparer must be provided * @param {array} arr - array to sort * @param {function} comparer - comparer function to sort * @param {number} lo - start index of array for sorting * @param {number} hi - end index of aray for sorting * @param {number} start - index to start comparison */ function binaryInsertionSort(arr, comparer, lo, hi, start) { lo = lo || 0; hi = hi || arr.length; start = start || lo + 1; if (!comparer) { comparer = function comparer(a, b) { return a - b; }; // default comparere is ascending order and for primitive type only } if (lo === start) { ++start; } for (; start < hi; ++start) { var l = lo, r = start, pivot = arr[r]; /* Invariants: * pivot >= all in [lo, l). * pivot < all in [r, start). * The second is vacuously true at the start. */ do { var p = l + (r - l >> 1); if (comparer(pivot, arr[p]) < 0) { r = p; } else { l = p + 1; } } while (l < r); /* The invariants still hold, so pivot >= all in [lo, l) and pivot < all in [l, start), so pivot belongs at l. Note that if there are elements equal to pivot, l points to the first slot after them -- that's why this sort is stable. Slide over to make room. */ for (var _p = start; _p > l; --_p) { arr[_p] = arr[_p - 1]; } arr[l] = pivot; } } /** * Stable merge sort implementation. This sorting does not modify the original array. * @param {array} arr - array to sort * @param {function} comparer - item comparison function * @return {array} - sorted array */ function mergeSort(arr, comparer) { if (arr.constructor !== Array) { throw new TypeError('Merge sort can only be applied on Array.'); } if (arr.length === 1) { return arr; } if (!comparer) { comparer = function comparer(a, b) { return a - b; }; } var middle = Math.floor(arr.length / 2), leftSection = arr.slice(0, middle), rightSection = arr.slice(middle); return merge(mergeSort(leftSection, comparer), mergeSort(rightSection, comparer), comparer); } /** * Merge 2 arrays and returns the merged array * @param {array} leftSection - first array to merge * @param {array} rightSection - second array to merge * @param {function} comparer - item comparison function */ function merge(leftSection, rightSection, comparer) { var result = [], leftSecIndex = 0, rightSecIndex = 0; while (leftSecIndex < leftSection.length && rightSecIndex < rightSection.length) { if (comparer(leftSection[leftSecIndex], rightSection[rightSecIndex]) <= 0) { result.push(leftSection[leftSecIndex]); leftSecIndex++; } else { result.push(rightSection[rightSecIndex]); rightSecIndex++; } } return result.concat(leftSection.slice(leftSecIndex)).concat(rightSection.slice(rightSecIndex)); } /** * This is an implementation of TimSort devised by Tim Peters for Python list. * This is the default sorting algorithm for Python, also this sorting is adopted in Java for non primitive object sorting starting from v7. * It's a stable and in-place hybrid sorting algorithm, which runs quite fast for real world data. * * Original documentation by Time Peters : https://svn.python.org/projects/python/trunk/Objects/listsort.txt * Original source code : https://github.com/python/cpython/blob/master/Objects/listobject.c * * Also part of the project refers to an existing JavaScript implementation of TimSort - https://github.com/mziccard/node-timsort */ /** * minimum size of a run */ var MINRUN_LENGTH = 64, /** * When we get into galloping mode, we stay there until both runs win less * often than MIN_GALLOP_LENGTH consecutive times. */ MIN_GALLOP_LENGTH = 7, /** * Default temp storage length. */ DEFAULT_TMP_STORAGE_LEN = 256, /** * Max stack size */ MAX_STACK_SIZE = 40; /** * Reverse a slice of a list in place, from lo up to (exclusive) hi. * @param {*} arr - array * @param {*} lo - lo index * @param {*} hi - hi index */ function reverseSlice(arr, lo, hi) { --hi; while (lo < hi) { var temp = arr[lo]; arr[lo++] = arr[hi]; arr[hi--] = temp; } } /** Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi is required on entry. "A run" is the longest ascending sequence, with lo[0] <= lo[1] <= lo[2] <= ... or the longest descending sequence, with lo[0] > lo[1] > lo[2] > ... For its intended use in a stable mergesort, the strictness of the defn of "descending" is needed so that the caller can safely reverse a descending sequence without violating stability (strict > ensures there are no equal elements to get out of order). If it's strictly descending then reverse the array. * @param {array} arr - array * @param {function} comparer - comparer function * @param {number} lo - lo index * @param {number} hi - hi index */ function countRun(arr, comparer, lo, hi) { var endIndex = lo + 1; if (endIndex === hi) { return 1; } // if strictly descending if (comparer(arr[endIndex++], arr[lo]) < 0) { while (endIndex < hi && comparer(arr[endIndex], arr[endIndex - 1]) < 0) { endIndex++; } reverseSlice(arr, lo, endIndex); } else { // if ascending while (endIndex < hi && comparer(arr[endIndex], arr[endIndex - 1]) >= 0) { endIndex++; } } return endIndex - lo; } /** * Compute a good value for the minimum run length; natural runs shorter * than this are boosted artificially via binary insertion. * * If n < 64, return n (it's too small to bother with fancy stuff). * Else if n is an exact power of 2, return 32. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but * strictly less than, an exact power of 2. * * @param {number} n */ function mergeComputeMinrun(n) { var r = 0; while (n >= MINRUN_LENGTH) { r |= n & 1; n >>= 1; } return n + r; } /** * Locate the proper position of key in a sorted vector; if the vector contains * an element equal to key, return the position immediately to the left of * the leftmost equal element. This ensures stability. * * @param {number} key - value to insert. * @param {array} arr - array * @param {number} start - first element in the range. * @param {number} length - length of the range. * @param {number} hint - index at which to begin the search. * @param {function} comparer - item comparison function. * @return {number} - index where to insert value. */ function gallopLeft(key, arr, start, length, hint, comparer) { var lastOffset = 0, maxOffset = 0, offset = 1, tmp = void 0, m = void 0; if (comparer(key, arr[start + hint]) > 0) { maxOffset = length - hint; /* a[start + hint] < key -- gallop right, until * a[start + hint + lastofs] < key <= a[start + hint + ofs] */ while (offset < maxOffset && comparer(key, arr[start + hint + offset]) > 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { // overflow offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Translate back to offsets relative to start lastOffset += hint; offset += hint; } else { /* key <= a[start + hint] -- gallop left, until * a[start + hint - ofs] < key <= a[start + hint - lastofs] */ maxOffset = hint + 1; while (offset < maxOffset && comparer(key, arr[start + hint - offset]) <= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Translate back to positive offsets relative to start tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } /* Now a[start + lastofs] < key <= a[start + ofs], so key belongs somewhere to the * right of lastofs but no farther right than ofs. Do a binary * search, with invariant a[start + lastofs - 1] < key <= a[start + ofs]. */ lastOffset++; while (lastOffset < offset) { m = lastOffset + (offset - lastOffset >>> 1); if (comparer(key, arr[start + m]) > 0) { lastOffset = m + 1; } else { offset = m; } } return offset; } /** * Exactly like gallopLeft(), except that if key already exists in arr[0:n], * finds the position immediately to the right of the rightmost equal value. * * @param {number} value - value to insert. * @param {array} arr - array in which to insert value. * @param {number} start - first element in the range. * @param {number} length - length of the range. * @param {number} hint - index at which to begin the search. * @param {function} comparer - item comparison function. * @return {number} - index where to insert value. */ function gallopRight(value, arr, start, length, hint, comparer) { var lastOffset = 0, maxOffset = 0, offset = 1, tmp = void 0, m = void 0; if (comparer(value, arr[start + hint]) < 0) { maxOffset = hint + 1; /* key < a[start + hint] -- gallop left, until * a[start + hint - ofs] <= key < a[start + hint - lastofs] */ while (offset < maxOffset && comparer(value, arr[start + hint - offset]) < 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Translate back to positive offsets relative to start tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } else { maxOffset = length - hint; /* a[start + hint] <= key -- gallop right, until * a[start + hint + lastofs] <= key < a[start + hint + ofs] */ while (offset < maxOffset && comparer(value, arr[start + hint + offset]) >= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Translate back to offsets relative to lastOffset += hint; offset += hint; } /* Now a[start + lastofs] <= key < a[start + ofs], so key belongs somewhere to the * right of lastofs but no farther right than ofs. Do a binary * search, with invariant a[start + lastofs-1] <= key < a[start + ofs]. */ lastOffset++; while (lastOffset < offset) { m = lastOffset + (offset - lastOffset >>> 1); if (comparer(value, arr[start + m]) < 0) { offset = m; } else { lastOffset = m + 1; } } return offset; } var MergeState = function () { function MergeState(arr, comparer) { _classCallCheck(this, MergeState); this.arr = arr; this.comparer = comparer; this.length = arr.length; this.tmpStorageLen = this.length < 2 * DEFAULT_TMP_STORAGE_LEN ? this.length >>> 1 : DEFAULT_TMP_STORAGE_LEN; this.tmp = new Array(this.tmpStorageLen); this.runBaseArr = new Array(MAX_STACK_SIZE); this.runLenArr = new Array(MAX_STACK_SIZE); this.minGallop = MIN_GALLOP_LENGTH; this.stackSize = 0; } /** * Push a new run on the stack * * @param {number} runStart - start index of the run in the original array * @param {number} runLength - length of the run */ MergeState.prototype.pushRun = function pushRun(runStart, runLength) { this.runBaseArr[this.stackSize] = runStart; this.runLenArr[this.stackSize] = runLength; this.stackSize++; }; /** * Examine the stack of runs waiting to be merged, merging adjacent runs * until the stack invariants are re-established: * 1. runLenArr[i - 3] > runLenArr[i - 2] + runLenArr[i - 1] * 2. runLenArr[i - 2] > runLenArr[i - 1] */ MergeState.prototype.mergeCollapse = function mergeCollapse() { var n = void 0; while (this.stackSize > 1) { n = this.stackSize - 2; if (n >= 1 && this.runLenArr[n - 1] <= this.runLenArr[n] + this.runLenArr[n + 1] || n >= 2 && this.runLenArr[n - 2] <= this.runLenArr[n] + this.runLenArr[n - 1]) { if (this.runLenArr[n - 1] < this.runLenArr[n + 1]) { n--; } } else if (this.runLenArr[n] > this.runLenArr[n + 1]) { break; } this.mergeAt(n); } }; /** * Regardless of invariants, merge all runs on the stack until only one remains. * This is used at the end of the mergesort. */ MergeState.prototype.mergeForceCollapse = function mergeForceCollapse() { var n = void 0; while (this.stackSize > 1) { n = this.stackSize - 2; if (n > 0 && this.runLenArr[n - 1] < this.runLenArr[n + 1]) { n--; } this.mergeAt(n); } }; /** * Merge the two runs at stack indices i and i+1 * * @param {number} i - index of the run to merge with next run */ MergeState.prototype.mergeAt = function mergeAt(i) { var comparer = this.comparer, arr = this.arr, start1 = this.runBaseArr[i], length1 = this.runLenArr[i], start2 = this.runBaseArr[i + 1], length2 = this.runLenArr[i + 1], k = void 0; /* Record the length of the combined runs; if i is the 3rd-last * run now, also slide over the last run (which isn't involved * in this merge). The current run i+1 goes away in any case. */ this.runLenArr[i] = length1 + length2; if (i === this.stackSize - 3) { this.runBaseArr[i + 1] = this.runBaseArr[i + 2]; this.runLenArr[i + 1] = this.runLenArr[i + 2]; } this.stackSize--; /* Where does run2 starts in run1 i.e. first elemet in the second run position in run1? * Elements in run1 before that can be ignored (already in place) */ k = gallopRight(arr[start2], arr, start1, length1, 0, comparer); start1 += k; length1 -= k; if (length1 === 0) { return; } /* Where does run1 ends in run2 i.e. last element of first run position in second run? * Elements in run2 after that can be ignored (already in place). */ length2 = gallopLeft(arr[start1 + length1 - 1], arr, start2, length2, length2 - 1, comparer); if (length2 === 0) { return; } /* Merge what remains of the runs, using a temp array with * min(length1, length2) elements. */ if (length1 <= length2) { this.mergeLo(start1, length1, start2, length2); } else { this.mergeHi(start1, length1, start2, length2); } }; /** * Merge the length1 elements starting at start1 with the length2 elements starting at * start2 = start1 + length1 in a stable way, in-place. length1 and length2 must be > 0. * Should have length1 <= length2. * * @param {number} start1 - first index of run1 * @param {number} length1 - length of run1 * @param {number} start2 - first index of run2 * @param {number} length2 - length of run2. */ MergeState.prototype.mergeLo = function mergeLo(start1, length1, start2, length2) { var i = 0, cursor1 = 0, cursor2 = start2, dest = start1, minGallop = void 0, count1 = void 0, count2 = void 0, exit = void 0; for (i = 0; i < length1; i++) { this.tmp[i] = this.arr[start1 + i]; } this.arr[dest++] = this.arr[cursor2++]; if (--length2 === 0) { for (i = 0; i < length1; i++) { this.arr[dest + i] = this.tmp[cursor1 + i]; } return; } if (length1 === 1) { for (i = 0; i < length2; i++) { this.arr[dest + i] = this.arr[cursor2 + i]; } this.arr[dest + length2] = this.tmp[cursor1]; return; } minGallop = this.minGallop; while (true) { count1 = 0; // number of times run1 won in a row count2 = 0; // number of times run2 won in a row exit = false; /* Do the straightforward thing until (if ever) one run * appears to win consistently. */ do { if (this.comparer(this.arr[cursor2], this.tmp[cursor1]) < 0) { this.arr[dest++] = this.arr[cursor2++]; count2++; count1 = 0; if (--length2 === 0) { exit = true; break; } } else { this.arr[dest++] = this.tmp[cursor1++]; count1++; count2 = 0; if (--length1 === 1) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) { break; } /* One run is winning so consistently that galloping may * be a huge win. So try that, and continue galloping until * (if ever) neither run appears to be winning consistently * anymore. */ do { count1 = gallopRight(this.arr[cursor2], this.tmp, cursor1, length1, 0, this.comparer); if (count1 !== 0) { for (i = 0; i < count1; i++) { this.arr[dest + i] = this.tmp[cursor1 + i]; } dest += count1; cursor1 += count1; length1 -= count1; if (length1 <= 1) { exit = true; break; } } this.arr[dest++] = this.arr[cursor2++]; if (--length2 === 0) { exit = true; break; } count2 = gallopLeft(this.tmp[cursor1], this.arr, cursor2, length2, 0, this.comparer); if (count2 !== 0) { for (i = 0; i < count2; i++) { this.arr[dest + i] = this.arr[cursor2 + i]; } dest += count2; cursor2 += count2; length2 -= count2; if (length2 === 0) { exit = true; break; } } this.arr[dest++] = this.tmp[cursor1++]; if (--length1 === 1) { exit = true; break; } minGallop--; } while (count1 >= MIN_GALLOP_LENGTH || count2 >= MIN_GALLOP_LENGTH); if (exit) { break; } if (minGallop < 0) { minGallop = 0; } minGallop += 2; /* penalize it for leaving galloping mode */ } this.minGallop = minGallop; if (minGallop < 1) { this.minGallop = 1; } if (length1 === 1) { for (i = 0; i < length2; i++) { this.arr[dest + i] = this.arr[cursor2 + i]; } this.arr[dest + length2] = this.tmp[cursor1]; } else { for (i = 0; i < length1; i++) { this.arr[dest + i] = this.tmp[cursor1 + i]; } } }; /** * Merge the length1 elements starting at start1 with the length2 elements starting at * start2 = start1 + length1 in a stable way, in-place. length1 and length2 must be > 0. * Should have length1 >= length2. * * @param {number} start1 - first index of run1 * @param {number} length1 - length of run1 * @param {number} start2 - first index of run2 * @param {number} length2 - length of run2. */ MergeState.prototype.mergeHi = function mergeHi(start1, length1, start2, length2) { var i = 0, cursor1 = start1 + length1 - 1, cursor2 = length2 - 1, dest = start2 + length2 - 1, customCursor = 0, customDest = 0, minGallop = void 0, count1 = void 0, count2 = void 0, exit = void 0; for (i = 0; i < length2; i++) { this.tmp[i] = this.arr[start2 + i]; } this.arr[dest--] = this.arr[cursor1--]; if (--length1 === 0) { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) { this.arr[customCursor + i] = this.tmp[i]; } return; } if (length2 === 1) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) { this.arr[customDest + i] = this.arr[customCursor + i]; } this.arr[dest] = this.tmp[cursor2]; return; } minGallop = this.minGallop; while (true) { count1 = 0; count2 = 0; exit = false; do { if (this.comparer(this.tmp[cursor2], this.arr[cursor1]) < 0) { this.arr[dest--] = this.arr[cursor1--]; count1++; count2 = 0; if (--length1 === 0) { exit = true; break; } } else { this.arr[dest--] = this.tmp[cursor2--]; count2++; count1 = 0; if (--length2 === 1) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) { break; } do { count1 = length1 - gallopRight(this.tmp[cursor2], this.arr, start1, length1, length1 - 1, this.comparer); if (count1 !== 0) { dest -= count1; cursor1 -= count1; length1 -= count1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = count1 - 1; i >= 0; i--) { this.arr[customDest + i] = this.arr[customCursor + i]; } if (length1 === 0) { exit = true; break; } } this.arr[dest--] = this.tmp[cursor2--]; if (--length2 === 1) { exit = true; break; } count2 = length2 - gallopLeft(this.arr[cursor1], this.tmp, 0, length2, length2 - 1, this.comparer); if (count2 !== 0) { dest -= count2; cursor2 -= count2; length2 -= count2; customDest = dest + 1; customCursor = cursor2 + 1; for (i = 0; i < count2; i++) { this.arr[customDest + i] = this.tmp[customCursor + i]; } if (length2 <= 1) { exit = true; break; } } this.arr[dest--] = this.arr[cursor1--]; if (--length1 === 0) { exit = true; break; } minGallop--; } while (count1 >= MIN_GALLOP_LENGTH || count2 >= MIN_GALLOP_LENGTH); if (exit) { break; } if (minGallop < 0) { minGallop = 0; } minGallop += 2; } this.minGallop = minGallop; if (minGallop < 1) { this.minGallop = 1; } if (length2 === 1) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) { this.arr[customDest + i] = this.arr[customCursor + i]; } this.arr[dest] = this.tmp[cursor2]; } else { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) { this.arr[customCursor + i] = this.tmp[i]; } } }; return MergeState; }(); /** * Sorts an array with the help of an comparer function. * This is an implementation of TimSort used in Python. It's stable and in place. * * @param {array} arr - array to sort * @param {function} comparer - item comparison function * @param {number} lo - index from which sorting will begin * @param {number} hi - end index of the range which will be sorted */ function timSort(arr, comparer, lo, hi) { if (arr.constructor !== Array) { throw new TypeError('Sorting can only be applied on arrays.'); } lo = lo || 0; hi = hi || arr.length; if (!comparer) { comparer = function comparer(a, b) { return a - b; }; } var nremaining = hi - lo, n = void 0, minrun = void 0, mergeState = void 0, force = void 0; if (nremaining < 2) { return; } // On small arrays binary sort can be used directly if (nremaining < MINRUN_LENGTH) { n = countRun(arr, comparer, lo, hi); binaryInsertionSort(arr, comparer, lo, hi, lo + n); return; } minrun = mergeComputeMinrun(nremaining); mergeState = new MergeState(arr, comparer); do { n = countRun(arr, comparer, lo, lo + nremaining); /* If short, extend to min(minrun, nremaining). */ if (n < minrun) { force = nremaining <= minrun ? nremaining : minrun; binaryInsertionSort(arr, comparer, lo, lo + force, lo + n); n = force; } mergeState.pushRun(lo, n); mergeState.mergeCollapse(); nremaining -= n; lo += n; } while (nremaining !== 0); mergeState.mergeForceCollapse(); } exports['default'] = timSort; exports.binaryInsertionSort = binaryInsertionSort; exports.mergeSort = mergeSort; /***/ }), /* 280 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var globalConfig = { enableUTC: false }; function getConfig(configName) { if (!configName) throw new Error('configName is missing'); return globalConfig[configName]; } function setConfig(configName, configVal) { if (!configName) throw new Error('configName is missing'); globalConfig[configName] = configVal; } exports.getConfig = getConfig; exports.setConfig = setConfig; /***/ }), /* 281 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.TimeConverter = undefined; var _timeFormatter = __webpack_require__(282); var _timeFormatter2 = _interopRequireDefault(_timeFormatter); var _timeParser = __webpack_require__(284); var _timeParser2 = _interopRequireDefault(_timeParser); var _week = __webpack_require__(290); var _week2 = __webpack_require__(289); var _day = __webpack_require__(285); var _day2 = _interopRequireDefault(_day); var _year = __webpack_require__(291); var _year2 = _interopRequireDefault(_year); var _day3 = __webpack_require__(288); var _day4 = _interopRequireDefault(_day3); var _year3 = __webpack_require__(293); var _year4 = _interopRequireDefault(_year3); var _enUS = __webpack_require__(295); var _enUS2 = _interopRequireDefault(_enUS); 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"); } } /** * @typedef {Object} LocaleDefinition Specifies locale specific formatting information. * @property {string} dateTime The date and time (%c) format specifier * @property {string} date The date (%x) format specifier * @property {string} time The time (%X) format specifier * @property {Array} periods The equivalents for AM and PM * @property {Array} days Full names of the weekdays starting from Sunday * @property {Array} shortDays Short names of the weekdays starting from Sunday * @property {Array} months Full names of the months starting from January * @property {Array} shortMonths Short names of the months starting from January */ var numberRe = /^\s*\d+/, // does not include percentages quarterRe = /^\s*Q\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g, pad = function pad(value, fill, width) { var sign = value < 0 ? '-' : '', string = (sign ? -value : value) + '', length = string.length, padStr = length < width ? new Array(width - length + 1).join(fill) + string : string; return sign + padStr; }, requote = function requote(s) { return s.replace(requoteRe, '\\$&'); }, formatRe = function formatRe(names) { return new RegExp('^(?:' + names.map(requote).join('|') + ')', 'i'); }, formatLookup = function formatLookup(names) { var map = {}, i = -1, n = names.length; while (++i < n) { map[names[i].toLowerCase()] = i; } return map; }, parseWeekdayNumberSunday = function parseWeekdayNumberSunday(d, string, i) { var n = numberRe.exec(string.slice(i, i + 1)); return n ? (d.w = +n[0], i + n[0].length) : -1; }, parseWeekdayNumberMonday = function parseWeekdayNumberMonday(d, string, i) { var n = numberRe.exec(string.slice(i, i + 1)); return n ? (d.u = +n[0], i + n[0].length) : -1; }, parseWeekNumberSunday = function parseWeekNumberSunday(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.U = +n[0], i + n[0].length) : -1; }, parseWeekNumberISO = function parseWeekNumberISO(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.V = +n[0], i + n[0].length) : -1; }, parseWeekNumberMonday = function parseWeekNumberMonday(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.W = +n[0], i + n[0].length) : -1; }, parseQuarter = function parseQuarter(d, string, i) { var n = quarterRe.exec(string.slice(i, i + 2)); return n ? (d.m = (n[0][1] - 1) * 3, i + n[0].length) : -1; }, parseFullYear = function parseFullYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 4)); return n ? (d.y = +n[0], i + n[0].length) : -1; }, parseYear = function parseYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1; }, parseZone = function parseZone(d, string, i) { var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6)); return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || '00')), i + n[0].length) : -1; }, parseMonthNumber = function parseMonthNumber(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.m = n[0] - 1, i + n[0].length) : -1; }, parseDayOfMonth = function parseDayOfMonth(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.d = +n[0], i + n[0].length) : -1; }, parseDayOfYear = function parseDayOfYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; }, parseHour24 = function parseHour24(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.H = +n[0], i + n[0].length) : -1; }, parseMinutes = function parseMinutes(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.M = +n[0], i + n[0].length) : -1; }, parseSeconds = function parseSeconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.S = +n[0], i + n[0].length) : -1; }, parseMilliseconds = function parseMilliseconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.L = +n[0], i + n[0].length) : -1; }, parseMicroseconds = function parseMicroseconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 6)); return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1; }, // eslint-disable-next-line parseLiteralPercent = function parseLiteralPercent(d, string, i) { var n = percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; }, parseUnixTimestamp = function parseUnixTimestamp(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.Q = +n[0], i + n[0].length) : -1; }, parseUnixTimestampSeconds = function parseUnixTimestampSeconds(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.Q = +n[0] * 1000, i + n[0].length) : -1; }, formatDayOfMonth = function formatDayOfMonth(d, p) { return pad(d.getDate(), p, 2); }, formatHour24 = function formatHour24(d, p) { return pad(d.getHours(), p, 2); }, formatHour12 = function formatHour12(d, p) { return pad(d.getHours() % 12 || 12, p, 2); }, formatDayOfYear = function formatDayOfYear(d, p) { return pad(1 + _day2['default'].count(_year2['default'].floor(d), d), p, 3); }, formatMilliseconds = function formatMilliseconds(d, p) { return pad(d.getMilliseconds(), p, 3); }, formatMicroseconds = function formatMicroseconds(d, p) { return formatMilliseconds(d, p) + '000'; }, formatMonthNumber = function formatMonthNumber(d, p) { return pad(d.getMonth() + 1, p, 2); }, formatMinutes = function formatMinutes(d, p) { return pad(d.getMinutes(), p, 2); }, formatSeconds = function formatSeconds(d, p) { return pad(d.getSeconds(), p, 2); }, formatQuarter = function formatQuarter(d, p) { return 'Q' + Math.ceil((d.getMonth() + 1) / 3) + ', ' + d.getFullYear(); }, formatWeekdayNumberMonday = function formatWeekdayNumberMonday(d) { var day = d.getDay(); return day === 0 ? 7 : day; }, formatWeekNumberSunday = function formatWeekNumberSunday(d, p) { return pad(_week.sunday.count(_year2['default'].floor(d), d), p, 2); }, formatWeekNumberISO = function formatWeekNumberISO(d, p) { var day = d.getDay(); d = day >= 4 || day === 0 ? _week.thursday.floor(d) : _week.thursday.ceil(d); return pad(_week.thursday.count(_year2['default'].floor(d), d) + (_year2['default'].floor(d).getDay() === 4), p, 2); }, formatWeekdayNumberSunday = function formatWeekdayNumberSunday(d) { return d.getDay(); }, formatWeekNumberMonday = function formatWeekNumberMonday(d, p) { return pad(_week.monday.count(_year2['default'].floor(d), d), p, 2); }, formatYear = function formatYear(d, p) { return pad(d.getFullYear() % 100, p, 2); }, formatFullYear = function formatFullYear(d, p) { return pad(d.getFullYear() % 10000, p, 4); }, formatZone = function formatZone(d) { var z = d.getTimezoneOffset(); return (z > 0 ? '-' : (z *= -1, '+')) + pad(z / 60 | 0, '0', 2) + pad(z % 60, '0', 2); }, formatUTCDayOfMonth = function formatUTCDayOfMonth(d, p) { return pad(d.getUTCDate(), p, 2); }, formatUTCHour24 = function formatUTCHour24(d, p) { return pad(d.getUTCHours(), p, 2); }, formatUTCHour12 = function formatUTCHour12(d, p) { return pad(d.getUTCHours() % 12 || 12, p, 2); }, formatUTCDayOfYear = function formatUTCDayOfYear(d, p) { return pad(1 + _day4['default'].count(_year4['default'].floor(d), d), p, 3); }, formatUTCMilliseconds = function formatUTCMilliseconds(d, p) { return pad(d.getUTCMilliseconds(), p, 3); }, formatUTCMicroseconds = function formatUTCMicroseconds(d, p) { return formatUTCMilliseconds(d, p) + '000'; }, formatUTCMonthNumber = function formatUTCMonthNumber(d, p) { return pad(d.getUTCMonth() + 1, p, 2); }, formatUTCMinutes = function formatUTCMinutes(d, p) { return pad(d.getUTCMinutes(), p, 2); }, formatUTCSeconds = function formatUTCSeconds(d, p) { return pad(d.getUTCSeconds(), p, 2); }, formatUTCQuarter = function formatUTCQuarter(d, p) { return 'Q' + Math.ceil((d.getUTCMonth() + 1) / 3) + ', ' + d.getUTCFullYear(); }, formatUTCWeekdayNumberMonday = function formatUTCWeekdayNumberMonday(d) { var dow = d.getUTCDay(); return dow === 0 ? 7 : dow; }, formatUTCWeekNumberSunday = function formatUTCWeekNumberSunday(d, p) { return pad(_week2.utcSunday.count(_year4['default'].floor(d), d), p, 2); }, formatUTCWeekNumberISO = function formatUTCWeekNumberISO(d, p) { var day = d.getUTCDay(); d = day >= 4 || day === 0 ? _week2.utcThursday.floor(d) : _week2.utcThursday.ceil(d); return pad(_week2.utcThursday.count(_year4['default'].floor(d), d) + (_year4['default'].floor(d).getUTCDay() === 4), p, 2); }, formatUTCWeekdayNumberSunday = function formatUTCWeekdayNumberSunday(d) { return d.getUTCDay(); }, formatUTCWeekNumberMonday = function formatUTCWeekNumberMonday(d, p) { return pad(_week2.utcMonday.count(_year4['default'].floor(d), d), p, 2); }, formatUTCYear = function formatUTCYear(d, p) { return pad(d.getUTCFullYear() % 100, p, 2); }, formatUTCFullYear = function formatUTCFullYear(d, p) { return pad(d.getUTCFullYear() % 10000, p, 4); }, formatUTCZone = function formatUTCZone() { return '+0000'; }, formatLiteralPercent = function formatLiteralPercent() { return '%'; }, formatUnixTimestamp = function formatUnixTimestamp(d) { return +d; }, formatUnixTimestampSeconds = function formatUnixTimestampSeconds(d) { return Math.floor(+d / 1000); }; /** * A TimeConverter can be used to format and parse dates in a number of * locale specific representations. To create a converter, pass a locale * object when instantiating the TimeConverter. */ var TimeConverter = function () { /** * Creates a TimeConverter instance with the given locale definition. It also internally * prepares locale specific formatting and parsing methods which is passed to * {@link TimeFormatter} and {@link TimeParser} when they are instantiated. * * @param {LocaleDefinition} locale The locale definition with which the TimeConverter * will be created */ function TimeConverter(locale) { var _this = this; _classCallCheck(this, TimeConverter); var localeDateTime = locale.dateTime, localeDate = locale.date, localeTime = locale.time, localePeriods = locale.periods, localeWeekdays = locale.days, localeShortWeekdays = locale.shortDays, localeMonths = locale.months, localeShortMonths = locale.shortMonths, periodRe = formatRe(localePeriods), periodLookup = formatLookup(localePeriods), weekdayRe = formatRe(localeWeekdays), weekdayLookup = formatLookup(localeWeekdays), shortWeekdayRe = formatRe(localeShortWeekdays), shortWeekdayLookup = formatLookup(localeShortWeekdays), monthRe = formatRe(localeMonths), monthLookup = formatLookup(localeMonths), shortMonthRe = formatRe(localeShortMonths), shortMonthLookup = formatLookup(localeShortMonths); /** * @ignore */ this._formats = { 'a': function a(d) { return localeShortWeekdays[d.getDay()]; }, 'A': function A(d) { return localeWeekdays[d.getDay()]; }, 'b': function b(d) { return localeShortMonths[d.getMonth()]; }, 'B': function B(d) { return localeMonths[d.getMonth()]; }, 'd': formatDayOfMonth, 'e': formatDayOfMonth, 'f': formatMicroseconds, 'H': formatHour24, 'I': formatHour12, 'j': formatDayOfYear, 'L': formatMilliseconds, 'm': formatMonthNumber, 'M': formatMinutes, 'p': function p(d) { return localePeriods[+(d.getHours() >= 12)]; }, 'q': formatQuarter, 'Q': formatUnixTimestamp, 's': formatUnixTimestampSeconds, 'S': formatSeconds, 'u': formatWeekdayNumberMonday, 'U': formatWeekNumberSunday, 'V': formatWeekNumberISO, 'w': formatWeekdayNumberSunday, 'W': formatWeekNumberMonday, 'y': formatYear, 'Y': formatFullYear, 'Z': formatZone, '%': formatLiteralPercent }; /** * @ignore */ this._utcFormats = { 'a': function a(d) { return localeShortWeekdays[d.getUTCDay()]; }, 'A': function A(d) { return localeWeekdays[d.getUTCDay()]; }, 'b': function b(d) { return localeShortMonths[d.getUTCMonth()]; }, 'B': function B(d) { return localeMonths[d.getUTCMonth()]; }, 'd': formatUTCDayOfMonth, 'e': formatUTCDayOfMonth, 'f': formatUTCMicroseconds, 'H': formatUTCHour24, 'I': formatUTCHour12, 'j': formatUTCDayOfYear, 'L': formatUTCMilliseconds, 'm': formatUTCMonthNumber, 'M': formatUTCMinutes, 'p': function p(d) { return localePeriods[+(d.getUTCHours() >= 12)]; }, 'q': formatUTCQuarter, 'Q': formatUnixTimestamp, 's': formatUnixTimestampSeconds, 'S': formatUTCSeconds, 'u': formatUTCWeekdayNumberMonday, 'U': formatUTCWeekNumberSunday, 'V': formatUTCWeekNumberISO, 'w': formatUTCWeekdayNumberSunday, 'W': formatUTCWeekNumberMonday, 'y': formatUTCYear, 'Y': formatUTCFullYear, 'Z': formatUTCZone, '%': formatLiteralPercent }; /** * @ignore */ this._parses = { 'a': function a(d, string, i) { var n = shortWeekdayRe.exec(string.slice(i)); if (n) { d.w = shortWeekdayLookup[n[0].toLowerCase()]; return i + n[0].length; } else { return -1; } }, 'A': function A(d, string, i) { var n = weekdayRe.exec(string.slice(i)); if (n) { d.w = weekdayLookup[n[0].toLowerCase()]; return i + n[0].length; } else { return -1; } }, 'b': function b(d, string, i) { var n = shortMonthRe.exec(string.slice(i)); if (n) { d.m = shortMonthLookup[n[0].toLowerCase()]; return i + n[0].length; } else { return -1; } }, 'B': function B(d, string, i) { var n = monthRe.exec(string.slice(i)); if (n) { d.m = monthLookup[n[0].toLowerCase()]; return i + n[0].length; } else { return -1; } }, 'c': null, 'd': parseDayOfMonth, 'e': parseDayOfMonth, 'f': parseMicroseconds, 'H': parseHour24, 'I': parseHour24, 'j': parseDayOfYear, 'L': parseMilliseconds, 'm': parseMonthNumber, 'M': parseMinutes, 'p': function p(d, string, i) { var n = periodRe.exec(string.slice(i)); if (n) { d.p = periodLookup[n[0].toLowerCase()]; return i + n[0].length; } else { return -1; } }, 'Q': parseUnixTimestamp, 'q': parseQuarter, 's': parseUnixTimestampSeconds, 'S': parseSeconds, 'u': parseWeekdayNumberMonday, 'U': parseWeekNumberSunday, 'V': parseWeekNumberISO, 'w': parseWeekdayNumberSunday, 'W': parseWeekNumberMonday, 'x': null, 'X': null, 'y': parseYear, 'Y': parseFullYear, 'Z': parseZone, '%': parseLiteralPercent }; this._formats.x = function (d) { return new _timeFormatter2['default'](localeDate, _this._formats).format(d); }; this._formats.X = function (d) { return new _timeFormatter2['default'](localeTime, _this._formats).format(d); }; this._formats.c = function (d) { return new _timeFormatter2['default'](localeDateTime, _this._formats).format(d); }; this._utcFormats.x = function (d) { return new _timeFormatter2['default'](localeDate, _this._utcFormats).format(d); }; this._utcFormats.X = function (d) { return new _timeFormatter2['default'](localeTime, _this._utcFormats).format(d); }; this._utcFormats.c = function (d) { return new _timeFormatter2['default'](localeDateTime, _this._utcFormats).format(d); }; this._parses.c = function (d, string, i) { return new _timeParser2['default'](localeDateTime, _this._parses).parseSpecifier(d, string, i); }; this._parses.x = function (d, string, i) { return new _timeParser2['default'](localeDate, _this._parses).parseSpecifier(d, string, i); }; this._parses.X = function (d, string, i) { return new _timeParser2['default'](localeTime, _this._parses).parseSpecifier(d, string, i); }; } /** * Creates a time formatter for the given string specifier. * * @param {string} specifier The specifier which will be used by the * formatter to format a date into a string. It may contain the following directives: * * `%a` - abbreviated weekday name. * * `%A` - full weekday name. * * `%b` - abbreviated month name. * * `%B` - full month name. * * `%c` - the locale’s date and time, such as %x, %X. * * `%d` - zero-padded day of the month as a decimal number [01,31]. * * `%e` - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d. * * `%f` - microseconds as a decimal number [000000, 999999]. * * `%H` - hour (24-hour clock) as a decimal number [00,23]. * * `%I` - hour (12-hour clock) as a decimal number [01,12]. * * `%j` - day of the year as a decimal number [001,366]. * * `%m` - month as a decimal number [01,12]. * * `%M` - minute as a decimal number [00,59]. * * `%L` - milliseconds as a decimal number [000, 999]. * * `%p` - either AM or PM. * * `%Q` - milliseconds since UNIX epoch. * * `%s` - seconds since UNIX epoch. * * `%S` - second as a decimal number [00,61]. * * `%u` - Monday-based (ISO 8601) weekday as a decimal number [1,7]. * * `%U` - Sunday-based week of the year as a decimal number [00,53]. All days * in a new year preceding the first Sunday are considered to be in week 0. * * `%V` - ISO 8601 week of the year as a decimal number [01, 53]. Weeks start * on a Monday, and are numbered from 01, for the first week, up to 52 or 53, * for the last week. Week 1 is the first week where four or more days fall * within the new year. Basically, week 01 is the first week of the * year that contains a Thursday; or, the week that has 4 January in it. * * `%w` - Sunday-based weekday as a decimal number [0,6]. * * `%W` - Monday-based week of the year as a decimal number [00,53]. All days * in a new year preceding the first Monday are considered to be in week 0. * * `%x` - the locale’s date, such as %-m/%-d/%Y. * * `%X` - the locale’s time, such as %-I:%M:%S %p. * * `%y` - year without century as a decimal number [00,99]. * * `%Y` - year with century as a decimal number. * * `%Z` - time zone offset, such as -0700, -07:00, -07, or Z. * * `%%` - a literal percent sign (%) * * The directives `%a`, `%A`, `%b`, `%B`, `%c`, `%p`, `%x`, `%X` are affected by the * locale definition. * * @example * new TimeConverter(LocaleDefinition).formatter('%B %Y').format(new Date(2017, 3, 4)); // "April 2017" * * @returns {TimeFormatter} A TimeFormatter instance which is able to format a * JavaScript Date instance according to the given specifier string. */ TimeConverter.prototype.formatter = function formatter(specifier) { return new _timeFormatter2['default'](specifier, this._formats); }; /** * Same as {@link TimeConverter#formatter}, except that all directives are * interpreted as Coordinated Universal Time (UTC) rather than local time. * * @param {string} specifier The specifier which will be used by the formatter * to format a date into a string. It may contain the same directives as the * specifier passed to {@link TimeConverter#formatter}. * * @returns {TimeFormatter} A TimeFormatter instance which is able to format a * JavaScript Date instance according to the given specifier string. */ TimeConverter.prototype.utcFormatter = function utcFormatter(specifier) { return new _timeFormatter2['default'](specifier, this._utcFormats); }; /** * Creates a time parser for the given string specifier. * * @param {string} specifier The specifier which will be used by the parser * to parse a string into a date. It may contain the same directives as the * specifier passed to {@link TimeConverter#formatter}. * * @returns {TimeParser} A TimeParser instance which is able to **strictly** parse a * string according to the given specifier. */ TimeConverter.prototype.parser = function parser(specifier) { return new _timeParser2['default'](specifier += '', this._parses, function (d) { if (d.y >= 0 && d.y < 100) { var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); date.setFullYear(d.y); return date; } return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); }); }; /** * Same as {@link TimeConverter#parser}, except that all directives are * interpreted as Coordinated Universal Time (UTC) rather than local time. * * @param {string} specifier The specifier which will be used by the parser * to parse a string into a date. It may contain the same directives as the * specifier passed to {@link TimeConverter#formatter}. * * @returns {TimeParser} A TimeParser instance which is able to **strictly** parse a * string according to the given specifier. */ TimeConverter.prototype.utcParser = function utcParser(specifier) { return new _timeParser2['default'](specifier += '', this._parses, _timeParser.utcDate); }; return TimeConverter; }(); exports.TimeConverter = TimeConverter; /** * An instance of {@link TimeConverter} initialized with the * English (United States) locale definition. * @type {TimeConverter} */ exports['default'] = new TimeConverter(_enUS2['default']); /***/ }), /* 282 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _pads = __webpack_require__(283); var _pads2 = _interopRequireDefault(_pads); 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"); } } /** * @type {number} The character code for the `%` character. */ var PERCENT_CHAR_CODE = 37, isNil = function isNil(x) { return x === null || typeof x === 'undefined'; }; /** * A TimeFormatter is able to format a Javascript Date instance into strings according * to the given specifier and locale specific formatter functions. */ var TimeFormatter = function () { /** * @param {string} specifier The specifier using which the formatter will format strings * @param {object} formats An object containing locale specific formatting functions * keyed by specifier directives. */ function TimeFormatter(specifier, formats) { _classCallCheck(this, TimeFormatter); /** * @type {string} */ this._specifier = specifier; /** * @type {object} */ this._formats = formats; } /** * Formats a given JavaScript Date instance into a string according to the given specifier. * * @param {Date} date The JavaScript Date instance which will be formatted into a string. * * @returns {string} A string representation of the provided date. */ TimeFormatter.prototype.format = function format(date) { var string = [], i = -1, j = 0, specifier = this._specifier, n = specifier.length, c, pad, format; if (!(date instanceof Date)) date = new Date(+date); while (++i < n) { if (specifier.charCodeAt(i) === PERCENT_CHAR_CODE) { string.push(specifier.slice(j, i)); c = specifier.charAt(++i); pad = _pads2['default'][c]; if (isNil(pad)) { pad = c === 'e' ? ' ' : '0'; } else { c = specifier.charAt(++i); } format = this._formats[c]; if (format) { c = format(date, pad); } string.push(c); j = i + 1; } } string.push(specifier.slice(j, i)); return string.join(''); }; /** * @returns {string} The specifier string using which Dates are formatted into strings */ TimeFormatter.prototype.toString = function toString() { return this._specifier; }; return TimeFormatter; }(); exports['default'] = TimeFormatter; /***/ }), /* 283 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { '-': '', '_': ' ', 0: '0' }; /***/ }), /* 284 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.utcDate = undefined; var _pads = __webpack_require__(283); var _pads2 = _interopRequireDefault(_pads); var _day = __webpack_require__(285); var _day2 = _interopRequireDefault(_day); var _day3 = __webpack_require__(288); var _day4 = _interopRequireDefault(_day3); var _week = __webpack_require__(289); var _week2 = __webpack_require__(290); 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"); } } /** * @typedef {Object} DateObject Specifies numeric information about Date construction. * @property {number} y The full year * @property {number} m Zero based month of year * @property {number} d The day of month * @property {number} H Hour of day in 24-hour format * @property {number} M Minute of hour * @property {number} S Second of minute * @property {number} L Millisecond of second */ /** * @type {number} The character code for the `%` character. */ var PERCENT_CHAR_CODE = 37, newYear = function newYear(y) { return { y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0 }; }, utcDate = function utcDate(d) { if (d.y >= 0 && d.y < 100) { var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); date.setUTCFullYear(d.y); return date; } return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); }; /** * A TimeParser is able to parse a string into a Javascript Date instance according * to the given specifier and locale specific parser functions. */ var TimeParser = function () { /** * @param {string} specifier The specifier using which the parsrer will parse strings * @param {object} formats An object containing locale specific parsing functions * keyed by specifier directives. * @param {function} Date newDate A Date factory. When passed a * {@link DateObject}, returns a JavaScript Date instance created using it. */ function TimeParser(specifier, parses, newDate) { _classCallCheck(this, TimeParser); /** * @type {string} */ this._specifier = specifier; /** * @type {object} */ this._parses = parses; /** * @type {function} */ this._newDate = newDate; } /** * Parses a specifier into dates * * @param {Date} d The Date to be used as a reference for parsing * @param {string} string The specifier to be parsed * @param {number} j The index from which to parse the specifier * * @returns {number} Parsed information about the specifier. Returns * -1 if parsing was not possible, */ TimeParser.prototype.parseSpecifier = function parseSpecifier(d, string, j) { var i = 0, n = this._specifier.length, m = string.length, c, parse; while (i < n) { if (j >= m) return -1; c = this._specifier.charCodeAt(i++); if (c === PERCENT_CHAR_CODE) { c = this._specifier.charAt(i++); parse = this._parses[c in _pads2['default'] ? this._specifier.charAt(i++) : c]; if (!parse || (j = parse(d, string, j)) < 0) { return -1; } } else if (c !== string.charCodeAt(j++)) { return -1; } } return j; }; /** * Parses a given string into a JavaScript Date instance according to the given specifier. * * @param {string} string The string which will be parsed into a Javascript Date instance. * * @returns {Date} A JavaScript Date instance representing the given string. */ TimeParser.prototype.parse = function parse(string) { var d = newYear(1900), i, week, day; string += ''; i = this.parseSpecifier(d, string, 0); if (i !== string.length) return null; // If a UNIX timestamp is specified, return it. if ('Q' in d) return new Date(d.Q); // The am-pm flag is 0 for AM, and 1 for PM. if ('p' in d) d.H = d.H % 12 + d.p * 12; // Convert day-of-week and week-of-year to day-of-year. if ('V' in d) { // Can't deal with this if (d.V < 1 || d.V > 53) return null; if (!('w' in d)) d.w = 1; if ('Z' in d) { week = utcDate(newYear(d.y)); day = week.getUTCDay(); week = day > 4 || day === 0 ? _week.utcMonday.ceil(week) : _week.utcMonday.floor(week); week = _day4['default'].offset(week, (d.V - 1) * 7); d.y = week.getUTCFullYear(); d.m = week.getUTCMonth(); d.d = week.getUTCDate() + (d.w + 6) % 7; } else { week = this._newDate(newYear(d.y)); day = week.getDay(); week = day > 4 || day === 0 ? _week2.monday.ceil(week) : _week2.monday.floor(week); week = _day2['default'].offset(week, (d.V - 1) * 7); d.y = week.getFullYear(); d.m = week.getMonth(); d.d = week.getDate() + (d.w + 6) % 7; } } else if ('W' in d || 'U' in d) { if (!('w' in d)) { if ('u' in d) { d.w = d.u % 7; } else { d.w = 'W' in d ? 1 : 0; } } day = 'Z' in d ? utcDate(newYear(d.y)).getUTCDay() : this._newDate(newYear(d.y)).getDay(); d.m = 0; d.d = 'W' in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7; } // If a time zone is specified, all fields are interpreted as UTC and then // offset according to the specified time zone. if ('Z' in d) { d.H += d.Z / 100 | 0; d.M += d.Z % 100; return utcDate(d); } // Otherwise, all fields are in local time. return this._newDate(d); }; /** * @returns {string} The specifier string using which strings are parsed into Dates */ TimeParser.prototype.toString = function toString() { return this._specifier; }; return TimeParser; }(); exports.utcDate = utcDate; exports['default'] = TimeParser; /***/ }), /* 285 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var day = new _timeInterval2['default']('day', function (d) { return d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setDate(d.getDate() + s); }, function (s, e) { return (e - s - (e.getTimezoneOffset() - s.getTimezoneOffset()) * _durations.durationMinute) / _durations.durationDay; }, function (d) { return d.getDate() - 1; }); exports['default'] = day; /***/ }), /* 286 */ /***/ (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"); } } var t0 = new Date(), t1 = new Date(), // The following variable is used to prevent UglifyJS from removing braces. // IE8 cannot handle do while loops nested within while loops unless they have // braces surrounding the code block. ie8Satisfier = 0; // eslint-disable-line no-unused-vars var isNil = function isNil(d) { return typeof d === 'undefined' || d === null; }; var TimeInterval = function () { function TimeInterval(name, floori, offseti, count, field) { _classCallCheck(this, TimeInterval); this._name = name; this._floori = floori; this._offseti = offseti; this._count = count; this._field = field; } TimeInterval.prototype.name = function name() { return this._name; }; TimeInterval.prototype.floor = function floor(date) { var newDate = new Date(Number(date)); this._floori(newDate); return newDate; }; TimeInterval.prototype.ceil = function ceil(date) { var datei = new Date(date - 1); this._floori(datei); this._offseti(datei, 1); this._floori(datei); return datei; }; TimeInterval.prototype.round = function round(date) { var d0 = this.floor(date), d1 = this.ceil(date); return date - d0 < d1 - date ? d0 : d1; }; TimeInterval.prototype.offset = function offset(date, step) { var datei = new Date(Number(date)); this._offseti(datei, isNil(step) ? 1 : Math.floor(step)); return datei; }; TimeInterval.prototype.range = function range(start, stop, step) { var range = [], starti = this.ceil(start), stepi = isNil(step) ? 1 : Math.floor(step); var previous = void 0; if (!(starti < stop) || !(stepi > 0)) return range; do { previous = new Date(Number(starti)); range.push(previous); this._offseti(starti, stepi); this._floori(starti); // eslint-disable-next-line no-unmodified-loop-condition } while (previous < starti && starti < stop); return range; }; TimeInterval.prototype.filter = function filter(test) { var _this = this; return new TimeInterval(this.name(), function (date) { if (!Number.isNaN(Number(date))) { // eslint-disable-next-line no-sequences while (_this._floori(date), !test(date)) { date.setTime(date - 1); } } }, function (date, step) { var stepi = step; if (!Number.isNaN(Number(date))) { if (stepi < 0) { while (++stepi <= 0) { ie8Satisfier++; do { _this._offseti(date, -1); } while (!test(date)); } } else { while (--stepi >= 0) { do { _this._offseti(date, 1); } while (!test(date)); } } } }); }; TimeInterval.prototype.count = function count(start, end) { var count = 0; if (this._count) { t0.setTime(Number(start)); t1.setTime(Number(end)); this._floori(t0); this._floori(t1); count = Math.floor(this._count(t0, t1)); } return count; }; TimeInterval.prototype.every = function every(step) { var _this2 = this; var stepi = Math.floor(step); var everyInterval = null; if (!this._count || !Number.isFinite(stepi) || !(stepi > 0)) { everyInterval = null; } else if (!(stepi > 1)) { everyInterval = this; } else { everyInterval = this.filter(this._field ? function (d) { return _this2._field(d) % stepi === 0; } : function (d) { return _this2.count(0, d) % stepi === 0; }); } return everyInterval; }; return TimeInterval; }(); exports['default'] = TimeInterval; /***/ }), /* 287 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var durationSecond = 1e+3, durationMinute = 6e+4, durationHour = 36e+5, durationDay = 864e+5, durationWeek = 6048e+5, durationMonth = 26298E+5, durationQuarter = 78894e+5, durationYear = 315576e+5; exports.durationSecond = durationSecond; exports.durationMinute = durationMinute; exports.durationHour = durationHour; exports.durationDay = durationDay; exports.durationWeek = durationWeek; exports.durationMonth = durationMonth; exports.durationQuarter = durationQuarter; exports.durationYear = durationYear; /***/ }), /* 288 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcDay = new _timeInterval2['default']('day', function (d) { return d.setUTCHours(0, 0, 0, 0); }, function (d, s) { return d.setUTCDate(d.getUTCDate() + s); }, function (s, e) { return (e - s) / _durations.durationDay; }, function (d) { return d.getUTCDate() - 1; }); exports['default'] = utcDay; /***/ }), /* 289 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.utcSaturday = exports.utcFriday = exports.utcThursday = exports.utcWednesday = exports.utcTuesday = exports.utcMonday = exports.utcSunday = undefined; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcWeekday = function utcWeekday(i, n) { return new _timeInterval2['default'](n, function (d) { d.setUTCDate(d.getUTCDate() - (d.getUTCDay() + 7 - i) % 7); d.setUTCHours(0, 0, 0, 0); }, function (d, s) { return d.setUTCDate(d.getUTCDate() + s * 7); }, function (s, e) { return (e - s) / _durations.durationWeek; }); }, utcWeek = utcWeekday(0, 'week'), utcSunday = utcWeekday(0, 'sunday'), utcMonday = utcWeekday(1, 'monday'), utcTuesday = utcWeekday(2, 'tuesday'), utcWednesday = utcWeekday(3, 'wednesday'), utcThursday = utcWeekday(4, 'thursday'), utcFriday = utcWeekday(5, 'friday'), utcSaturday = utcWeekday(6, 'saturday'); exports['default'] = utcWeek; exports.utcSunday = utcSunday; exports.utcMonday = utcMonday; exports.utcTuesday = utcTuesday; exports.utcWednesday = utcWednesday; exports.utcThursday = utcThursday; exports.utcFriday = utcFriday; exports.utcSaturday = utcSaturday; /***/ }), /* 290 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.saturday = exports.friday = exports.thursday = exports.wednesday = exports.tuesday = exports.monday = exports.sunday = undefined; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var weekday = function weekday(i, n) { return new _timeInterval2['default'](n, function (d) { d.setDate(d.getDate() - (d.getDay() + 7 - i) % 7); d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setDate(d.getDate() + s * 7); }, function (s, e) { return (e - s - (e.getTimezoneOffset() - s.getTimezoneOffset()) * _durations.durationMinute) / _durations.durationWeek; }); }, week = weekday(0, 'week'), sunday = weekday(0, 'sunday'), monday = weekday(1, 'monday'), tuesday = weekday(2, 'tuesday'), wednesday = weekday(3, 'wednesday'), thursday = weekday(4, 'thursday'), friday = weekday(5, 'friday'), saturday = weekday(6, 'saturday'); exports['default'] = week; exports.sunday = sunday; exports.monday = monday; exports.tuesday = tuesday; exports.wednesday = wednesday; exports.thursday = thursday; exports.friday = friday; exports.saturday = saturday; /***/ }), /* 291 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeIntervalYear = __webpack_require__(292); var _timeIntervalYear2 = _interopRequireDefault(_timeIntervalYear); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var year = new _timeIntervalYear2['default']('year', function (d) { d.setMonth(0, 1); d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setFullYear(d.getFullYear() + s); }, function (s, e) { return e.getFullYear() - s.getFullYear(); }, function (d) { return d.getFullYear(); }); exports['default'] = year; /***/ }), /* 292 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var YearInterval = function (_TimeInterval) { _inherits(YearInterval, _TimeInterval); function YearInterval() { _classCallCheck(this, YearInterval); return _possibleConstructorReturn(this, _TimeInterval.apply(this, arguments)); } YearInterval.prototype.every = function every(step) { var stepi = Math.floor(step); if (!this.count || !Number.isFinite(stepi) || !(stepi > 0)) { return null; } return new _timeInterval2['default']('year', function (d) { d.setFullYear(Math.floor(d.getFullYear() / stepi) * stepi); d.setMonth(0, 1); d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setFullYear(d.getFullYear() + s * stepi); }); }; return YearInterval; }(_timeInterval2['default']); exports['default'] = YearInterval; /***/ }), /* 293 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeIntervalUtcYear = __webpack_require__(294); var _timeIntervalUtcYear2 = _interopRequireDefault(_timeIntervalUtcYear); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcYear = new _timeIntervalUtcYear2['default']('year', function (d) { d.setUTCMonth(0, 1); d.setUTCHours(0, 0, 0, 0); }, function (d, s) { return d.setUTCFullYear(d.getUTCFullYear() + s); }, function (s, e) { return e.getUTCFullYear() - s.getUTCFullYear(); }, function (d) { return d.getUTCFullYear(); }); exports['default'] = utcYear; /***/ }), /* 294 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint-disable class-methods-use-this */ var UtcYearInterval = function (_TimeInterval) { _inherits(UtcYearInterval, _TimeInterval); function UtcYearInterval() { _classCallCheck(this, UtcYearInterval); return _possibleConstructorReturn(this, _TimeInterval.apply(this, arguments)); } // An simpler, optimized implementation for a UTC Year Interval UtcYearInterval.prototype.every = function every(step) { if (!isFinite(step = Math.floor(step)) || !(step > 0)) { return null; } else { return new _timeInterval2['default']('year', function (d) { d.setUTCFullYear(Math.floor(d.getUTCFullYear() / step) * step); d.setUTCMonth(0, 1); d.setUTCHours(0, 0, 0, 0); }, function (d, s) { return d.setUTCFullYear(d.getUTCFullYear() + s * step); }); } }; return UtcYearInterval; }(_timeInterval2['default']); exports['default'] = UtcYearInterval; /***/ }), /* 295 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * The English (United States) locale time definition. * @type {LocaleDefinition} */ var enUS = { dateTime: '%x, %X', date: '%-m/%-d/%Y', time: '%-I:%M:%S %p', periods: ['AM', 'PM'], days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }; exports['default'] = enUS; /***/ }), /* 296 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(297); __webpack_require__(78); __webpack_require__(298); __webpack_require__(301); __webpack_require__(312); __webpack_require__(315); __webpack_require__(317); module.exports = __webpack_require__(7).Set; /***/ }), /* 297 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.3.6 Object.prototype.toString() var classof = __webpack_require__(90); var test = {}; test[__webpack_require__(65)('toStringTag')] = 'z'; if (test + '' != '[object z]') { __webpack_require__(18)(Object.prototype, 'toString', function toString() { return '[object ' + classof(this) + ']'; }, true); } /***/ }), /* 298 */ /***/ (function(module, exports, __webpack_require__) { var $iterators = __webpack_require__(299); var getKeys = __webpack_require__(48); var redefine = __webpack_require__(18); var global = __webpack_require__(6); var hide = __webpack_require__(8); var Iterators = __webpack_require__(81); var wks = __webpack_require__(65); 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); } } /***/ }), /* 299 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__(98); var step = __webpack_require__(300); var Iterators = __webpack_require__(81); var toIObject = __webpack_require__(24); // 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__(80)(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'); /***/ }), /* 300 */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /* 301 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var strong = __webpack_require__(302); var validate = __webpack_require__(308); var SET = 'Set'; // 23.2 Set Objects module.exports = __webpack_require__(309)(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); /***/ }), /* 302 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var dP = __webpack_require__(9).f; var create = __webpack_require__(46); var redefineAll = __webpack_require__(303); var ctx = __webpack_require__(21); var anInstance = __webpack_require__(304); var forOf = __webpack_require__(305); var $iterDefine = __webpack_require__(80); var step = __webpack_require__(300); var setSpecies = __webpack_require__(306); var DESCRIPTORS = __webpack_require__(13); var fastKey = __webpack_require__(307).fastKey; var validate = __webpack_require__(308); 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); } }; /***/ }), /* 303 */ /***/ (function(module, exports, __webpack_require__) { var redefine = __webpack_require__(18); module.exports = function (target, src, safe) { for (var key in src) redefine(target, key, src[key], safe); return target; }; /***/ }), /* 304 */ /***/ (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; }; /***/ }), /* 305 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(21); var call = __webpack_require__(86); var isArrayIter = __webpack_require__(87); var anObject = __webpack_require__(10); var toLength = __webpack_require__(31); var getIterFn = __webpack_require__(89); 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; /***/ }), /* 306 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(6); var dP = __webpack_require__(9); var DESCRIPTORS = __webpack_require__(13); var SPECIES = __webpack_require__(65)('species'); module.exports = function (KEY) { var C = global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /* 307 */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(20)('meta'); var isObject = __webpack_require__(11); var has = __webpack_require__(19); var setDesc = __webpack_require__(9).f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(14)(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 }; /***/ }), /* 308 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; /***/ }), /* 309 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(6); var $export = __webpack_require__(5); var redefine = __webpack_require__(18); var redefineAll = __webpack_require__(303); var meta = __webpack_require__(307); var forOf = __webpack_require__(305); var anInstance = __webpack_require__(304); var isObject = __webpack_require__(11); var fails = __webpack_require__(14); var $iterDetect = __webpack_require__(91); var setToStringTag = __webpack_require__(83); var inheritIfRequired = __webpack_require__(310); 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; }; /***/ }), /* 310 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); var setPrototypeOf = __webpack_require__(311).set; module.exports = function (that, target, C) { var S = target.constructor; var P; if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { setPrototypeOf(that, P); } return that; }; /***/ }), /* 311 */ /***/ (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__(11); var anObject = __webpack_require__(10); 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__(21)(Function.call, __webpack_require__(40).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 }; /***/ }), /* 312 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(5); $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(313)('Set') }); /***/ }), /* 313 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = __webpack_require__(90); var from = __webpack_require__(314); module.exports = function (NAME) { return function toJSON() { if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; /***/ }), /* 314 */ /***/ (function(module, exports, __webpack_require__) { var forOf = __webpack_require__(305); module.exports = function (iter, ITERATOR) { var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; /***/ }), /* 315 */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of __webpack_require__(316)('Set'); /***/ }), /* 316 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://tc39.github.io/proposal-setmap-offrom/ var $export = __webpack_require__(5); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { of: function of() { var length = arguments.length; var A = new Array(length); while (length--) A[length] = arguments[length]; return new this(A); } }); }; /***/ }), /* 317 */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from __webpack_require__(318)('Set'); /***/ }), /* 318 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://tc39.github.io/proposal-setmap-offrom/ var $export = __webpack_require__(5); var aFunction = __webpack_require__(22); var ctx = __webpack_require__(21); var forOf = __webpack_require__(305); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { var mapFn = arguments[1]; var mapping, A, n, cb; aFunction(this); mapping = mapFn !== undefined; if (mapping) aFunction(mapFn); if (source == undefined) return new this(); A = []; if (mapping) { n = 0; cb = ctx(mapFn, arguments[2], 2); forOf(source, false, function (nextItem) { A.push(cb(nextItem, n++)); }); } else { forOf(source, false, A.push, A); } return new this(A); } }); }; /***/ }), /* 319 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * Attaches handler functions to an event * * @param {string} eventName The name of the event * @param {function} handler The handler function for the event * @param {object} sender The object on which the event occured */ function addHandler(eventName, handler, sender) { var attachedHandlersLen; // in case handler is sent as array, we recursively process it if (handler instanceof Array) { var recurseReturn = [], handlerLen = handler.length; for (var i = 0; i < handlerLen; i += 1) { recurseReturn.push(addHandler(eventName, handler[i], sender)); } return recurseReturn; } if (!eventName || typeof eventName !== 'string') throw new Error('eventName must be a non-empty string'); if (typeof handler !== 'function') throw new Error('handler must be a function'); if (!(sender instanceof Object)) throw new Error('sender must be an object'); // initialize the sender._evtHandlers if absent sender._evtHandlers = sender._evtHandlers || {}; if (!sender._evtHandlers[eventName] || !(sender._evtHandlers[eventName] instanceof Array)) { sender._evtHandlers[eventName] = []; } // if this is a a duplicate handler for this eventName, then exit with false attachedHandlersLen = sender._evtHandlers[eventName].length; for (var _i = 0; _i < attachedHandlersLen; _i++) { if (sender._evtHandlers[eventName][_i] === handler) { return false; } } // push this handler in the array of handlers for this eventName sender._evtHandlers[eventName].push(handler); return true; } /** * Fetched handler functions for an event * * @param {string} eventName The name of the event * @param {function} handler The handler function for the event */ function getHanlders(eventName, sender) { if (typeof eventName !== 'string') throw new Error('eventName must be a non-empty string'); if (!(sender instanceof Object)) throw new Error('sender must be an object'); return sender._evtHandlers && sender._evtHandlers[eventName] || []; } /** * Removes handler functions from an event * * @param {string} eventName The name of the event * @param {function} handler The handler function for the event * @param {object} sender The object on which the event occured */ function removeHandler(eventName, handler, sender) { var attachedHandlers, attachedHandlersLen; // in case handler is sent as array, we recursively process it if (handler instanceof Array) { var recurseReturn = [], handlerLen = handler.length; for (var i = 0; i < handlerLen; i += 1) { recurseReturn.push(removeHandler(eventName, handler[i], sender)); } return recurseReturn; } if (!eventName || typeof eventName !== 'string') throw new Error('eventName must be a non-empty string'); if (handler && typeof handler !== 'function') throw new Error('handler must be a function'); if (!(sender instanceof Object)) throw new Error('sender must be an object'); // get all the handlers for the event attachedHandlers = getHanlders(eventName, sender); // if event has no handlers, return if (!(attachedHandlers instanceof Array) || attachedHandlers.length === 0) { return; } // if handler is empty, remove all if (!handler) { delete sender._evtHandlers[eventName]; return true; } // else, loop through the handlers and remove the relevant one attachedHandlersLen = attachedHandlers.length; for (var _i2 = 0; _i2 < attachedHandlersLen; _i2++) { if (attachedHandlers[_i2] === handler) { attachedHandlers.splice(_i2, 1); } } return true; } function triggerEvent(eventName, sender, args) { var attachedHandlers, attachedHandlersLen, eventObj; if (!eventName || typeof eventName !== 'string') throw new Error('eventName must be a non-empty string'); if (!(sender instanceof Object)) throw new Error('sender must be an object'); attachedHandlers = getHanlders(eventName, sender); eventObj = { eventName: eventName, sender: sender, data: args }; // if event has no handlers, return if (!(attachedHandlers instanceof Array) || attachedHandlers.length === 0) { return; } // loop through the handlers and call each attachedHandlersLen = attachedHandlers.length; for (var i = 0; i < attachedHandlersLen; i++) { attachedHandlers[i](eventObj); } return true; } exports.addHandler = addHandler; exports.getHanlders = getHanlders; exports.removeHandler = removeHandler; exports.triggerEvent = triggerEvent; /***/ }), /* 320 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.pivot = exports.sort = exports.pipe = exports.groupBy = exports.select = exports.filter = exports.greaterEquals = exports.greater = exports.lessEquals = exports.less = exports.equals = exports.between = undefined; var _operators = __webpack_require__(321); exports.between = _operators.between; exports.equals = _operators.equals; exports.less = _operators.less; exports.lessEquals = _operators.lessEquals; exports.greater = _operators.greater; exports.greaterEquals = _operators.greaterEquals; exports.filter = _operators.filter; exports.select = _operators.select; exports.groupBy = _operators.groupBy; exports.pipe = _operators.pipe; exports.sort = _operators.sort; exports.pivot = _operators.pivot; /***/ }), /* 321 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.pivot = exports.sort = exports.pipe = exports.groupBy = exports.select = exports.filter = exports.greaterEquals = exports.indexColGreaterEquals = exports.greater = exports.indexColGreater = exports.lessEquals = exports.indexColLessEquals = exports.less = exports.indexColLess = exports.equals = exports.indexColEquals = exports.between = exports.indexColBetween = undefined; var _filterOperations = __webpack_require__(322); var _selectFilter = __webpack_require__(325); var _groupBy = __webpack_require__(326); var _groupBy2 = _interopRequireDefault(_groupBy); var _pipe = __webpack_require__(346); var _pipe2 = _interopRequireDefault(_pipe); var _sort = __webpack_require__(347); var _sort2 = _interopRequireDefault(_sort); var _pivot = __webpack_require__(348); var _pivot2 = _interopRequireDefault(_pivot); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.indexColBetween = _filterOperations.indexColBetween; exports.between = _filterOperations.between; exports.indexColEquals = _filterOperations.indexColEquals; exports.equals = _filterOperations.equals; exports.indexColLess = _filterOperations.indexColLess; exports.less = _filterOperations.less; exports.indexColLessEquals = _filterOperations.indexColLessEquals; exports.lessEquals = _filterOperations.lessEquals; exports.indexColGreater = _filterOperations.indexColGreater; exports.greater = _filterOperations.greater; exports.indexColGreaterEquals = _filterOperations.indexColGreaterEquals; exports.greaterEquals = _filterOperations.greaterEquals; exports.filter = _selectFilter.filter; exports.select = _selectFilter.select; exports.groupBy = _groupBy2['default']; exports.pipe = _pipe2['default']; exports.sort = _sort2['default']; exports.pivot = _pivot2['default']; /***/ }), /* 322 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.greaterEquals = exports.indexColGreaterEquals = exports.greater = exports.indexColGreater = exports.lessEquals = exports.indexColLessEquals = exports.less = exports.indexColLess = exports.equals = exports.indexColEquals = exports.between = exports.indexColBetween = undefined; var _sortedSearch = __webpack_require__(323); var _datatableUtils = __webpack_require__(276); var _typeEnums = __webpack_require__(324); var _comparators = __webpack_require__(278); /** * Get all rows between 2 values, this function assumes the column is already sorted * @param {number} columnIndex 0 based index of the column * @param {*} startVal start value * @param {*} endVal end value */ function indexColBetween(columnIndex, startVal, endVal, comparer) { var start = startVal, end = endVal; return { ops: 'indexColBetween', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(startLimit, endLimit) { start = startLimit; end = endLimit; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } // find the left most element which is exactly equal to or just greater than the start var loIndex = (0, _sortedSearch.leftMostExactOrGreater)(start, data, comparer, 0, data.length), // find the right most element which is exactly equal to or just less than the end hiIndex = (0, _sortedSearch.rightMostExactOrLesser)(end, data, comparer, loIndex, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(loIndex, hiIndex + 1); } }; } }; } /** * Get all rows between 2 values * @param {string} columnName - name of the column * @param {number} startVal - start value * @param {number} endVal - end value * @returns {array} - filtered data rows */ function between(columnName, startVal, endVal) { var start = startVal, end = endVal; return { ops: 'between', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(startLimit, endLimit) { start = startLimit; end = endLimit; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColBetween(columnIndex, start, end, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return comparer(row, start) >= 0 && comparer(row, end) <= 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get all rows where a column value is equal to a given value * @param {number} columnIndex index of the column * @param {*} val value to search with */ function indexColEquals(columnIndex, val, comparer) { var valToCheck = val; return { ops: 'indexColEquals', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } var loIndex = void 0, hiIndex = void 0; // find the left most element which is exactly equal to or just greater than the startVal loIndex = (0, _sortedSearch.leftMostExactOrGreater)(valToCheck, data, comparer, 0, data.length); // check if the match is an exact match otheriwse return blank array if (loIndex >= data.length || comparer(data[loIndex], valToCheck) !== 0) { return { data: [], schema: schema, config: config }; } // get the index of right most occurrence hiIndex = (0, _sortedSearch.rightMostExactOrLesser)(valToCheck, data, comparer, loIndex, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(loIndex, hiIndex + 1); } }; } }; } /** * Get all rows where a column value is equal to a given value * @param {string} columnName - name of the column * @param {number | string} val - value to filter with * @returns {array} - filtered data rows */ function equals(columnName, val) { var valToCheck = val; return { ops: 'equals', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColEquals(columnIndex, valToCheck, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return comparer(row, valToCheck) === 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get all rows where a column value is less than a given value * @param {number} columnIndex index of the column * @param {*} val value to check with */ function indexColLess(columnIndex, val, comparer) { var valToCheck = val; return { ops: 'indexColLess', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } // get the index of right most occurrence var pos = (0, _sortedSearch.leftMostExactOrGreater)(valToCheck, data, comparer, 0, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(0, pos); } }; } }; } /** * Get all rows less than a given value * @param {string} columnName - name of the column * @param {number} val - value to check * @returns {array} - filtered data rows */ function less(columnName, val) { var valToCheck = val; return { ops: 'less', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColLess(columnIndex, valToCheck, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return comparer(row, valToCheck) < 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get all rows where a column value is less than a given value * @param {number} columnIndex index of the column * @param {*} val value to check with */ function indexColLessEquals(columnIndex, val, comparer) { var valToCheck = val; return { ops: 'indexColLessEquals', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } // get the index of right most occurrence var pos = (0, _sortedSearch.rightMostExactOrLesser)(valToCheck, data, comparer, 0, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(0, pos + 1); } }; } }; } /** * Get all rows less than a given value * @param {string} columnName - name of the column * @param {number} val - value to check * @returns {array} - filtered data rows */ function lessEquals(columnName, val) { var valToCheck = val; return { ops: 'lessEquals', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColLessEquals(columnIndex, valToCheck, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return comparer(row, valToCheck) <= 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get all rows where a column value is greater than a given value * @param {number} columnIndex index of the column * @param {*} val value to check with */ function indexColGreater(columnIndex, val, comparer) { var valToCheck = val; return { ops: 'indexColGreater', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } // get the index of right most occurrence var pos = (0, _sortedSearch.rightMostExactOrLesser)(valToCheck, data, comparer, 0, data.length), nullPos = (0, _sortedSearch.leftMostExactOrGreater)(null, data, comparer, pos, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(pos + 1, nullPos); } }; } }; } /** * Get all rows greater than a given value * @param {string} columnName - name of the column * @param {number} val - value to check * @returns {array} - filtered data rows */ function greater(columnName, val) { var valToCheck = val; return { ops: 'greater', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColGreater(columnIndex, valToCheck, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return row[columnIndex] !== null && typeof row[columnIndex] !== 'undefined' && comparer(row, valToCheck) > 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get all rows where a column value is greater than a given value * @param {number} columnIndex index of the column * @param {*} val value to check with */ function indexColGreaterEquals(columnIndex, val, comparer) { var valToCheck = val; return { ops: 'indexColGreaterEquals', type: _typeEnums.OperatorTypes.IndexOpsFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!comparer) { comparer = _getIndexColComparer(schema, columnIndex); } // get the index of right most occurrence var pos = (0, _sortedSearch.leftMostExactOrGreater)(valToCheck, data, comparer, 0, data.length), nullPos = (0, _sortedSearch.leftMostExactOrGreater)(null, data, comparer, pos, data.length); return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.slice(pos, nullPos); } }; } }; } /** * Get all rows greater than a given value * @param {string} columnName - name of the column * @param {number} val - value to check * @returns {array} - filtered data rows */ function greaterEquals(columnName, val) { var valToCheck = val; return { ops: 'greaterEquals', type: _typeEnums.OperatorTypes.GenericFilter, _updateArgs: function _updateArgs(compareVal) { valToCheck = compareVal; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), comparer = void 0; if (columnIndex >= 0) { comparer = _getIndexColComparer(schema, columnIndex); if (config && config.indexBy === columnName) { var indexOps = indexColGreaterEquals(columnIndex, valToCheck, comparer); return indexOps.fn(data, schema, config); } else { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { return data.filter(function (row) { return row[columnIndex] !== null && typeof row[columnIndex] !== 'undefined' && comparer(row, valToCheck) >= 0; }); } }; } } else throw new Error('Column \'' + columnName + '\' is not found in the schema.'); } }; } /** * Get the compararer function for a particular column * @param {*} schema * @param {*} columnIndex */ var _getIndexColComparer = function _getIndexColComparer(schema, columnIndex) { switch (schema[columnIndex].type) { case 'interval': // for interval column we compare the value with the start value of interval return function (a, b) { return (0, _comparators.numberComparator)(a[columnIndex].start, b); }; case 'number': case 'date': return function (a, b) { return (0, _comparators.numberComparator)(a[columnIndex], b); }; default: return function (a, b) { return (0, _comparators.stringComparator)(String(a[columnIndex]).toLowerCase(), String(b).toLowerCase()); }; // case insensitive matching is performed here } }; exports.indexColBetween = indexColBetween; exports.between = between; exports.indexColEquals = indexColEquals; exports.equals = equals; exports.indexColLess = indexColLess; exports.less = less; exports.indexColLessEquals = indexColLessEquals; exports.lessEquals = lessEquals; exports.indexColGreater = indexColGreater; exports.greater = greater; exports.indexColGreaterEquals = indexColGreaterEquals; exports.greaterEquals = greaterEquals; /***/ }), /* 323 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * Find the left most element compared with a value * If multiple exact matches are found then returns the left most one or first occurrence * If no matches are found then returns the next greater element position of value * @param {*} val * @param {Array} arr * @param {*} comparer * @param {number} startPos * @param {number} endPos */ function leftMostExactOrGreater(val, arr, comparer, startPos, endPos) { var left = startPos, right = endPos; while (left < right) { var mid = left + Math.floor((right - left) / 2); if (comparer(arr[mid], val) < 0) { left = mid + 1; } else { right = mid; } } return left; } /** * Find the right most element compared with a value * If multiple exact matches are found then returns the right most one or last occurrence * If no matches are found then returns the last lesser element position of value * @param {*} val * @param {Array} arr * @param {*} comparer * @param {number} startPos * @param {number} endPos */ function rightMostExactOrLesser(val, arr, comparer, startPos, endPos) { var left = startPos, right = endPos; while (left < right) { var mid = left + Math.floor((right - left) / 2); if (comparer(arr[mid], val) > 0) { right = mid; } else { left = mid + 1; } } return left - 1; } exports.leftMostExactOrGreater = leftMostExactOrGreater; exports.rightMostExactOrLesser = rightMostExactOrLesser; /***/ }), /* 324 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var OperatorTypes = exports.OperatorTypes = { 'IndexOpsFilter': 0, 'GenericFilter': 1, 'GroupBy': 2, 'Sort': 3, 'Select': 4 }; /***/ }), /* 325 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.filter = exports.select = undefined; var _typeEnums = __webpack_require__(324); /** * Select a number of columns from the data table * @param {string[]} columnNames - array of column names */ function select(columnNames, options) { // If user provides only one column as argument, instead of an array of argument // Then make it a singe element array columnNames = columnNames && columnNames.constructor !== Array ? [columnNames] : columnNames; return { ops: 'select', type: _typeEnums.OperatorTypes.Select, fn: function fn(data, schema, config, generatorFn) { // let newSchema = columnNames ? schema.filter(element => columnNames.includes(element.name)) : schema; var newSchema = [], selectedColIndices = []; if (columnNames) { var i = void 0; options = options || { exclude: false }; for (i = 0; i < schema.length; i++) { if (options.exclude && !columnNames.includes(schema[i].name) || !options.exclude && columnNames.includes(schema[i].name)) { newSchema.push(schema[i]); selectedColIndices.push(i); } } } else { newSchema = schema; } return { data: data, schema: newSchema, config: config, generatorFn: function generatorFn() { var selectedColLen = selectedColIndices.length; if (selectedColLen > 0) { var returnData = [], _i = void 0, j = void 0, row = void 0; for (_i = 0; _i < data.length; _i++) { row = []; for (j = 0; j < selectedColLen; j++) { row[j] = data[_i][selectedColIndices[j]]; } returnData[_i] = row; } return returnData; } else { return data.slice(0); } } }; } }; } function filter(_fn) { var _this = this; return { ops: 'filter', type: _typeEnums.OperatorTypes.GenericFilter, fn: function fn(data, schema, config, _generatorFn) { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { if (_generatorFn) { data = _generatorFn.call(); } // create the columns object which is basically a mapping between column name and index // as user will provide the filter fn as = (row, columns) => row[columns.Name] === 'val' var columns = {}; for (var i = 0; i < schema.length; i++) { columns[schema[i].name] = i; } return data.filter(function (row) { return _fn.call(_this, row, columns); }); } }; } }; } exports.select = select; exports.filter = filter; /***/ }), /* 326 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports._singleSortedAddRowDate = exports._singleSortedAddRow = undefined; var _datatableUtils = __webpack_require__(276); var _datetimeOps = __webpack_require__(327); var _duration = __webpack_require__(342); var _interval = __webpack_require__(343); var _aggregators = __webpack_require__(344); var _aggregators2 = _interopRequireDefault(_aggregators); __webpack_require__(345); var _globalConfig = __webpack_require__(280); var _typeEnums = __webpack_require__(324); var _sortedSearch = __webpack_require__(323); var _comparators = __webpack_require__(278); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Performs group by operation on current data table. * * @param {array} groupConfigArr - The group configuration array * @param {array} aggrConfigArr - The aggregation configuration array * @returns {array} - grouped data rows */ function groupBy(groupConfigArr, aggrConfigArr) { var groupConfigArray = groupConfigArr, aggrConfigArray = aggrConfigArr; return { ops: 'groupBy', type: _typeEnums.OperatorTypes.GroupBy, _updateArgs: function _updateArgs(groupConfiguration, aggrConfiguration) { groupConfigArray = groupConfiguration; aggrConfigArray = aggrConfiguration; }, fn: function fn(data, schema, config, generatorFn) { if (generatorFn) { data = generatorFn.call(); } if (!groupConfigArray || groupConfigArray.length === 0) throw new Error('groupConfigArray cannot be empty'); if (!aggrConfigArray || aggrConfigArray.length === 0) throw new Error('aggrConfigArray cannot be empty'); if (!(groupConfigArray instanceof Array) && groupConfigArray instanceof Object) { groupConfigArray = [groupConfigArray]; } if (!(aggrConfigArray instanceof Array) && aggrConfigArray instanceof Object) { aggrConfigArray = [aggrConfigArray]; } if (groupConfigArray.length === 1 && config && groupConfigArray[0].column === config.indexBy) { // if single and indexBy column return _singleSortedGroupBy(data, schema, config, groupConfigArray[0], aggrConfigArray); } else { // OR, unsorted single/multiple columns return _genericGroupBy(data, schema, config, groupConfigArray, aggrConfigArray); } } }; } /** * Takes both the group config and aggregation config arrays, * and creates and returns a schema from the two. * * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array */ function _createAggrSchema(schema, groupConfig, aggrConfig, cacheColumnConfig) { var newSchema = [], groupConfigLength = groupConfig.length, aggrConfigLength = aggrConfig.length, column, type, aggregatorFn, i, operation, newColumn; groupConfig = groupConfig instanceof Array ? groupConfig : [groupConfig]; aggrConfig = aggrConfig instanceof Array ? aggrConfig : [aggrConfig]; // add the group columns in new schema for (i = 0; i < groupConfigLength; i++) { column = cacheColumnConfig(groupConfig[i].column, schema); // update the schema newColumn = { name: groupConfig[i].outputAs || groupConfig[i].column, type: column.type === 'date' ? 'interval' : column.type }; if (column.enableUTC !== undefined) { newColumn.enableUTC = column.enableUTC; } newSchema.push(newColumn); } for (i = 0; i < aggrConfigLength; i++) { // default operation is avg operation = aggrConfig[i].operation || 'avg'; column = cacheColumnConfig(aggrConfig[i].column, schema); aggregatorFn = _aggregators2['default'].resolve(operation); if (!aggregatorFn) throw new Error(operation + ' is not a defined operation'); // if operation is first or last then inherit from schema's column // if it's count, type will be number // rest are all numeric operations // however, if the column type is not numeric, throw an error switch (operation) { case 'first': case 'last': type = column.type; break; case 'count': type = 'number'; break; default: if (column.type !== 'number') throw new Error(operation + ' can apply only on numbers'); type = 'number'; } // update the schema newSchema.push({ name: aggrConfig[i].outputAs || aggrConfig[i].column + (operation ? ' - ' + operation : ''), type: type }); } return newSchema; } /** * Performs group by on a single column. * * @param {array} data The datatable being operated on * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array */ function _singleSortedGroupBy(data, schema, config, groupConfig, aggrConfig) { var newData = [], newSchema = [], dataLength = data.length, column, maxDate, timeDuration, startValFloorVal, startPos = 0, lastEntry, cacheColumnConfig = _cacheColumnConfig(), cacheGroupCount = [], newDataLength, enableUTC, i; column = cacheColumnConfig(groupConfig.column, schema); column.outputAs = groupConfig.outputAs; // prepare the schema newSchema = _createAggrSchema(schema, [column], aggrConfig, cacheColumnConfig); if (dataLength > 0) { enableUTC = column.enableUTC || (0, _globalConfig.getConfig)('enableUTC'); // if it's a date column, // create a duration object // if startValue is present/number, else use first row's datetime // get the start value of the dataset if (column.type === 'date') { var peaks = void 0, minDate = void 0, startValue = void 0; timeDuration = (0, _duration.duration)(groupConfig.timeUnit, Math.abs(groupConfig.binSize) || 1); if (!data[0] || !data[0][column.index] || !data[dataLength - 1] || !data[dataLength - 1][column.index]) { peaks = (0, _datatableUtils.columnExtents)(groupConfig.column, data, schema, config.indexBy); } minDate = data[0] && data[0][column.index] || peaks.min; startValue = groupConfig.startValue && parseInt(groupConfig.startValue, 10); if (startValue) { if (startValue >= minDate) { var comparer = function comparer(a, b) { return (0, _comparators.numberComparator)(a[column.index], b); }; // if start value falls on or after the minimum date in dataset, then floor it to unit with binning 1 startValFloorVal = (0, _datetimeOps.getDateStart)(startValue, (0, _duration.duration)(groupConfig.timeUnit, 1), enableUTC, groupConfig.weekStartFrom); // get the index of left most occurrence startPos = (0, _sortedSearch.leftMostExactOrGreater)(startValFloorVal, data, comparer, 0, data.length); } else { // if start value falls before the minimum date in dataset, then floor the minimum to date unit with binning binSize startValFloorVal = (0, _datetimeOps.getDateStart)(minDate, timeDuration, enableUTC, groupConfig.weekStartFrom, startValue); } } else { // if start value absent, then floor the minimum to date unit with binning 1 startValFloorVal = (0, _datetimeOps.getDateStart)(minDate, (0, _duration.duration)(groupConfig.timeUnit, 1), enableUTC, groupConfig.weekStartFrom); } maxDate = data[dataLength - 1] && data[dataLength - 1][column.index] || peaks.max; } // if start value is less than maxdate only then proceed if (startValFloorVal === undefined || startValFloorVal <= maxDate) { var intervalConfig = { duration: timeDuration, outputFormat: groupConfig.outputFormat, enableUTC: enableUTC, weekStartFrom: groupConfig.weekStartFrom }; if (startValFloorVal !== undefined) { // if no entry in new data array, create new interval entry, // add it to new data array and return it lastEntry = [(0, _interval.interval)(startValFloorVal, intervalConfig)]; newData.push(lastEntry); } for (i = startPos; i < dataLength; i++) { if (data[i].length > 0) { // date field // OR, string field OR, number field with binning 1 if (column.type === 'date') { lastEntry = _singleSortedAddRowDate(newData, lastEntry, data[i][column.index], intervalConfig, startValFloorVal); } else if (column.type === 'string' || column.type === 'number') { lastEntry = _singleSortedAddRow(newData, lastEntry, data[i][column.index]); } newDataLength = newData.length - 1; // init the cacheGroupCount current row with an empty object before aggregation cacheGroupCount[newDataLength] = cacheGroupCount[newDataLength] || {}; lastEntry && _applyAggr(data[i], schema, lastEntry, 1, aggrConfig, cacheColumnConfig, cacheGroupCount[newDataLength]); } } } } return { data: newData, schema: newSchema, config: { indexBy: groupConfig.column } }; } /** * Performs row addition when group by is on single sorted non-date data. * * @param {array} newData The new data array after group by * @param {array} lastEntry The last entry in the new data array * @param {any} value String or number, the data value */ function _singleSortedAddRow(newData, lastEntry, value) { // if no entry in new data array OR, the current value doesn't fit in the last entry, // make a new entry in the new data array and return it if (!lastEntry || value !== lastEntry[0]) { lastEntry = [value]; newData.push(lastEntry); } return lastEntry; } /** * Performs row addition when group by is on single sorted date data. * * @param {array} newData The new data array after group by * @param {array} lastEntry The last entry in the new data array * @param {number} start The start datetime of the interval * @param {object} intervalConfig The configuration object used by interval * @param {number} minStart The starting datetime of the dataset grouping */ function _singleSortedAddRowDate(newData, lastEntry, start, intervalConfig, minStart) { // if current date is greater than or equal to last interval's end // then create a new interval entry starting from the previous interval's end, // add it to the new data array, and repeat if (start >= lastEntry[0].end) { var startValFloorVal = void 0; switch (intervalConfig.duration.Unit) { case 'Month': case 'Quarter': case 'Year': startValFloorVal = (0, _datetimeOps.getDateStart)(start, intervalConfig.duration, intervalConfig.enableUTC, intervalConfig.weekStartFrom, minStart); break; default: startValFloorVal = start - (start - minStart) % intervalConfig.duration.ms; break; } lastEntry = [(0, _interval.interval)(startValFloorVal, intervalConfig)]; newData.push(lastEntry); } return lastEntry; } /** * Caches the column's index in the original data schema. */ function _cacheColumnConfig() { var cache = {}; return function (columnName, schema, data) { if (!cache[columnName]) { var columnIndex = (0, _datatableUtils.columnIndexOf)(columnName, schema), column = schema[columnIndex]; if (column === undefined) throw new Error('incorrect column name in config - ' + columnName); cache[columnName] = column; cache[columnName].column = columnName; cache[columnName].index = columnIndex; if (column.type === 'date' && data) { cache[columnName].peaks = (0, _datatableUtils.columnExtents)(columnName, data, schema); } } return cache[columnName]; }; } /** * Performs group by on unsorted/multiple column data. * * @param {array} data The datatable being operated on * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array */ function _genericGroupBy(data, schema, config, groupConfig, aggrConfig) { var newData = [], newSchema = [], groupConfigCopy = [], loopData = true, dataLength = data.length, groupConfigLength = groupConfig.length, column, startValFloorVal, dateColumns = {}, cacheGroupCount = [], cacheColumnConfig = _cacheColumnConfig(), hashTable = {}, hashCount = 0, i; // prepare the schema // loop through the group config for (i = 0; i < groupConfigLength; i++) { // get column details column = cacheColumnConfig(groupConfig[i].column, schema, data); column.outputAs = groupConfig[i].outputAs; // if date, store in separate array // else, add to row // in both cases create the hash value if (column.type === 'date') { if (!dateColumns[i]) { // if group config start value exceeds max of column, then prepare for exiting data processing if (groupConfig[i].startValue >= column.peaks.max) { loopData = false; } dateColumns[i] = Object.assign({}, column); dateColumns[i].intervalConfig = { duration: (0, _duration.duration)(groupConfig[i].timeUnit, Math.abs(groupConfig[i].binSize) || 1), outputFormat: groupConfig[i].outputFormat, enableUTC: column.enableUTC || (0, _globalConfig.getConfig)('enableUTC'), weekStartFrom: groupConfig[i].weekStartFrom }; startValFloorVal = parseInt(groupConfig[i].startValue, 10) || column.peaks.min; dateColumns[i].startValFloorVal = startValFloorVal && (0, _datetimeOps.getDateStart)(startValFloorVal, (0, _duration.duration)(groupConfig[i].timeUnit, 1), dateColumns[i].intervalConfig.enableUTC, dateColumns[i].intervalConfig.weekStartFrom, parseInt(groupConfig[i].startValue, 10)); dateColumns[i].max = column.peaks.max; } } groupConfigCopy[i] = column; } newSchema = _createAggrSchema(schema, groupConfigCopy, aggrConfig, cacheColumnConfig); // loop through the data if (loopData && dataLength > 0) { for (i = 0; i < dataLength; i++) { hashCount = _genericGroupByProcessRow(data[i], schema, groupConfig, aggrConfig, cacheColumnConfig, dateColumns, hashTable, hashCount, newData, cacheGroupCount); } } return { data: newData, schema: newSchema, config: { indexBy: config.indexBy } }; } /** * Processes a data row and makes an entry/aggregation in the grouped data. * * @param {array} dataRow The datatable row being operated on * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array * @param {function} cacheColumnConfig The cache storage for column configs * @param {object} dateColumns Stores column configs of all date columns * @param {object} hashTable Stores the hasvalues for data rows * @param {number} hashCount The current hashcount in the hashtable * @param {array} newData The new data array after group by * @param {array} cacheGroupCount */ function _genericGroupByProcessRow(dataRow, schema, groupConfig, aggrConfig, cacheColumnConfig, dateColumns, hashTable, hashCount, newData, cacheGroupCount) { var j = void 0, column = void 0, hashVal = '', currentRow = [], cacheGroupCountIndex = void 0, intervalObj = void 0, groupConfigLength = groupConfig.length; if (dataRow.length > 0) { // loop through the group config for (j = 0; j < groupConfigLength; j++) { // get column details column = cacheColumnConfig(groupConfig[j].column, schema); // if date, store the startValue // else, add to row // in both cases create the hash value if (column.type === 'date') { // if date is less than start value then exclude the row if (dateColumns[j].startValFloorVal > dataRow[column.index]) { return hashCount; } // always calculate the rounded date given the start of the column data and binsize switch (groupConfig[j].timeUnit.name) { case 'Month': case 'Quarter': case 'Year': dateColumns[j].value = (0, _datetimeOps.getDateStart)(dataRow[column.index], dateColumns[j].intervalConfig.duration, dateColumns[j].intervalConfig.enableUTC, dateColumns[j].intervalConfig.weekStartFrom, dateColumns[j].startValFloorVal); break; default: dateColumns[j].value = dataRow[column.index] - (dataRow[column.index] - dateColumns[j].startValFloorVal) % dateColumns[j].intervalConfig.duration.ms; break; } hashVal += dateColumns[j].value + '-'; } else { currentRow[j] = dataRow[column.index]; hashVal += dataRow[column.index] + '-'; } } // remove the last '-' hashVal = hashVal.slice(0, -1); // search hash value in hash table if (hashTable[hashVal] >= 0) { // get the row from the grouped data array currentRow = newData[hashTable[hashVal]]; cacheGroupCountIndex = hashTable[hashVal]; } else { // make entry in hash table array hashTable[hashVal] = hashCount++; // if date storage array present, loop through it for (var key in dateColumns) { // create interval using derived start date, and other datetime info // add interval to grouped data array in the relevant index intervalObj = (0, _interval.interval)(dateColumns[key].value, dateColumns[key].intervalConfig); currentRow[key] = intervalObj; } newData.push(currentRow); cacheGroupCountIndex = newData.length - 1; } // init the cacheGroupCount current row with an empty object before aggregation cacheGroupCount[cacheGroupCountIndex] = cacheGroupCount[cacheGroupCountIndex] || {}; // apply aggregation to this row currentRow && _applyAggr(dataRow, schema, currentRow, groupConfigLength, aggrConfig, cacheColumnConfig, cacheGroupCount[cacheGroupCountIndex]); return hashCount; } } /** * Perform aggregation operation on given aggregation configuration and a data row. * * @param {array} dataRow The datatable row being operated on * @param {array} schema The schema * @param {array} lastEntry The last entry in the new data array * @param {number} entryIndex The entry index for the aggregated columns in the row, after the group columns * @param {array} aggrConfig The aggregation configuration array * @param {function} cacheColumnIndex The reference to the caching function for column indices * @param {object} cacheGroupCountRow The current row in the cache group count column */ function _applyAggr(dataRow, schema, lastEntry, entryIndex, aggrConfig, cacheColumnConfig, cacheGroupCountRow) { var aggrConfigLength = aggrConfig.length, column = void 0, operation = void 0, count = void 0, i = void 0; for (i = 0; i < aggrConfigLength; i++) { column = cacheColumnConfig(aggrConfig[i].column, schema); if (dataRow[column.index] !== undefined && dataRow[column.index] !== null) { operation = aggrConfig[i].operation || 'avg'; // for the below operations, calculate and store the current count of the column values in the group, in the cacheGroupCount and count switch (operation) { case 'sum': case 'min': case 'max': case 'first': case 'last': count = null; break; default: count = cacheGroupCountRow[i] = cacheGroupCountRow[i] && cacheGroupCountRow[i] + 1 || 1; break; } // for operation other than count, calculate the aggregated value and add to the last entered row lastEntry[entryIndex + i] = operation === 'count' ? count : _aggregators2['default'].resolve(operation)(lastEntry[entryIndex + i] !== undefined ? lastEntry[entryIndex + i] : null, dataRow[column.index], count); } } } exports['default'] = groupBy; exports._singleSortedAddRow = _singleSortedAddRow; exports._singleSortedAddRowDate = _singleSortedAddRowDate; /***/ }), /* 327 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.getDateOffset = exports.getDateStart = exports.dateRangeCaclulator = exports.dateIntervalToString = exports.getDefaultOutputFormat = undefined; var _timeIntervals = __webpack_require__(328); var timeIntervals = _interopRequireWildcard(_timeIntervals); var _utc = __webpack_require__(336); var timeIntervalsUTC = _interopRequireWildcard(_utc); var _datetimeEnums = __webpack_require__(341); var _timeConverter = __webpack_require__(281); var _timeConverter2 = _interopRequireDefault(_timeConverter); 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 unitDefaultFormats = { 'Year': '%Y', // 2018 'Month': '%b %Y', // Jan 2018 'Day': '%b %d, %Y', // Jan 01, 2018 'Hour': '%b %d, %Y %H hrs', // Jan 01, 2018 23 hrs 'Minute': '%b %d, %Y %H:%M', // Jan 01, 2018 23:34 'Second': '%b %d, %Y %H:%M:%S', // Jan 01, 2018 23:34:26 'Millisecond': '%b %d, %Y %H:%M:%S:%L' // Jan 01, 2018 23:34:26:123 }, timeIntervalMapping = { 'Millisecond': timeIntervals.timeMillisecond, 'Second': timeIntervals.timeSecond, 'Minute': timeIntervals.timeMinute, 'Hour': timeIntervals.timeHour, 'Day': timeIntervals.timeDay, 'Week': { 0: timeIntervals.timeSunday, 1: timeIntervals.timeMonday, 2: timeIntervals.timeTuesday, 3: timeIntervals.timeWednesday, 4: timeIntervals.timeThursday, 5: timeIntervals.timeFriday, 6: timeIntervals.timeSaturday }, 'Month': timeIntervals.timeMonth, 'Quarter': timeIntervals.timeQuarter, 'Year': timeIntervals.timeYear }, UTCTimeIntervalMapping = { 'Millisecond': timeIntervalsUTC.utcMillisecond, 'Second': timeIntervalsUTC.utcSecond, 'Minute': timeIntervalsUTC.utcMinute, 'Hour': timeIntervalsUTC.utcHour, 'Day': timeIntervalsUTC.utcDay, 'Week': { 0: timeIntervalsUTC.utcSunday, 1: timeIntervalsUTC.utcMonday, 2: timeIntervalsUTC.utcTuesday, 3: timeIntervalsUTC.utcWednesday, 4: timeIntervalsUTC.utcThursday, 5: timeIntervalsUTC.utcFriday, 6: timeIntervalsUTC.utcSaturday }, 'Month': timeIntervalsUTC.utcMonth, 'Quarter': timeIntervalsUTC.utcQuarter, 'Year': timeIntervalsUTC.utcYear }; /** * Returns the default output format for a datetime unit. * @param {string} Unit The datetime unit */ function getDefaultOutputFormat(Unit) { switch (Unit) { case 'Millisecond': case 'Second': case 'Minute': case 'Hour': case 'Day': case 'Month': case 'Year': return unitDefaultFormats[Unit]; case 'Week': return unitDefaultFormats.Day; // Day case 'Quarter': return unitDefaultFormats.Month; // Month } } /** * Returns the string output of datetime interval. */ function dateIntervalToString() { var specifier, config = this.config; specifier = (config.enableUTC !== undefined ? config.enableUTC : false) ? _timeConverter2['default'].utcFormatter(config.outputFormat) : _timeConverter2['default'].formatter(config.outputFormat); switch (config.duration.Unit) { case 'Millisecond': case 'Second': case 'Minute': case 'Hour': case 'Day': case 'Month': case 'Year': return specifier.format(new Date(this.start)) + (config.duration.number > 1 ? ' - ' + specifier.format(new Date(this.end - 1)) : ''); case 'Week': case 'Quarter': return specifier.format(new Date(this.start)) + ' - ' + specifier.format(new Date(this.end - 1)); } } /** * Returns the start and end timestamps, provided a start date and duration information. * * @param {number} start The given start date's timestamp * @param {object} duration The duration object defining the duration * @param {boolean} enableUTC The setting to enable/disable UTC * @param {object} weekStartFrom The weekday which will be considered as start of a week */ function dateRangeCaclulator(start, duration, enableUTC, weekStartFrom) { var calculateStart = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var startDate, endDate, durationCopy; startDate = start; if (calculateStart) { durationCopy = Object.assign({}, duration); durationCopy.number = 1; startDate = getDateStart(startDate, durationCopy, enableUTC, weekStartFrom); } endDate = getDateOffset(startDate, duration.Unit, duration.number, enableUTC, weekStartFrom); return { startDate: startDate, endDate: endDate }; } /** * Get the floor value of the given date given the time unit. * * @param {number} date The date for which to get the start date * @param {object} duration The duration object * @param {boolean} enableUTC The setting to enable/disable UTC * @param {object} weekStartFrom The weekday which will be considered as start of a week * @param {number} start The start date wrt which, the provided date's binning start date will be calculated */ function getDateStart(date, duration, enableUTC, weekStartFrom, start) { var timeIntervalObj = (enableUTC !== undefined ? enableUTC : false) ? UTCTimeIntervalMapping[duration.Unit] : timeIntervalMapping[duration.Unit]; if (weekStartFrom && !_datetimeEnums.Weekdays[weekStartFrom.name]) throw new Error('Invalid weekStartFrom provided: ' + weekStartFrom); // for single/no binning, simply floor the provided date // for binnig of more than 1, // if start value is not provided, use logical binning level // else, // get the count from the start to the provided date, // find number by which date exceeds binning // floor the date to single logical binning, and get previous using above number as offset if (duration.number === 1) { if (duration.Unit === 'Week') { weekStartFrom = weekStartFrom || _datetimeEnums.Weekdays.Sunday; return +timeIntervalObj[weekStartFrom.id].floor(new Date(date)); } return +timeIntervalObj.floor(new Date(date)); } else if (!start) { if (duration.Unit === 'Week') { weekStartFrom = weekStartFrom || _datetimeEnums.Weekdays.Sunday; return +timeIntervalObj[weekStartFrom.id].every(duration.number).floor(new Date(date)); } return +timeIntervalObj.every(duration.number).floor(new Date(date)); } else { var count = void 0, extraUnit = void 0; if (duration.Unit === 'Week') { weekStartFrom = weekStartFrom || _datetimeEnums.Weekdays.Sunday; count = timeIntervalObj[weekStartFrom.id].count(start, date); extraUnit = count % duration.number; if (extraUnit) { return getDateOffset(+timeIntervalObj[weekStartFrom.id].floor(date), duration.Unit, -extraUnit, enableUTC, weekStartFrom); } else { return +timeIntervalObj[weekStartFrom.id].floor(date); } } count = timeIntervalObj.count(start, date); extraUnit = count % duration.number; if (extraUnit) { return getDateOffset(+timeIntervalObj.floor(date), duration.Unit, -extraUnit, enableUTC, weekStartFrom); } else { return +timeIntervalObj.floor(date); } } } /** * Get the offset value of the given date given the time unit and the step count. * * @param {number} date The date for which to get the start date * @param {string} unit The datetime unit string * @param {number} offset The offset integer, postive or negative * @param {boolean} enableUTC The setting to enable/disable UTC * @param {object} weekStartFrom The weekday which will be considered as start of a week */ function getDateOffset(date, unit, offset, enableUTC, weekStartFrom) { // Calculate only for month, quarter and year which involves the uninform time unit 'month' // for rest, just add the miliseconds of the unit multiplied by offset times to the provided date switch (unit) { case 'Month': case 'Quarter': case 'Year': var timeIntervalObj = (enableUTC !== undefined ? enableUTC : false) ? UTCTimeIntervalMapping[unit] : timeIntervalMapping[unit]; return +timeIntervalObj.offset(new Date(date), offset); default: return date + _datetimeEnums.DatetimeUnits[unit].ms * offset; } } exports.getDefaultOutputFormat = getDefaultOutputFormat; exports.dateIntervalToString = dateIntervalToString; exports.dateRangeCaclulator = dateRangeCaclulator; exports.getDateStart = getDateStart; exports.getDateOffset = getDateOffset; /***/ }), /* 328 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.timeYear = exports.timeMonth = exports.timeQuarter = exports.timeSaturday = exports.timeFriday = exports.timeThursday = exports.timeWednesday = exports.timeTuesday = exports.timeMonday = exports.timeSunday = exports.timeWeek = exports.timeDay = exports.timeHour = exports.timeMinute = exports.timeSecond = exports.timeMillisecond = undefined; var _millisecond = __webpack_require__(329); var _millisecond2 = _interopRequireDefault(_millisecond); var _second = __webpack_require__(331); var _second2 = _interopRequireDefault(_second); var _minute = __webpack_require__(332); var _minute2 = _interopRequireDefault(_minute); var _hour = __webpack_require__(333); var _hour2 = _interopRequireDefault(_hour); var _day = __webpack_require__(285); var _day2 = _interopRequireDefault(_day); var _week = __webpack_require__(290); var _week2 = _interopRequireDefault(_week); var _quarter = __webpack_require__(334); var _quarter2 = _interopRequireDefault(_quarter); var _month = __webpack_require__(335); var _month2 = _interopRequireDefault(_month); var _year = __webpack_require__(291); var _year2 = _interopRequireDefault(_year); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.timeMillisecond = _millisecond2['default']; exports.timeSecond = _second2['default']; exports.timeMinute = _minute2['default']; exports.timeHour = _hour2['default']; exports.timeDay = _day2['default']; exports.timeWeek = _week2['default']; exports.timeSunday = _week.sunday; exports.timeMonday = _week.monday; exports.timeTuesday = _week.tuesday; exports.timeWednesday = _week.wednesday; exports.timeThursday = _week.thursday; exports.timeFriday = _week.friday; exports.timeSaturday = _week.saturday; exports.timeQuarter = _quarter2['default']; exports.timeMonth = _month2['default']; exports.timeYear = _year2['default']; /***/ }), /* 329 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeIntervalMs = __webpack_require__(330); var _timeIntervalMs2 = _interopRequireDefault(_timeIntervalMs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var millisecond = new _timeIntervalMs2['default']('millisecond', function () {/* no-op */}, function (d, s) { return d.setTime(Number(d) + Number(s)); }, function (s, e) { return e - s; }); exports['default'] = millisecond; /***/ }), /* 330 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var MillisecondInterval = function (_TimeInterval) { _inherits(MillisecondInterval, _TimeInterval); function MillisecondInterval() { _classCallCheck(this, MillisecondInterval); return _possibleConstructorReturn(this, _TimeInterval.apply(this, arguments)); } // Optimized implementation in case of a millisecond time interval MillisecondInterval.prototype.every = function every(step) { var stepi = Math.floor(step); if (!this.count || !Number.isFinite(stepi) || !(stepi > 0)) { return null; } if (!(stepi > 1)) { return this; } return new _timeInterval2['default']('millisecond', function (d) { return d.setTime(Math.floor(d / stepi) * stepi); }, function (d, s) { return d.setTime(Number(d) + s * stepi); }, function (s, e) { return (e - s) / stepi; }); }; return MillisecondInterval; }(_timeInterval2['default']); exports['default'] = MillisecondInterval; /***/ }), /* 331 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var second = new _timeInterval2['default']('second', function (d) { return d.setTime(Math.floor(d / _durations.durationSecond) * _durations.durationSecond); }, function (d, s) { return d.setTime(Number(d) + s * _durations.durationSecond); }, function (s, e) { return (e - s) / _durations.durationSecond; }, function (d) { return d.getUTCSeconds(); }); exports['default'] = second; /***/ }), /* 332 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var minute = new _timeInterval2['default']('minute', function (d) { return d.setTime(Math.floor(d / _durations.durationMinute) * _durations.durationMinute); }, function (d, s) { return d.setTime(Number(d) + s * _durations.durationMinute); }, function (s, e) { return (e - s) / _durations.durationMinute; }, function (d) { return d.getMinutes(); }); exports['default'] = minute; /***/ }), /* 333 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var hour = new _timeInterval2['default']('hour', function (d) { var offset = d.getTimezoneOffset() * _durations.durationMinute % _durations.durationHour; if (offset < 0) offset += _durations.durationHour; d.setTime(Math.floor((Number(d) - offset) / _durations.durationHour) * _durations.durationHour + offset); }, function (d, s) { return d.setTime(Number(d) + s * _durations.durationHour); }, function (s, e) { return (e - s) / _durations.durationHour; }, function (d) { return d.getHours(); }); exports['default'] = hour; /***/ }), /* 334 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var quarter = new _timeInterval2['default']('quarter', function (d) { d.setMonth(d.getMonth() - (d.getMonth() + 3) % 3, 1); d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setMonth(d.getMonth() + s * 3); }, function (s, e) { return (e.getMonth() - (e.getMonth() + 3) % 3 - (s.getMonth() - (s.getMonth() + 3) % 3)) / 3 + (e.getFullYear() - s.getFullYear()) * 4; }, function (d) { return Math.floor(d.getMonth() / 3); } // works incorrectly with every ); exports['default'] = quarter; /***/ }), /* 335 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var month = new _timeInterval2['default']('month', function (d) { d.setDate(1); d.setHours(0, 0, 0, 0); }, function (d, s) { return d.setMonth(d.getMonth() + s); }, function (s, e) { return e.getMonth() - s.getMonth() + (e.getFullYear() - s.getFullYear()) * 12; }, function (d) { return d.getMonth(); }); exports['default'] = month; /***/ }), /* 336 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.utcYear = exports.utcMonth = exports.utcQuarter = exports.utcSaturday = exports.utcFriday = exports.utcThursday = exports.utcWednesday = exports.utcTuesday = exports.utcMonday = exports.utcSunday = exports.utcWeek = exports.utcDay = exports.utcHour = exports.utcMinute = exports.utcSecond = exports.utcMillisecond = undefined; var _millisecond = __webpack_require__(329); var _millisecond2 = _interopRequireDefault(_millisecond); var _second = __webpack_require__(331); var _second2 = _interopRequireDefault(_second); var _minute = __webpack_require__(337); var _minute2 = _interopRequireDefault(_minute); var _hour = __webpack_require__(338); var _hour2 = _interopRequireDefault(_hour); var _day = __webpack_require__(288); var _day2 = _interopRequireDefault(_day); var _week = __webpack_require__(289); var _week2 = _interopRequireDefault(_week); var _quarter = __webpack_require__(339); var _quarter2 = _interopRequireDefault(_quarter); var _month = __webpack_require__(340); var _month2 = _interopRequireDefault(_month); var _year = __webpack_require__(293); var _year2 = _interopRequireDefault(_year); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.utcMillisecond = _millisecond2['default']; exports.utcSecond = _second2['default']; exports.utcMinute = _minute2['default']; exports.utcHour = _hour2['default']; exports.utcDay = _day2['default']; exports.utcWeek = _week2['default']; exports.utcSunday = _week.utcSunday; exports.utcMonday = _week.utcMonday; exports.utcTuesday = _week.utcTuesday; exports.utcWednesday = _week.utcWednesday; exports.utcThursday = _week.utcThursday; exports.utcFriday = _week.utcFriday; exports.utcSaturday = _week.utcSaturday; exports.utcQuarter = _quarter2['default']; exports.utcMonth = _month2['default']; exports.utcYear = _year2['default']; exports['default'] = { getInterval: function getInterval(intervalName) { switch (intervalName + '') { case 'millisecond': return _millisecond2['default']; case 'second': return _second2['default']; case 'minute': return _minute2['default']; case 'hour': return _hour2['default']; case 'day': return _day2['default']; case 'week': return _week2['default']; case 'sunday': return _week.utcSunday; case 'monday': return _week.utcMonday; case 'tuesday': return _week.utcTuesday; case 'wednesday': return _week.utcWednesday; case 'thursday': return _week.utcThursday; case 'friday': return _week.utcFriday; case 'saturday': return _week.utcSaturday; case 'quarter': return _quarter2['default']; case 'month': return _month2['default']; case 'year': return _year2['default']; } } }; /***/ }), /* 337 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcMinute = new _timeInterval2['default']('minute', function (d) { return d.setUTCSeconds(0, 0); }, function (d, s) { return d.setTime(Number(d) + s * _durations.durationMinute); }, function (s, e) { return (e - s) / _durations.durationMinute; }, function (d) { return d.getUTCMinutes(); }); exports['default'] = utcMinute; /***/ }), /* 338 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); var _durations = __webpack_require__(287); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcHour = new _timeInterval2['default']('hour', function (d) { return d.setUTCMinutes(0, 0, 0); }, function (d, s) { return d.setTime(Number(d) + s * _durations.durationHour); }, function (s, e) { return (e - s) / _durations.durationHour; }, function (d) { return d.getUTCHours(); }); exports['default'] = utcHour; /***/ }), /* 339 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcQuarter = new _timeInterval2['default']('quarter', function (d) { d.setUTCMonth(d.getUTCMonth() - (d.getUTCMonth() + 3) % 3, 1); d.setUTCHours(0, 0, 0, 0); }, function (d, s) { return d.setUTCMonth(d.getUTCMonth() + s * 3); }, function (s, e) { return (e.getUTCMonth() - (e.getUTCMonth() + 3) % 3 - (s.getUTCMonth() - (s.getUTCMonth() + 3) % 3)) / 3 + (e.getUTCFullYear() - s.getUTCFullYear()) * 4; }, function (d) { return Math.floor(d.getMonth() / 3); } // works incorrectly with every ); exports['default'] = utcQuarter; /***/ }), /* 340 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _timeInterval = __webpack_require__(286); var _timeInterval2 = _interopRequireDefault(_timeInterval); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var utcMonth = new _timeInterval2['default']('month', function (date) { date.setUTCDate(1); date.setUTCHours(0, 0, 0, 0); }, function (date, step) { return date.setUTCMonth(date.getUTCMonth() + step); }, function (start, end) { return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; }, function (date) { return date.getUTCMonth(); }); exports['default'] = utcMonth; /***/ }), /* 341 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.Weekdays = exports.DatetimeUnits = undefined; var _durations = __webpack_require__(287); var DatetimeUnits = { Millisecond: { name: 'Millisecond', ms: 1 }, Second: { name: 'Second', ms: _durations.durationSecond }, Minute: { name: 'Minute', ms: _durations.durationMinute }, Hour: { name: 'Hour', ms: _durations.durationHour }, Day: { name: 'Day', ms: _durations.durationDay }, Week: { name: 'Week', ms: _durations.durationWeek }, Month: { name: 'Month', ms: _durations.durationMonth }, Quarter: { name: 'Quarter', ms: _durations.durationQuarter }, Year: { name: 'Year', ms: _durations.durationYear } }, Weekdays = { Sunday: { name: 'Sunday', id: 0 }, Monday: { name: 'Monday', id: 1 }, Tuesday: { name: 'Tuesday', id: 2 }, Wednesday: { name: 'Wednesday', id: 3 }, Thursday: { name: 'Thursday', id: 4 }, Friday: { name: 'Friday', id: 5 }, Saturday: { name: 'Saturday', id: 6 } }; exports.DatetimeUnits = DatetimeUnits; exports.Weekdays = Weekdays; /***/ }), /* 342 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.duration = undefined; var _datetimeEnums = __webpack_require__(341); function duration(Unit, number) { // If Unit is not one of predefined, throw an error. if (!Unit || !_datetimeEnums.DatetimeUnits[Unit.name]) throw new Error('Invalid Unit provided: ' + Unit); number = Math.abs(number) || 1; return { Unit: Unit.name, number: number, ms: Unit.ms * number }; } exports.duration = duration; /***/ }), /* 343 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.interval = undefined; var _datetimeEnums = __webpack_require__(341); var _datetimeOps = __webpack_require__(327); /** * Creates an interval object with a start value, a duration and an outputFormat * to be used for formatting the results. * * @param {number} start The start value for the interval - timestamp or number * @param {object} duration The duration object defining the interval duration * @param {string} outputFormat The format in string using placeholders */ function interval(start, intervalConfig) { var calculateStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // Check duration object to identify date or number interval if (intervalConfig.duration.ms) { var _dateRangeCaclulator = (0, _datetimeOps.dateRangeCaclulator)(start, intervalConfig.duration, intervalConfig.enableUTC, intervalConfig.weekStartFrom || _datetimeEnums.Weekdays.Sunday, calculateStart), startDate = _dateRangeCaclulator.startDate, endDate = _dateRangeCaclulator.endDate; intervalConfig.outputFormat = intervalConfig.outputFormat || (0, _datetimeOps.getDefaultOutputFormat)(intervalConfig.duration.Unit); return { start: startDate, end: endDate, config: intervalConfig, toString: _datetimeOps.dateIntervalToString }; } } exports.interval = interval; /***/ }), /* 344 */ /***/ (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"); } } /** * A storage for aggregator functions. Stores a mapping of aggregator function names * to the actual functions. Provides methods to both register as well as retrieve * aggregator functions. Only a single instance is always provided for any module importing this file. */ var AggregatorStore = function () { function AggregatorStore() { _classCallCheck(this, AggregatorStore); this.store = {}; } AggregatorStore.prototype.register = function register(name, fn) { this.store[name] = fn; }; AggregatorStore.prototype.resolve = function resolve(name) { return this.store[name]; }; return AggregatorStore; }(); /** * Aggregator store to register new aggregators */ var aggregatorStore = function () { var store = null; function getStore() { if (store === null) { store = new AggregatorStore(); } return store; } return getStore(); }(); exports["default"] = aggregatorStore; /***/ }), /* 345 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.avg = exports.sum = undefined; var _ = __webpack_require__(344); var _2 = _interopRequireDefault(_); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var sum, avg, count, min, max, first, last, variance, stddev, aggregators; exports.sum = sum = function sum(prevSum, value) { return prevSum + value; }; exports.avg = avg = function avg(prevAvg, value, n) { return ((n - 1) * prevAvg + value) / n; }; count = function count(prevCount) { return ++prevCount; }; min = function min(prevMin, value) { return prevMin !== null ? prevMin > value ? value : prevMin : value; }; max = function max(prevMax, value) { return prevMax !== null ? prevMax < value ? value : prevMax : value; }; first = function first(prevFirst, value) { return prevFirst === null ? value : prevFirst; }; last = function last(prevLast, value) { return value; }; variance = function variance(prevVal, value, n) { var mean = value, vr = 0, prevMean; if (prevVal) { mean = prevVal.avg; vr = prevVal.variance; } prevMean = mean; if (n > 1) { mean = avg(mean, value, n); vr = (vr * (n - 2) + (value - mean) * (value - prevMean)) / (n - 1); } return { avg: mean, variance: vr }; }; stddev = function stddev(prevVal, value, n) { var newPrevVal, vr; if (prevVal) { newPrevVal = { avg: prevVal.avg, variance: prevVal.stddev * prevVal.stddev }; } vr = variance(newPrevVal, value, n); return { avg: vr.avg, stddev: Math.sqrt(vr.variance) }; }; // Register all internal aggregators aggregators = { sum: sum, avg: avg, count: count, min: min, max: max, first: first, last: last, variance: variance, stddev: stddev }; Object.entries(aggregators).forEach(function (key) { _2['default'].register(key[0], key[1]); }); exports.sum = sum; exports.avg = avg; /***/ }), /* 346 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = pipe; var _typeEnums = __webpack_require__(324); var _sort = __webpack_require__(279); /** * Optimize the flow of operations while keeping the intended output same * @param {...any} operations set of operations to optimize */ function pipe() { var opsLen = void 0, currentFunnel = [], markedForDel = [], resultFunnel = [], _optimizeGroupBetweenOps = function _optimizeGroupBetweenOps(current, marked) { var result = [], funnelLen = current.length; // loop over the current funnel and remove all select and sort operations for (var i = 0; i < funnelLen; i++) { if (!marked[i]) { // in result funnel only push operations which are not marked for deletion i.e. filter operations result.push(current[i]); } } // sort the filter operations, indexed filters are a priority over generic filters if (result && result.length > 0) { (0, _sort.binaryInsertionSort)(result, function (a, b) { return a.type - b.type; }); } return result; }, _optimizeEndOps = function _optimizeEndOps(current) { var result = [], funnelLen = current.length; // At first sort the operations based on operations types // Here sorting does 2 job - place the filter operations at first with index filters preceding generic filters // and then place sort and select operations at the last. But if multiple sort or select operations are used by mistake // then sorting will place them together, making it easier to remove all select, sort except last // So, clearly we need a stable sort here (0, _sort.binaryInsertionSort)(current, function (a, b) { return a.type - b.type; }); // push the first operation in stack for comparison result.push(current[0]); // start examining from the second element for (var i = 1; i < funnelLen; i++) { // Type 3 and 4 denotes sort and select respectively // For only sort and select operation if result funnel's last ops type is same as currently encountered ops type // then result funnel's last operations must be overridden with current operation // due to stable sorting of operations, all sort and select filters are placed together and only last ops of each type is valid // hence a linear search is performed, checking the last element each time, if the type matches then overrides the last element until there are no ops of same type left if (current[i].type >= 3 && current[i].type === result[result.length - 1].type) { result.pop(); } result.push(current[i]); } return result; }; // loop over all operations and check if the operation need to removed or reordered for (var _len = arguments.length, operations = Array(_len), _key = 0; _key < _len; _key++) { operations[_key] = arguments[_key]; } opsLen = operations.length; for (var i = 0; i < opsLen; i++) { switch (operations[i].type) { // if the operation is any kind of filter operation then they are never going to be removed, just pushed to current funnel stack for reordering case _typeEnums.OperatorTypes.IndexOpsFilter: case _typeEnums.OperatorTypes.GenericFilter: currentFunnel.push(operations[i]); markedForDel.push(false); break; // if the operation is select or sort operation then they will be removed if occurred between 2 group by operations case _typeEnums.OperatorTypes.Select: case _typeEnums.OperatorTypes.Sort: currentFunnel.push(operations[i]); markedForDel.push(true); break; case _typeEnums.OperatorTypes.GroupBy: // if a group by is encountered then this is considered as a pivot point // all select and sort operations will be removed and filter operations are sorted - index filters are performed first then rest of the filters resultFunnel = resultFunnel.concat(_optimizeGroupBetweenOps(currentFunnel, markedForDel), operations[i]); // reset the current funnel and marked funnel stack as funnel stack before group by is already optimized and added to final result funnel currentFunnel = []; markedForDel = []; break; } } // At this point, all operations between every group by is optimized, only the last section i.e. from last group by till end // or if a group by is not present then from start to end are left with // All filter operations are pushed first with indexed filters as priority over geberic filter // Then sort operation is placed, if multiple sort operations are present then only the last sort is valid // Then select operayion is placed, if multiple select operations are present then only the last select is valid resultFunnel = resultFunnel.concat(_optimizeEndOps(currentFunnel)); return resultFunnel; } /***/ }), /* 347 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeEnums = __webpack_require__(324); var _datatableUtils = __webpack_require__(276); var _comparators = __webpack_require__(278); var _sort = __webpack_require__(279); var _sort2 = _interopRequireDefault(_sort); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * sorts the data table * @param {array} sortConfig - an array of sort configuration, number of items in array is equal to number of levels of sorting */ function sort(sortConfig) { var sortConfigArr = sortConfig; return { ops: 'sort', type: _typeEnums.OperatorTypes.Sort, _updateArgs: function _updateArgs(configArr) { sortConfigArr = configArr; }, fn: function fn(data, schema, config, _generatorFn) { return { data: data, schema: schema, config: config, generatorFn: function generatorFn() { if (_generatorFn) { data = _generatorFn.call(); } var compareFn = void 0; if (sortConfigArr.constructor === Function) { compareFn = sortConfigArr; } else { if (sortConfigArr.constructor !== Array) { sortConfigArr = [sortConfigArr]; } var comparatorFnArr = [], colIndexArr = [], i = void 0, colIndex = void 0, result = void 0; for (i = 0; i < sortConfigArr.length; i++) { if (sortConfigArr[i].column) { colIndex = (0, _datatableUtils.columnIndexOf)(sortConfigArr[i].column, schema); colIndexArr.push(colIndex); if (colIndex === -1) { throw new Error('Sort column is not found in schema - ' + sortConfigArr[i].column); } switch (schema[colIndex].type) { case 'number': case 'interval': case 'date': comparatorFnArr.push(_comparators.numberComparator); break; default: comparatorFnArr.push(_comparators.stringComparator); } } } compareFn = function compareFn(a, b) { for (i = 0; i < sortConfigArr.length; i++) { if (schema[colIndexArr[i]].type === 'interval') { result = sortConfigArr[i].order === 'desc' ? comparatorFnArr[i](b[colIndexArr[i]].start, a[colIndexArr[i]].start) : comparatorFnArr[i](a[colIndexArr[i]].start, b[colIndexArr[i]].start); } else { result = sortConfigArr[i].order === 'desc' ? comparatorFnArr[i](b[colIndexArr[i]], a[colIndexArr[i]]) : comparatorFnArr[i](a[colIndexArr[i]], b[colIndexArr[i]]); } if (result === 0) { // if exact match if (i === sortConfigArr.length - 1) { // if current sort level is the last one then simply return 0, no swap will occur return 0; } else continue; // if exact match is found but this is not the current level then further levels need to be evaluated } else { // if anything other than 0 then further evaluation is not needed return result; } } }; } (0, _sort2['default'])(data, compareFn); return data; } }; } }; } exports['default'] = sort; /***/ }), /* 348 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _datatableUtils = __webpack_require__(276); var _datetimeOps = __webpack_require__(327); var _duration = __webpack_require__(342); var _interval = __webpack_require__(343); var _aggregators = __webpack_require__(344); var _aggregators2 = _interopRequireDefault(_aggregators); __webpack_require__(345); var _globalConfig = __webpack_require__(280); var _typeEnums = __webpack_require__(324); var _groupBy = __webpack_require__(326); var _groupBy2 = _interopRequireDefault(_groupBy); var _comparators = __webpack_require__(278); var _sortedSearch = __webpack_require__(323); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Performs pivot operation on current data table. * * @param {array} groupConfigArr - The group configuration array * @param {string} pivotColumn - The column name on which to pivot * @param {array} aggrConfigArr - The aggregation configuration array * @returns {array} - data rows after performing pivot operations */ function pivot(groupConfigArr, pivotColumn, aggrConfigArr) { var groupConfigArray = groupConfigArr, pivotCol = pivotColumn, aggrConfigArray = aggrConfigArr; return { ops: 'pivot', type: _typeEnums.OperatorTypes.GroupBy, _updateArgs: function _updateArgs(groupConfigurationArr, pivotColumnName, aggrConfigurationArr) { groupConfigArray = groupConfigurationArr; pivotCol = pivotColumnName; aggrConfigArray = aggrConfigurationArr; }, fn: function fn(data, schema, config, generatorFn) { if (groupConfigArray.length === 0) throw new Error('groupConfigArray cannot be empty'); if (aggrConfigArray.length === 0) throw new Error('aggrConfigArray cannot be empty'); if (!pivotCol) throw new Error('pivotCol cannot be empty'); if (!(groupConfigArray instanceof Array) && groupConfigArray instanceof Object) { groupConfigArray = [groupConfigArray]; } if (!(aggrConfigArray instanceof Array) && aggrConfigArray instanceof Object) { aggrConfigArray = [aggrConfigArray]; } if (groupConfigArray.length === 1 && config && groupConfigArray[0].column === config.indexBy) { // if single and indexBy column return _singleSortedPivot(data, schema, config, groupConfigArray[0], aggrConfigArray, pivotCol); } else { // OR, unsorted single/multiple columns return _genericPivot(data, schema, config, generatorFn, groupConfigArray, aggrConfigArray, pivotCol); } } }; } /** * Takes the group config, aggregation config arrays and the pivot column name, * and creates and returns a schema from the two. * * @param {array} data The datatable being operated on * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array * @param {object} pivotColumn The column on which to pivot */ function _createAggrSchema(data, schema, groupConfig, aggrConfig, pivotColumn) { var newSchema = [], comparator, uniquePivotItems, uniquePivotLength, pivotColumns = {}, groupConfigLength, aggrConfigLength, columnIndex, column, type, aggregatorFn, aggrColName, i, j, count = 0, operation, newColumn; groupConfig = groupConfig instanceof Array ? groupConfig : [groupConfig]; aggrConfig = aggrConfig instanceof Array ? aggrConfig : [aggrConfig]; groupConfigLength = groupConfig.length; aggrConfigLength = aggrConfig.length; // add the group columns in new schema for (i = 0; i < groupConfigLength; i++) { columnIndex = (0, _datatableUtils.columnIndexOf)(groupConfig[i].column, schema); column = schema[columnIndex]; if (columnIndex === -1) throw new Error('incorrect column name in groupConfigArr - ' + groupConfig[i].column); newColumn = { name: groupConfig[i].outputAs || groupConfig[i].column, type: column.type === 'date' ? 'interval' : column.type }; if (column.enableUTC !== undefined) { newColumn.enableUTC = column.enableUTC; } newSchema.push(newColumn); } switch (pivotColumn.type) { case 'number': case 'date': // we will not be dealing with interval column // interval is only an intermediate column and not exposed // and user will only be feeding exterbal data to data store // but for children data table we must deal with interval column comparator = _comparators.numberComparator; break; default: comparator = _comparators.stringComparator; break; } // get unique pivot values uniquePivotItems = (0, _datatableUtils.columnUnique)(pivotColumn.name, data, schema); uniquePivotItems.sort(function (a, b) { return comparator(a, b); }); uniquePivotLength = uniquePivotItems.length; for (i = 0; i < aggrConfigLength; i++) { // default operation is avg operation = aggrConfig[i].operation || 'avg'; columnIndex = (0, _datatableUtils.columnIndexOf)(aggrConfig[i].column, schema); column = schema[columnIndex]; if (columnIndex === -1) throw new Error('incorrect column name in aggrConfigArr - ' + aggrConfig[i].column); aggregatorFn = _aggregators2['default'].resolve(operation); if (!aggregatorFn) throw new Error(operation + ' is not a defined operation'); // if operation is first or last then inherit from schema's column // if it's count, type will be number // rest are all numeric operations // however, if the column type is not numeric, throw an error switch (operation) { case 'first': case 'last': type = column.type; break; case 'count': type = 'number'; break; default: if (column.type !== 'number') throw new Error(operation + ' can apply only on numbers'); type = 'number'; } for (j = 0; j < uniquePivotLength; j++) { aggrColName = uniquePivotItems[j] + ' - ' + (aggrConfig[i].outputAs || aggrConfig[i].column + (operation ? ' - ' + operation : '')); pivotColumns[aggrColName] = count++; newSchema.push({ name: aggrColName, type: type }); } } return { schema: newSchema, pivots: pivotColumns }; } /** * Performs group by on a single column. * * @param {array} data The datatable being operated on * @param {array} schema The schema * @param {array} groupConfig The group configuration array * @param {array} aggrConfig The aggregation configuration array * @param {string} pivotName The column name on which to pivot */ function _singleSortedPivot(data, schema, config, groupConfig, aggrConfig, pivotName) { var newData = [], newSchema = [], pivotColumns = {}, schemaResult, dataLength = data.length, groupColumnIndex, groupColumn, pivotColumnIndex, pivotColumn, maxDate, groupConfigCopy, timeDuration, startValFloorVal, startPos = 0, lastEntry, cacheColumnIndex = _cacheColumnIndex(), cacheGroupCount = [], newDataLength, enableUTC, i; groupColumnIndex = (0, _datatableUtils.columnIndexOf)(groupConfig.column, schema); if (groupColumnIndex === -1) throw new Error('incorrect column name in groupConfigArr - ' + groupConfig); pivotColumnIndex = (0, _datatableUtils.columnIndexOf)(pivotName, schema); if (pivotColumnIndex === -1) throw new Error('incorrect pivot column name'); groupColumn = schema[groupColumnIndex]; pivotColumn = schema[pivotColumnIndex]; groupConfigCopy = Object.assign({}, groupConfig); // prepare the schema groupConfigCopy.type = groupColumn.type; groupConfigCopy.outputAs = groupConfig.outputAs; schemaResult = _createAggrSchema(data, schema, groupConfigCopy, aggrConfig, pivotColumn); newSchema = schemaResult.schema; pivotColumns = schemaResult.pivots; if (dataLength > 0) { enableUTC = groupColumn.enableUTC || (0, _globalConfig.getConfig)('enableUTC'); // if it's a date column, // create a duration object // if startValue is present/number, else use first row's datetime // get the start value of the dataset if (groupColumn.type === 'date') { var peaks = void 0, minDate = void 0, startValue = void 0; timeDuration = (0, _duration.duration)(groupConfig.timeUnit, Math.abs(groupConfig.binSize) || 1); if (!data[0] || !data[0][groupColumnIndex] || !data[dataLength - 1] || !data[dataLength - 1][groupColumnIndex]) { peaks = (0, _datatableUtils.columnExtents)(groupConfig.column, data, schema, config.indexBy); } minDate = data[0] && data[0][groupColumnIndex] || peaks.min; startValue = groupConfig.startValue && parseInt(groupConfig.startValue, 10); if (startValue) { if (startValue >= minDate) { var comparer = function comparer(a, b) { return (0, _comparators.numberComparator)(a[groupColumnIndex], b); }; // if start value falls on or after the minimum date in dataset, then floor it to unit with binning 1 startValFloorVal = (0, _datetimeOps.getDateStart)(startValue, (0, _duration.duration)(groupConfig.timeUnit, 1), enableUTC, groupConfig.weekStartFrom); // get the index of left most occurrence startPos = (0, _sortedSearch.leftMostExactOrGreater)(startValFloorVal, data, comparer, 0, data.length); } else { // if start value falls before the minimum date in dataset, then floor the minimum to date unit with binning binSize startValFloorVal = (0, _datetimeOps.getDateStart)(minDate, timeDuration, enableUTC, groupConfig.weekStartFrom, startValue); } } else { // if start value absent, then floor the minimum to date unit with binning 1 startValFloorVal = (0, _datetimeOps.getDateStart)(minDate, (0, _duration.duration)(groupConfig.timeUnit, 1), enableUTC, groupConfig.weekStartFrom); } maxDate = data[dataLength - 1] && data[dataLength - 1][groupColumnIndex] || peaks.max; } // if start value is less than maxdate only then proceed if (startValFloorVal === undefined || startValFloorVal <= maxDate) { var intervalConfig = { duration: timeDuration, outputFormat: groupConfig.outputFormat, enableUTC: enableUTC, weekStartFrom: groupConfig.weekStartFrom }; if (startValFloorVal !== undefined) { // if no entry in new data array, create new interval entry, // add it to new data array and return it lastEntry = [(0, _interval.interval)(startValFloorVal, intervalConfig)]; newData.push(lastEntry); } for (i = startPos; i < dataLength; i++) { if (data[i].length > 0) { // date field // OR, string field OR, number field with binning 1 if (groupColumn.type === 'date') { lastEntry = (0, _groupBy._singleSortedAddRowDate)(newData, lastEntry, data[i][groupColumnIndex], intervalConfig, startValFloorVal); } else if (groupColumn.type === 'string' || groupColumn.type === 'number') { lastEntry = (0, _groupBy._singleSortedAddRow)(newData, lastEntry, data[i][groupColumnIndex]); } newDataLength = newData.length - 1; // init the cacheGroupCount current row with an empty object before aggregation cacheGroupCount[newDataLength] = cacheGroupCount[newDataLength] || {}; lastEntry && _applyAggr(data[i], schema, lastEntry, 1, aggrConfig, pivotColumnIndex, pivotColumns, cacheColumnIndex, cacheGroupCount[newDataLength]); } } } } return { data: newData, schema: newSchema, config: { indexBy: groupConfig.groupColumn } }; } /** * Performs group by on unsorted/multiple column data. * * @param {array} data The datatable being operated on * @param {array} schema The schema * @param {object} config The config object * @param {object} generatorFn * @param {array} groupConfigArr The group configuration array * @param {array} aggrConfigArr The aggregation configuration array * @param {string} pivotColumn The column name on which to pivot */ function _genericPivot(data, schema, config, generatorFn, groupConfigArr, aggrConfigArr, pivotColumn) { var groupOps = void 0, groupedData = void 0, comparator = void 0, pivotUnique = void 0, pivotUniqueSorted = void 0, groupedSchemaWithoutPivot = void 0, pivotColIndex = void 0, groupedSchemaLen = void 0, groupConfigColumns = void 0, groupColMap = {}, hashTable = {}, _getRowIndex = function _getRowIndex(hashKey) { if (hashTable.hasOwnProperty(hashKey)) { return hashTable[hashKey]; } else return -1; }, _insertNewKey = function _insertNewKey(hashKey, rowIndex) { hashTable[hashKey] = rowIndex; }, _getPivotAggrColName = function _getPivotAggrColName(pivotCol, outputAs, aggrCol, aggrOps) { return pivotCol + ' - ' + (outputAs || aggrCol + (aggrOps ? ' - ' + aggrOps : '')); }, _buildPivotSchema = function _buildPivotSchema() { var newSchema = [], aggr = void 0; var _loop = function _loop(i) { // if column is one of group by column then directly copy the column config if (groupConfigColumns.includes(groupedSchemaWithoutPivot[i].name)) { newSchema.push(groupedSchemaWithoutPivot[i]); // build the column mapping for future use groupColMap[groupedSchemaWithoutPivot[i].name] = i; } else { // if column is one of aggregation column then create a new name by prefixing the aggregation column name with the unique values of pivot columns /* eslint-disable no-loop-func */ aggr = aggrConfigArr.filter(function (x) { return (x.outputAs || x.column + (x.operation ? ' - ' + x.operation : '')) === groupedSchemaWithoutPivot[i].name; })[0]; // loop through all the unique values and create a column for each combination for (var j = 0; j < pivotUniqueSorted.length; j++) { newSchema.push({ name: _getPivotAggrColName(pivotUniqueSorted[j], aggr.outputAs, aggr.column, aggr.operation), type: groupedSchemaWithoutPivot[i].type }); } } }; for (var i = 0; i < groupedSchemaLen; i++) { _loop(i); } return newSchema; }, _buildPivotData = function _buildPivotData(newSchema) { var pivotData = [], columnLen = newSchema.length, newSchemaColMap = {}, i = void 0, j = void 0, rowIndex = void 0, aggr = void 0, rowMapIndex = void 0, rowMap = {}, hashKey = ''; // build the mapping of key value pair where key is the column name of new schema and value is the index of data for (i = 0; i < columnLen; i++) { newSchemaColMap[newSchema[i].name] = i; } // loop through all data of grouped result set to build the pivot for (i = 0; i < groupedData.data.length; i++) { rowMap = {}; hashKey = ''; for (j = 0; j < groupedData.schema.length; j++) { // previously group col map was built which contains all columns of original group by // if column is one of the group by column then create the hashkey using the column value if (groupColMap.hasOwnProperty(groupedData.schema[j].name)) { // a row map is created for the curret row where key is index of column rowMap[newSchemaColMap[groupedData.schema[j].name]] = groupedData.data[i][j]; // build the hashkey if (groupedData.schema[j].type === 'interval') { hashKey += groupedData.data[i][j].start; } else { hashKey += groupedData.data[i][j]; } } else if (groupedData.schema[j].name !== pivotColumn) { // do not take any action for pivot column // for all aggregation column we combine the aggregation column with the pivot column value // fine the proper column index where it should be inserted and insert the value in row map /* eslint-disable no-loop-func */ aggr = aggrConfigArr.filter(function (x) { return (x.outputAs || x.column + (x.operation ? ' - ' + x.operation : '')) === groupedData.schema[j].name; })[0]; rowMapIndex = newSchemaColMap[_getPivotAggrColName(groupedData.data[i][pivotColIndex], aggr.outputAs, aggr.column, aggr.operation)]; if (rowMapIndex) rowMap[rowMapIndex] = groupedData.data[i][j]; } } // check if row already exists rowIndex = _getRowIndex(hashKey); if (rowIndex > -1) { // if row already exists and just need to update pivot aggregation value var row = pivotData[rowIndex]; for (var index in rowMap) { row[index] = rowMap[index]; } } else { // if row does not exist // create an array of exact schema length var _row = new Array(columnLen); // insert all values at proper place, keeping the missing values as undefined // missing values may be filled up at later phase for (var _index in rowMap) { _row[_index] = rowMap[_index]; } // insert the row pivotData.push(_row); // insert the row index at hash table _insertNewKey(hashKey, pivotData.length - 1); } } return pivotData; }, pivotSchema = [], pivotData = []; groupOps = (0, _groupBy2['default'])(groupConfigArr.concat({ column: pivotColumn }), aggrConfigArr); groupedData = groupOps.fn(data, schema, config, generatorFn); pivotUnique = (0, _datatableUtils.columnUnique)(pivotColumn, data, schema); pivotColIndex = (0, _datatableUtils.columnIndexOf)(pivotColumn, groupedData.schema); switch (groupedData.schema[pivotColIndex].type) { case 'number': case 'date': // we will not be dealing with interval column // interval is only an intermediate column and not exposed // and user will only be feeding exterbal data to data store // but for children data table we must deal with interval column comparator = _comparators.numberComparator; break; default: comparator = _comparators.stringComparator; break; } pivotUniqueSorted = pivotUnique && pivotUnique.sort(function (a, b) { return comparator(a, b); }) || []; groupedSchemaWithoutPivot = groupedData.schema.filter(function (x) { return x.name !== pivotColumn; }); groupedSchemaLen = groupedSchemaWithoutPivot.length; groupConfigColumns = groupConfigArr.map(function (x) { return x.outputAs || x.column; }); pivotSchema = _buildPivotSchema(); if (groupedData.data.length > 0) { pivotData = _buildPivotData(pivotSchema); } return { data: pivotData, schema: pivotSchema, config: groupedData.config }; } /** * Caches the column's index in the original data schema. */ function _cacheColumnIndex() { var cache = {}; return function (columnName, schema) { if (!cache[columnName]) { cache[columnName] = (0, _datatableUtils.columnIndexOf)(columnName, schema); } return cache[columnName]; }; } /** * Perform aggregation operation on given aggregation configuration and a data row. * * @param {array} dataRow The datatable row being operated on * @param {array} schema The schema * @param {array} lastEntry The last entry in the new data array * @param {number} entryIndex The entry index for the aggregated columns in the row, after the group columns * @param {array} aggrConfig The aggregation configuration array * @param {number} pivotColumnIndex The index of the pivot column in data * @param {object} pivotColumns The list of unique pivot column values mapped to their index * @param {function} cacheColumnIndex The reference to the caching function for column indices * @param {object} cacheGroupCountRow The current row in the cache group count column */ function _applyAggr(dataRow, schema, lastEntry, entryIndex, aggrConfig, pivotColumnIndex, pivotColumns, cacheColumnIndex, cacheGroupCountRow) { var aggrConfigLength = aggrConfig.length, columnIndex = void 0, operation = void 0, count = void 0, i = void 0, index = void 0; for (i = 0; i < aggrConfigLength; i++) { columnIndex = cacheColumnIndex(aggrConfig[i].column, schema); if (dataRow[columnIndex] !== undefined && dataRow[columnIndex] !== null) { // default operation is avg operation = aggrConfig[i].operation || 'avg'; index = pivotColumns[dataRow[pivotColumnIndex] + ' - ' + (aggrConfig[i].outputAs || aggrConfig[i].column + (operation ? ' - ' + operation : ''))]; // for the below operations, calculate and store the current count of the column values in the group, in the cacheGroupCount and count switch (operation) { case 'sum': case 'min': case 'max': case 'first': case 'last': count = null; break; default: count = cacheGroupCountRow[index] = cacheGroupCountRow[index] && cacheGroupCountRow[index] + 1 || 1; break; } // for operation other than count, calculate the aggregated value and add to the last entered row lastEntry[entryIndex + index] = operation === 'count' ? count : _aggregators2['default'].resolve(operation)(lastEntry[entryIndex + index] !== undefined ? lastEntry[entryIndex + index] : null, dataRow[columnIndex], count); } } } exports['default'] = pivot; /***/ }), /* 349 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.aggregatorStore = undefined; var _aggregators = __webpack_require__(344); var _aggregators2 = _interopRequireDefault(_aggregators); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.aggregatorStore = _aggregators2['default']; /***/ }), /* 350 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.Weekdays = exports.DatetimeUnits = exports.duration = exports.formatDate = exports.parseDate = exports.after = exports.before = undefined; var _beforeAfter = __webpack_require__(351); var _parserFormatter = __webpack_require__(352); var _duration = __webpack_require__(342); var _datetimeEnums = __webpack_require__(341); exports.before = _beforeAfter.before; exports.after = _beforeAfter.after; exports.parseDate = _parserFormatter.parseDate; exports.formatDate = _parserFormatter.formatDate; exports.duration = _duration.duration; exports.DatetimeUnits = _datetimeEnums.DatetimeUnits; exports.Weekdays = _datetimeEnums.Weekdays; /***/ }), /* 351 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.after = exports.before = undefined; var _datetimeOps = __webpack_require__(327); var _datetimeEnums = __webpack_require__(341); function before(duration, timestamp, enableUTC, weekStartFrom) { if (!duration) throw new Error('duration is missing'); if (timestamp && (isNaN(timestamp) || isNaN(+new Date(timestamp)))) throw new Error('timestamp is incorrect'); return (0, _datetimeOps.getDateOffset)(!isNaN(timestamp) ? timestamp : +new Date(), duration.Unit, -duration.number, enableUTC, weekStartFrom || _datetimeEnums.Weekdays.Sunday); } function after(duration, timestamp, enableUTC, weekStartFrom) { if (!duration) throw new Error('duration is missing'); if (timestamp && (isNaN(timestamp) || isNaN(+new Date(timestamp)))) throw new Error('timestamp is incorrect'); return (0, _datetimeOps.getDateOffset)(!isNaN(timestamp) ? timestamp : +new Date(), duration.Unit, duration.number, enableUTC, weekStartFrom || _datetimeEnums.Weekdays.Sunday); } exports.before = before; exports.after = after; /***/ }), /* 352 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.formatDate = exports.parseDate = undefined; var _timeConverter = __webpack_require__(281); var _timeConverter2 = _interopRequireDefault(_timeConverter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Parses a date string using a given format and returns the timestamp. * * @param {string} dateStr The date as a string * @param {string} format The format of the date string defined using placeholders */ function parseDate(dateStr, format, enableUTC) { var specifier, parsed; if (format) { specifier = (enableUTC !== undefined ? enableUTC : false) ? _timeConverter2['default'].utcParser(format) : _timeConverter2['default'].parser(format); parsed = specifier.parse(dateStr); parsed = parsed && parsed.getTime(); } // if parsed date not received or format missing, try using system converter if (!parsed) { parsed = (enableUTC !== undefined ? enableUTC : false) ? +new Date(dateStr + 'Z') : +new Date(dateStr); } // if still not parsed, throw error if (!parsed) throw new Error('Incorrect string or format provided'); return parsed; } /** * Converts a given timestamp into a date string using a given format. * * @param {number} timestamp The timestamp to be formatted * @param {string} format The format of the date string defined using placeholders */ function formatDate(timestamp, format, enableUTC) { var specifier, formatted; if (isNaN(parseInt(timestamp, 10))) throw new Error('Timestamp must be a number: ' + timestamp); if (!format) { format = '%a, %-d %b %Y, %H:%M:%S:%L'; } specifier = (enableUTC !== undefined ? enableUTC : false) ? _timeConverter2['default'].utcFormatter(format) : _timeConverter2['default'].formatter(format); formatted = specifier.format(new Date(timestamp)); if (!formatted) throw new Error('Incorrect format provided: ' + format); return formatted; } exports.parseDate = parseDate; exports.formatDate = formatDate; /***/ }), /* 353 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { // Chart APIs in the Charts package column2d: 'charts', column3d: 'charts', bar2d: 'charts', bar3d: 'charts', pie2d: 'charts', pie3d: 'charts', line: 'charts', area2d: 'charts', doughnut2d: 'charts', doughnut3d: 'charts', pareto2d: 'charts', pareto3d: 'charts', mscolumn2d: 'charts', mscolumn3d: 'charts', msline: 'charts', msarea: 'charts', msbar2d: 'charts', msbar3d: 'charts', stackedcolumn2d: 'charts', marimekko: 'charts', stackedcolumn3d: 'charts', stackedarea2d: 'charts', stackedcolumn2dline: 'charts', stackedcolumn3dline: 'charts', stackedbar2d: 'charts', stackedbar3d: 'charts', msstackedcolumn2d: 'charts', mscombi2d: 'charts', mscombi3d: 'charts', mscolumnline3d: 'charts', mscombidy2d: 'charts', mscolumn3dlinedy: 'charts', stackedcolumn3dlinedy: 'charts', msstackedcolumn2dlinedy: 'charts', scatter: 'charts', bubble: 'charts', ssgrid: 'charts', scrollcolumn2d: 'charts', scrollcolumn3d: 'charts', scrollline2d: 'charts', scrollarea2d: 'charts', scrollstackedcolumn2d: 'charts', scrollcombi2d: 'charts', scrollcombidy2d: 'charts', spline: 'charts', splinearea: 'charts', msspline: 'charts', mssplinearea: 'charts', mssplinedy: 'charts', // Chart APIs in the powercharts package multiaxisline: 'powercharts', multilevelpie: 'powercharts', waterfall2d: 'powercharts', msstepline: 'powercharts', inversemsline: 'powercharts', inversemscolumn2d: 'powercharts', inversemsarea: 'powercharts', errorbar2d: 'powercharts', errorscatter: 'powercharts', errorline: 'powercharts', logmsline: 'powercharts', logmscolumn2d: 'powercharts', logstackedcolumn2d: 'powercharts', radar: 'powercharts', dragnode: 'powercharts', candlestick: 'powercharts', selectscatter: 'powercharts', dragcolumn2d: 'powercharts', dragline: 'powercharts', dragarea: 'powercharts', boxandwhisker2d: 'powercharts', kagi: 'powercharts', heatmap: 'powercharts', // Chart APIs in the Widgets package angulargauge: 'widgets', bulb: 'widgets', cylinder: 'widgets', drawingpad: 'widgets', funnel: 'widgets', hbullet: 'widgets', hled: 'widgets', hlineargauge: 'widgets', vlineargauge: 'widgets', pyramid: 'widgets', realtimearea: 'widgets', realtimecolumn: 'widgets', realtimeline: 'widgets', realtimelinedy: 'widgets', realtimestackedarea: 'widgets', realtimestackedcolumn: 'widgets', sparkcolumn: 'widgets', sparkline: 'widgets', sparkwinloss: 'widgets', thermometer: 'widgets', vbullet: 'widgets', vled: 'widgets', // Chart APIs in the ZoomLine package zoomline: 'zoomline', zoomlinedy: 'zoomline', // Chart APIs in no specific package gantt: 'gantt', treemap: 'treemap', zoomscatter: 'zoomscatter', overlappedbar2d: 'overlappedbar2d', overlappedcolumn2d: 'overlappedcolumn2d', msstackedcolumn2dsplinedy: 'msstackedcolumn2dsplinedy', timeseries: 'timeseries' }; /***/ }), /* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); // Regular Expressions that helps to check XSS security loops var SCRIPT_LOAD_TIMEOUT = 120000; /** * To keep a track of scripts requested. * @type Object */ var loadedScripts = {}; /** * Loads a JS file by attaching it to the head of the docuent as a script. */ function loadScript(scriptSrc) { if (!loadedScripts[scriptSrc]) { var head = document.getElementsByTagName('head')[0], script = document.createElement('script'), timeout = setTimeout(function () { script.onerror({ type: 'timeout', target: script }); }, SCRIPT_LOAD_TIMEOUT); script.charset = 'utf-8'; script.timeout = SCRIPT_LOAD_TIMEOUT; loadedScripts[scriptSrc] = new Promise(function (resolve, reject) { script.onload = function (e) { script.onerror = script.onload = null; clearTimeout(timeout); resolve(e); }; script.onerror = function (e) { script.onerror = script.onload = null; clearTimeout(timeout); reject(e); }; }); // we do not allow XSS unsafe string if (!(0, _lib.isXSSSafe)(scriptSrc, false)) { scriptSrc = typeof window.encodeURIComponent === 'function' ? window.encodeURIComponent(scriptSrc) : window.escape(scriptSrc); } script.src = scriptSrc; head.appendChild(script); } return loadedScripts[scriptSrc]; } exports['default'] = loadScript; /***/ }), /* 355 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(this, {})) /***/ }) /******/ ])["default"]; }); //# sourceMappingURL=http://localhost:3052/3.13.3-sr.1/map/source/fusioncharts.js.map (window["webpackJsonpFusionCharts"] = window["webpackJsonpFusionCharts"] || []).push([[2],Array(359).concat([ /* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesian = __webpack_require__(360); var _cartesian2 = _interopRequireDefault(_cartesian); var _singleseriesDataset = __webpack_require__(431); var _singleseriesDataset2 = _interopRequireDefault(_singleseriesDataset); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var SSCartesian = function (_Cartesian) { _inherits(SSCartesian, _Cartesian); /** * constructor fn */ function SSCartesian() { _classCallCheck(this, SSCartesian); var _this = _possibleConstructorReturn(this, _Cartesian.call(this)); _this.registerFactory('dataset', _singleseriesDataset2['default'], ['vCanvas']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ SSCartesian.getName = function getName() { return 'SSCartesian'; }; /** * Sets the name of the component * @return {string} name */ SSCartesian.prototype.getName = function getName() { return 'SSCartesian'; }; SSCartesian.prototype.__setDefaultConfig = function __setDefaultConfig() { _Cartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.hasLegend = false; config.linethickness = 4; }; /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ SSCartesian.prototype._checkInvalidSpecificData = function _checkInvalidSpecificData() { var jsonData = this.getFromEnv('dataSource'), data = jsonData.data; if (!data || !data.length) { return true; } }; SSCartesian.prototype._setCategories = function _setCategories() { var iapi = this, dataObj = iapi.getFromEnv('dataSource'), xAxis = iapi.getChildren('xAxis'), dataset = dataObj.dataset, categories = dataObj.data || dataset && dataset[0].data; xAxis[0].setTickValues(categories); }; return SSCartesian; }(_cartesian2['default']); exports['default'] = SSCartesian; /***/ }), /* 360 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _commonspacemanager = __webpack_require__(361); var _commonspacemanager2 = _interopRequireDefault(_commonspacemanager); var _lib = __webpack_require__(125); var _cartesianAxis = __webpack_require__(376); var _cartesianAxis2 = _interopRequireDefault(_cartesianAxis); var _canvasAxisRefCartesian = __webpack_require__(424); var _canvasAxisRefCartesian2 = _interopRequireDefault(_canvasAxisRefCartesian); var _vcanvas = __webpack_require__(427); var _vcanvas2 = _interopRequireDefault(_vcanvas); var _mouseTracker = __webpack_require__(429); var _mouseTracker2 = _interopRequireDefault(_mouseTracker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var mathMax = Math.max, mathMin = Math.min, UNDEF = void 0; /** * Base class for all cartesian charts and who depend on this class * Its not an standalone chart * @type {class} */ var Cartesian = function (_CommonSpaceManager) { _inherits(Cartesian, _CommonSpaceManager); /** * Constructor for this class */ function Cartesian() { _classCallCheck(this, Cartesian); var _this = _possibleConstructorReturn(this, _CommonSpaceManager.call(this)); _this.registerFactory('axis', _cartesianAxis2['default'], ['canvas']); _this.registerFactory('canvas', _canvasAxisRefCartesian2['default']); _this.registerFactory('vCanvas', _vcanvas2['default'], ['axis']); _this.registerFactory('mouseTracker', _mouseTracker2['default'], ['canvas']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ Cartesian.getName = function getName() { return 'Cartesian'; }; /** * Sets the name of the component * @return {string} name */ Cartesian.prototype.getName = function getName() { return 'Cartesian'; }; /** * Returns the type of the component * * @return {string} The type of the component */ Cartesian.prototype.getType = function getType() { return 'chartAPI'; }; /** * function to allocate space x axis label * It restricts xAxis to take maximum space for for label * @param {Component} axis xAxis instance of CartesianAxis */ Cartesian.prototype._allocateXAxisLabelSpace = function _allocateXAxisLabelSpace(axis) { var iapi = this, config = iapi.config, dimensions = axis.getAxisEndLabelDisplaySpace(), left = dimensions.left, right = dimensions.right, top = dimensions.top, sum, bottom = dimensions.bottom, availableWidth = config.availableWidth, availableHeight = config.availableHeight, canvasLeft = config.canvasLeft, canvasRight = config.canvasRight, canvasTop = config.canvasTop, canvasBottom = config.canvasBottom, width = config.width, height = config.height, setDimension = function setDimension(dimension1, dimension2) { if (dimension1 < dimension2 && dimension2 > 0) { return dimension2 - dimension1; } else { return 0; } }; // Restricting space allocation to the maximum available space if (top + bottom > availableHeight) { sum = top + bottom; top = availableHeight * top / sum; bottom = availableHeight * bottom / sum; } if (left + right > availableWidth) { sum = left + right; left = availableWidth * left / sum; right = availableWidth * right / sum; } // Checking for existing canvas to chart space and recalculationg space allocation. left = setDimension(canvasLeft, left); right = setDimension(width - canvasRight, right); top = setDimension(canvasTop, top); bottom = setDimension(height - canvasBottom, bottom); iapi._allocateSpace({ left: left, right: right, top: top, bottom: bottom }); }; /** * function to set category to xAxis */ Cartesian.prototype._setCategories = function _setCategories() { var iapi = this, dataObj = iapi.getFromEnv('dataSource'), xAxis = iapi.getChildren('xAxis'), categories = dataObj.categories && dataObj.categories.length && dataObj.categories[0].category; xAxis && xAxis[0].setTickValues(categories); }; /** * function to parse JSON data for configurations of axis * @return {Object} configurations of axes */ Cartesian.prototype._feedAxesRawData = function _feedAxesRawData() { var iapi = this, chartConfig = iapi.config, dataObj = iapi.getFromEnv('dataSource'), xAxisConf, yAxisConf; xAxisConf = iapi.getSpecificxAxisConf(); yAxisConf = iapi.getSpecificyAxisConf(); xAxisConf.vtrendlines = (0, _lib.extend2)([], dataObj.vtrendlines); yAxisConf.trendlines = (0, _lib.extend2)([], dataObj.trendlines); if (chartConfig.isstacked) { yAxisConf.isPercent = (0, _lib.pluckNumber)(chartConfig.stack100percent, 0); } return { yAxisConf: [yAxisConf], xAxisConf: [xAxisConf] }; }; /** * Returns x-axis configuration for chart. * @return {Object} configurations of x-axis. */ Cartesian.prototype.getSpecificxAxisConf = function getSpecificxAxisConf() { var iapi = this, chartAttrs = iapi.getFromEnv('chart-attrib'), chartConfig = iapi.config, is3D = iapi.config.is3D, xAxisConf = iapi.getBasexAxisConf(); xAxisConf.isReverse = chartConfig.reverseXAxis; xAxisConf.axisLineColor = (0, _lib.pluck)(chartAttrs.xaxislinecolor, chartAttrs.axislinecolor, '#000000'); xAxisConf.showAlternateGridColor = (0, _lib.pluckNumber)(chartAttrs.showalternatevgridcolor, 0); xAxisConf.numDivLines = (0, _lib.pluckNumber)(chartAttrs.numvdivlines, chartConfig.numVDivLines); xAxisConf.axisName = chartAttrs.xaxisname; xAxisConf.setAdaptiveMin = (0, _lib.pluckNumber)(chartAttrs.setadaptivexmin, chartConfig.setadaptivexmin, chartConfig.setadaptivexmin); xAxisConf.showLimits = (0, _lib.pluckNumber)(chartAttrs.showvlimits, chartConfig.showvlimits); xAxisConf.showDivLineValues = (0, _lib.pluckNumber)(chartAttrs.showvdivlinevalues, chartAttrs.showvdivlinevalues, chartConfig.showvdivlinevalues); xAxisConf.zeroPlaneThickness = (0, _lib.pluckNumber)(chartAttrs.vzeroplanethickness, chartAttrs.vdivlinethickness, chartConfig.zeroplanethickness, 2); xAxisConf.zeroPlaneAlpha = (0, _lib.pluckNumber)(chartAttrs.vzeroplanealpha, chartAttrs.vdivlinealpha, chartConfig.zeroplanealpha); xAxisConf.showZeroPlaneValue = (0, _lib.pluckNumber)(chartAttrs.showvzeroplanevalue, chartConfig.showzeroplanevalue); xAxisConf.showAxisLine = is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showxaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, chartConfig.showxaxisline, 0); xAxisConf.maxLabelHeight = chartAttrs.maxlabelheight; xAxisConf.showZeroPlane = (0, _lib.pluckNumber)(chartAttrs.showvzeroplane, chartConfig.showzeroplane); return xAxisConf; }; /** * Returns y-axis configuration for chart. * @return {Object} configurations of y-axis. */ Cartesian.prototype.getSpecificyAxisConf = function getSpecificyAxisConf() { var iapi = this, chartAttrs = iapi.getFromEnv('chart-attrib'), chartConfig = iapi.config, is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, isReverse = chartConfig.isInverse, colorM = iapi.getFromEnv('color-manager'), showYAxisZeroPlane = (0, _lib.pluckNumber)(chartAttrs.showzeroplane, chartConfig.showzeroplane, 1), showYAxisZeroPlaneValue = (0, _lib.pluckNumber)(chartAttrs.showzeroplanevalue, chartConfig.showzeroplanevalue); if (!showYAxisZeroPlane && showYAxisZeroPlaneValue === UNDEF) { showYAxisZeroPlaneValue = 0; } return { isVertical: true, isReverse: !isReverse, isOpposit: false, outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisBreaks: chartAttrs.yaxisbreaks, axisNamePadding: chartAttrs.yaxisnamepadding, axisValuePadding: chartAttrs.yaxisvaluespadding, axisNameFont: chartAttrs.yaxisnamefont, axisNameFontSize: chartAttrs.yaxisnamefontsize, axisNameFontColor: chartAttrs.yaxisnamefontcolor, axisNameFontBold: chartAttrs.yaxisnamefontbold, axisNameFontItalic: chartAttrs.yaxisnamefontitalic, axisNameBgColor: chartAttrs.yaxisnamebgcolor, axisNameBorderColor: chartAttrs.yaxisnamebordercolor, axisNameAlpha: chartAttrs.yaxisnamealpha, axisNameFontAlpha: chartAttrs.yaxisnamefontalpha, axisNameBgAlpha: chartAttrs.yaxisnamebgalpha, axisNameBorderAlpha: chartAttrs.yaxisnameborderalpha, axisNameBorderPadding: chartAttrs.yaxisnameborderpadding, axisNameBorderRadius: chartAttrs.yaxisnameborderradius, axisNameBorderThickness: chartAttrs.yaxisnameborderthickness, axisNameBorderDashed: chartAttrs.yaxisnameborderdashed, axisNameBorderDashLen: chartAttrs.yaxisnameborderdashlen, axisNameBorderDashGap: chartAttrs.yaxisnameborderdashgap, axisNameWidth: chartAttrs.yaxisnamewidth, useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, rotateAxisName: (0, _lib.pluckNumber)(chartAttrs.rotateyaxisname, 1), axisName: chartAttrs.yaxisname, divLineColor: (0, _lib.pluck)(chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.divlinealpha, is3D ? colorM.getColor('divLineAlpha3D') : colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.divlinedashgap, 2), showAlternateGridColor: (0, _lib.pluckNumber)(chartAttrs.showalternatehgridcolor, 1), alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatehgridcolor, colorM.getColor('altHGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatehgridalpha, colorM.getColor('altHGridAlpha')), numDivLines: (0, _lib.pluckNumber)(chartAttrs.numdivlines, chartConfig.numDivLines), axisMinValue: chartConfig.yRangeMin || chartAttrs.yaxisminvalue, axisMaxValue: chartConfig.yRangeMax || chartAttrs.yaxismaxvalue, setAdaptiveMin: (0, _lib.pluckNumber)(chartAttrs.setadaptivesymin, chartAttrs.setadaptiveymin, chartConfig.setAdaptiveMin), adjustDiv: chartAttrs.adjustdiv, labelStep: chartAttrs.yaxisvaluesstep, showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showyaxisvalues, chartAttrs.showyaxisvalue, chartConfig.showyaxisvalues), showLimits: (0, _lib.pluckNumber)(chartAttrs.showyaxislimits, chartAttrs.showlimits, iapi.showLimits), showDivLineValues: (0, _lib.pluckNumber)(chartAttrs.showdivlinevalues, chartAttrs.showdivlinevalue, chartConfig.showdivlinevalues), showZeroPlane: showYAxisZeroPlane, zeroPlaneColor: chartAttrs.zeroplanecolor, zeroPlaneThickness: (0, _lib.pluckNumber)(chartAttrs.zeroplanethickness, chartAttrs.divlinethickness, chartConfig.zeroplanethickness, 2), zeroPlaneAlpha: (0, _lib.pluckNumber)(chartAttrs.zeroplanealpha, chartAttrs.divlinealpha, chartConfig.zeroplanealpha), showZeroPlaneValue: showYAxisZeroPlaneValue, showZeroPlaneOnTop: chartConfig.showzeroplaneontop, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, trendlineAlpha: chartAttrs.trendlinealpha, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, showAxisLine: is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showyaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, chartConfig.showyaxisline, 0), axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.yaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.yaxislinealpha, chartAttrs.axislinealpha, 100), axisLineColor: (0, _lib.pluck)(chartAttrs.yaxislinecolor, chartAttrs.axislinecolor, '#000000'), forceTrendBelow: !!chartConfig.is3D }; }; /** * Returns generic, x-axis configuration for chart. * @return {Object} configurations of x-axis. */ Cartesian.prototype.getBasexAxisConf = function getBasexAxisConf() { var iapi = this, chartAttrs = iapi.getFromEnv('chart-attrib'), is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, colorM = iapi.getFromEnv('color-manager'); return { isVertical: false, isOpposit: false, outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisNamePadding: chartAttrs.xaxisnamepadding, axisValuePadding: chartAttrs.labelpadding, axisNameFont: chartAttrs.xaxisnamefont, axisNameFontSize: chartAttrs.xaxisnamefontsize, axisNameFontColor: chartAttrs.xaxisnamefontcolor, axisNameFontBold: chartAttrs.xaxisnamefontbold, axisNameFontItalic: chartAttrs.xaxisnamefontitalic, axisNameBgColor: chartAttrs.xaxisnamebgcolor, axisNameBorderColor: chartAttrs.xaxisnamebordercolor, axisNameAlpha: chartAttrs.xaxisnamealpha, axisNameFontAlpha: chartAttrs.xaxisnamefontalpha, axisNameBgAlpha: chartAttrs.xaxisnamebgalpha, axisNameBorderAlpha: chartAttrs.xaxisnameborderalpha, axisNameBorderPadding: chartAttrs.xaxisnameborderpadding, axisNameBorderRadius: chartAttrs.xaxisnameborderradius, axisNameBorderThickness: chartAttrs.xaxisnameborderthickness, axisNameBorderDashed: chartAttrs.xaxisnameborderdashed, axisNameBorderDashLen: chartAttrs.xaxisnameborderdashlen, axisNameBorderDashGap: chartAttrs.xaxisnameborderdashgap, useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, divLineColor: (0, _lib.pluck)(chartAttrs.vdivlinecolor, chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.vdivlinealpha, chartAttrs.divlinealpha, is3D ? colorM.getColor('divLineAlpha3D') : colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.vdivlinethickness, chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.vdivlinedashed, chartAttrs.vdivlineisdashed, chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.vdivlinedashlen, chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.vdivlinedashgap, chartAttrs.divlinedashgap, 2), alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatevgridcolor, colorM.getColor('altVGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatevgridalpha, colorM.getColor('altVGridAlpha')), labelFont: chartAttrs.labelfont, labelFontSize: chartAttrs.labelfontsize, labelFontColor: chartAttrs.labelfontcolor, labelFontAlpha: chartAttrs.labelalpha, labelFontBold: chartAttrs.labelfontbold, labelFontItalic: chartAttrs.labelfontitalic, axisMinValue: chartAttrs.xaxisminvalue, axisMaxValue: chartAttrs.xaxismaxvalue, adjustDiv: chartAttrs.adjustvdiv, labelDisplay: chartAttrs.labeldisplay, showLabels: chartAttrs.showlabels, rotateLabels: chartAttrs.rotatelabels, slantLabel: (0, _lib.pluckNumber)(chartAttrs.slantlabels, chartAttrs.slantlabel), labelStep: (0, _lib.pluckNumber)(chartAttrs.labelstep, chartAttrs.xaxisvaluesstep), showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showxaxisvalues, chartAttrs.showxaxisvalue), zeroPlaneColor: chartAttrs.vzeroplanecolor, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, trendlineAlpha: chartAttrs.trendlinealpha, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.xaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.xaxislinealpha, chartAttrs.axislinealpha, 100) }; }; /** * This function return the configuration value * @param {string} confName configuration name * @return {Array} return configuration value corresponding to the confName */ Cartesian.prototype.getConfig = function getConfig(confName) { return confName ? this.config[confName] : this.config; }; /** * function to get calculate width or hieght for stacked charts * @param {number} maxAvailableSpace available space for height or width * @return {Object} contains top and right value */ Cartesian.prototype._getSumValueSpace = function _getSumValueSpace(maxAvailableSpace) { var iapi = this, dim = {}, isBar = iapi.isBar, chartAttr = iapi.getFromEnv('dataSource').chart, showSum = iapi.showsum !== 0 ? (0, _lib.pluckNumber)(chartAttr.showsum, iapi.showsum, 0) : 0, stack100Percent = (0, _lib.pluckNumber)(iapi.config.stack100percent), isStacked = iapi.config.isstacked, width = 0, i, stackManagers = [], height = 0; iapi.iterateComponents(function (child) { if (child.getName() === 'cartesianStackGroup' || child.getName() === 'marimekkoStackgroup') { stackManagers.push(child); } }); if (showSum && stack100Percent && isStacked && stackManagers.length) { for (i = stackManagers.length - 1; i >= 0; i--) { dim = stackManagers[i].getMaxSumValueSpace(); if (!isBar) { height = Math.max(height, dim.maxHeight); } else { width = Math.max(width, dim.maxWidth); } } if (height > maxAvailableSpace) { height = maxAvailableSpace; } if (width > maxAvailableSpace) { width = maxAvailableSpace; } } return { top: height, right: width }; }; // @todo remove checking for axis, ideally these fn should not get called when no axis components are present /** * Sets dimension of Axis components */ Cartesian.prototype.setAxisDimention = function setAxisDimention() { var iapi = this, xAxis = iapi.getChildren('xAxis') && iapi.getChildren('xAxis')[0], yAxis = iapi.getChildren('yAxis') && iapi.getChildren('yAxis')[0], chartConfig = iapi.getFromEnv('chartConfig'), xDepth = chartConfig.xDepth, canvasConfig = iapi.getChildren('canvas') && iapi.getChildren('canvas')[0].config, canvasBorderWidth = canvasConfig && canvasConfig.canvasBorderWidth, scrollBar = xAxis && xAxis.getChildren('scrollBar') && xAxis.getChildren('scrollBar')[0], // check if scrollbar is present, then apply the shift hasScrollBar = scrollBar && !scrollBar.getState('removed'), shift = (hasScrollBar || chartConfig.is3D) && chartConfig.shift, canvasPadding = canvasConfig && canvasConfig.canvasPadding, canvasLeft = canvasConfig.canvasLeft, canvasPaddingLeft = canvasConfig && canvasConfig.canvasPaddingLeft, canvasPaddingRight = canvasConfig && canvasConfig.canvasPaddingRight, canvasTop = canvasConfig.canvasTop, canvasPaddingTop = canvasConfig && canvasConfig.canvasPaddingTop; xAxis && xAxis.setAxisConfig({ 'canvasPaddingLeft': Math.max(canvasPaddingLeft, canvasPadding), 'canvasPaddingRight': Math.max(canvasPaddingRight, canvasPadding) }); xAxis && xAxis.setAxisDimention({ x: canvasLeft + (xDepth || 0) + Math.max(canvasPaddingLeft, canvasPadding), y: chartConfig.canvasBottom + (shift || 0) + canvasBorderWidth, opposite: canvasTop - canvasBorderWidth, axisLength: canvasConfig.canvasWidth - (xDepth || 0) - Math.max(canvasPaddingLeft, canvasPadding) - Math.max(canvasPaddingRight, canvasPadding) }); yAxis && yAxis.setAxisDimention({ x: canvasLeft - canvasBorderWidth, y: canvasTop + canvasPaddingTop, opposite: chartConfig.canvasRight + canvasBorderWidth, axisLength: chartConfig.canvasHeight - canvasPaddingTop - canvasConfig.canvasPaddingBottom }); }; /** * *@TODO needs to be validate where to place this fn * function to calculate max, min value of trendlines * @param {string} type trendline type vertical or horizontal * @param {string} axisType axis type primary or secondary * @return {Object} contains value of min and max */ Cartesian.prototype._getTrendLineMinMax = function _getTrendLineMinMax(type, axisType) { var iapi = this, trendLines = type === 'v' ? iapi.getFromEnv('dataSource').vtrendlines : iapi.getFromEnv('dataSource').trendlines, retObj = { max: -Infinity, min: Infinity }, trendLineObj, i, ii, ln, lnn; axisType = axisType || 'p'; if (trendLines) { for (i = 0, ln = trendLines.length; i < ln; i += 1) { for (ii = 0, lnn = trendLines[i].line ? trendLines[i].line.length : 0; ii < lnn; ii += 1) { trendLineObj = trendLines[i].line[ii]; if (axisType === 's' && trendLineObj.parentyaxis !== 's' || axisType !== 's' && trendLineObj.parentyaxis === 's') { continue; } retObj.max = mathMax(trendLineObj.startvalue || -Infinity, trendLineObj.endvalue || -Infinity, retObj.max); retObj.min = mathMin(trendLineObj.startvalue || Infinity, trendLineObj.endvalue || Infinity, retObj.min); } } } return retObj; }; return Cartesian; }(_commonspacemanager2['default']); exports['default'] = Cartesian; /***/ }), /* 361 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _commonchartapi = __webpack_require__(362); var _commonchartapi2 = _interopRequireDefault(_commonchartapi); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var CommonSpaceManager = function (_CommonAPI) { _inherits(CommonSpaceManager, _CommonAPI); function CommonSpaceManager() { _classCallCheck(this, CommonSpaceManager); return _possibleConstructorReturn(this, _CommonAPI.apply(this, arguments)); } /** * calculate and allote space for various components * every components are get notified with maximum space and then components return * the available space. */ CommonSpaceManager.prototype._spaceManager = function _spaceManager() { // todo marge _allocateSpace and _spacemanager var availableWidth, availableHeight, iapi = this, config = iapi.config, xAxis = iapi.getChildren('xAxis') && iapi.getChildren('xAxis')[0], yAxisArr = iapi.getChildren('yAxis') && iapi.getChildren('yAxis') || [], yAxis, len, legendPosition = config.legendposition, xDepth = config.xDepth, yDepth = config.yDepth, canvasBgDepth = config.canvasBgDepth, allottedSpace, canvasBaseDepth = config.canvasBaseDepth, canvasBasePadding = config.canvasBasePadding, canvas = iapi.getChildren('canvas')[0], canvasBorderWidth = canvas.config.canvasBorderWidth, showRTValue = config.realTimeConfig && config.realTimeConfig.showRTValue, chartBorderWidth = config.borderWidth, canvasMarginTop = config.canvasMarginTop, canvasMarginBottom = config.canvasMarginBottom, canvasMarginLeft = config.canvasMarginLeft, canvasMarginRight = config.canvasMarginRight, minCanvasHeight = config.minCanvasHeight, minCanvasWidth = config.minCanvasWidth, minChartWidth = config.minChartWidth, minChartHeight = config.minChartHeight, height = config.height, width = config.width, diff, heightAdjust = false, widthAdjust = false, top, bottom, left, right, i, currentCanvasHeight, currentCanvasWidth, origCanvasTopMargin = config.origCanvasTopMargin, origCanvasBottomMargin = config.origCanvasBottomMargin, origCanvasLeftMargin = config.origCanvasLeftMargin, origCanvasRightMargin = config.origCanvasRightMargin, chartBorderHorizontal, chartBorderVertical, canvasBorderHorizontal, canvasBorderVertical, yAxisSpaceAllocation = [], xAxisSpaceAllocation, spaceTakenByAxis, sum; if (config.canvasWidth - 2 * chartBorderWidth < minChartWidth) { chartBorderVertical = (config.canvasWidth - minChartWidth) / 2; } if (config.canvasHeight - 2 * chartBorderWidth < minChartHeight) { chartBorderHorizontal = (config.canvasHeight - minChartHeight) / 2; } iapi._allocateSpace({ top: chartBorderHorizontal || chartBorderWidth, bottom: chartBorderHorizontal || chartBorderWidth, left: chartBorderVertical || chartBorderWidth, right: chartBorderVertical || chartBorderWidth }); for (i = 0, len = yAxisArr.length; i < len; i++) { yAxis = yAxisArr[i]; //* ***** Manage space availableWidth = config.availableWidth * 0.7; spaceTakenByAxis = yAxis && yAxis.placeAxis(availableWidth) || {}; yAxisSpaceAllocation.push({ axisIndex: i, spaceTaken: spaceTakenByAxis }); yAxis && iapi._allocateSpace(spaceTakenByAxis); } config.yAxisSpaceAllocation = yAxisSpaceAllocation; iapi._allocateSpace(iapi._manageActionBarSpace && iapi._manageActionBarSpace(config.availableHeight * 0.225) || {}); // No space is allocated for legend drawing in single series charts iapi._manageLegendSpace && config.showLegend && iapi._manageLegendSpace(allottedSpace); availableHeight = legendPosition === _lib.POSITION_BOTTOM ? config.availableHeight * 0.6 : config.availableWidth * 0.6; // space management for 3d canvas if (yDepth) { iapi._allocateSpace({ bottom: yDepth }); config.shift = xDepth + canvasBasePadding + canvasBaseDepth; } if (canvasBgDepth) { iapi._allocateSpace({ right: canvasBgDepth }); } if (config.canvasWidth - 2 * canvasBorderWidth < minCanvasWidth) { canvasBorderVertical = (config.canvasWidth - minCanvasWidth) / 2; } iapi._allocateSpace({ left: canvasBorderVertical || canvasBorderWidth, right: canvasBorderVertical || canvasBorderWidth }); // Check for minimun canvas width for applying canvas left and right margin. if (minCanvasWidth > width - canvasMarginLeft - canvasMarginRight) { widthAdjust = true; diff = config.canvasWidth - minCanvasWidth; sum = canvasMarginLeft + canvasMarginRight; canvasMarginLeft = config.canvasMarginLeft = diff * canvasMarginLeft / sum; canvasMarginRight = config.canvasMarginRight = diff * canvasMarginRight / sum; } // Calculating the left and right canvas margin. left = canvasMarginLeft > config.canvasLeft ? canvasMarginLeft - config.canvasLeft : 0; right = canvasMarginRight > width - config.canvasRight ? canvasMarginRight + config.canvasRight - width : 0; iapi._allocateSpace({ left: left, right: right }); // Forcing canvas width to its minimum if (widthAdjust) { sum = origCanvasLeftMargin + origCanvasRightMargin; currentCanvasWidth = config.canvasWidth; if (currentCanvasWidth > minCanvasWidth) { diff = currentCanvasWidth - minCanvasWidth; left = diff * origCanvasLeftMargin / sum; right = diff * origCanvasRightMargin / sum; } iapi._allocateSpace({ left: left, right: right }); } config.actualCanvasMarginRight = right; config.actualCanvasMarginBottom = bottom; // a space manager that manages the space for the tools as well as the captions. iapi._manageChartMenuBar(availableHeight); availableHeight = config.availableHeight * 0.2; iapi._getSumValueSpace && iapi._allocateSpace(iapi._getSumValueSpace(availableHeight)); availableHeight = config.availableHeight * 0.3; if (config.realtimeEnabled) { if (showRTValue) { iapi._allocateSpace(iapi._realTimeValuePositioning(availableHeight)); } else { iapi._hideRealTimeValue(); } } iapi._resetViewPortConfig && iapi._resetViewPortConfig(); iapi._setAxisScale && iapi._setAxisScale(); availableHeight = config.availableHeight * 0.6; config.xAxisSpaceAllocation = xAxisSpaceAllocation = xAxis && xAxis.placeAxis(availableHeight); xAxis && iapi._allocateSpace(xAxisSpaceAllocation); if (config.canvasHeight - 2 * canvasBorderWidth < minCanvasHeight) { canvasBorderHorizontal = (config.canvasHeight - minCanvasHeight) / 2; } iapi._allocateSpace({ top: canvasBorderHorizontal || canvasBorderWidth, bottom: canvasBorderHorizontal || canvasBorderWidth }); iapi._allocateSpace({ bottom: canvasBaseDepth }); // Check for minimum canvas height for applying top and bottom margin. if (minCanvasHeight > height - canvasMarginTop - canvasMarginBottom) { heightAdjust = true; diff = config.canvasHeight - minCanvasHeight; sum = canvasMarginTop + canvasMarginBottom; canvasMarginTop = config.canvasMarginTop = diff * canvasMarginTop / sum; canvasMarginBottom = config.canvasMarginBottom = diff * canvasMarginBottom / sum; } // Allocate space for canvas margin only if the margin is less than the margin entered by the user. top = canvasMarginTop > config.canvasTop ? canvasMarginTop - config.canvasTop : 0; bottom = canvasMarginBottom > height - config.canvasBottom ? canvasMarginBottom + config.canvasBottom - height : 0; iapi._allocateSpace({ top: top, bottom: bottom }); // Forcing canvas height to its minimum if (heightAdjust) { sum = origCanvasTopMargin + origCanvasBottomMargin; currentCanvasHeight = config.canvasHeight; if (currentCanvasHeight > minCanvasHeight) { diff = currentCanvasHeight - minCanvasHeight; top = diff * origCanvasTopMargin / sum; bottom = diff * origCanvasBottomMargin / sum; } iapi._allocateSpace({ top: top, bottom: bottom }); } config.actualCanvasMarginTop = top; config.actualCanvasMarginLeft = left; canvas.setDimension({ top: config.canvasTop, left: config.canvasLeft, width: config.canvasWidth, height: config.canvasHeight }); }; /** * function to calculate post space management calculations * calculations like axis dimenetion set, allocate space for xaxis labels, * canvas padding etc. */ CommonSpaceManager.prototype._postSpaceManagement = function _postSpaceManagement() { // this method is not called for charts athat do not have axis var iapi = this, config = iapi.config, components = iapi.getChildren(), xAxis = components.xAxis && components.xAxis[0], legend = components.legend && components.legend[0], xDepth = config.xDepth, i, canvas, canvasArr = iapi.getChildren('canvas'); iapi.setAxisDimention && iapi.setAxisDimention(); xAxis && iapi._allocateXAxisLabelSpace(xAxis); xAxis && xAxis.shiftLabels(-xDepth, 0); legend && legend.postSpaceManager(); for (i = 0; i < (canvasArr && canvasArr.length); i++) { canvas = canvasArr[i]; // function for adjusting value padding depending upon data and axis labels. canvas.setCanvasPadding(); } // Re-set the dimension after setting the canvas padding iapi.setAxisDimention && iapi.setAxisDimention(); iapi.allocateDimensionOfChartMenuBar(); }; return CommonSpaceManager; }(_commonchartapi2['default']); exports['default'] = CommonSpaceManager; /***/ }), /* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.configurer = exports._createToolBox = exports._drawDataset = undefined; var _baseChart = __webpack_require__(161); var _baseChart2 = _interopRequireDefault(_baseChart); var _canvas = __webpack_require__(363); var _canvas2 = _interopRequireDefault(_canvas); var _dependencyManager = __webpack_require__(132); var _caption = __webpack_require__(366); var _caption2 = _interopRequireDefault(_caption); var _subCaption = __webpack_require__(368); var _subCaption2 = _interopRequireDefault(_subCaption); var _background = __webpack_require__(370); var _background2 = _interopRequireDefault(_background); var _colormanager = __webpack_require__(372); var _colormanager2 = _interopRequireDefault(_colormanager); var _numberFormatter = __webpack_require__(147); var _numberFormatter2 = _interopRequireDefault(_numberFormatter); var _eventApi = __webpack_require__(131); var _common = __webpack_require__(375); var _common2 = _interopRequireDefault(_common); var _lib = __webpack_require__(125); var _domEvent = __webpack_require__(127); var _domEvent2 = _interopRequireDefault(_domEvent); var _toolbox = __webpack_require__(228); var _helper = __webpack_require__(232); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ // import AlertManagerClass from '../components/alertmanager'; // import MouseTracker from '../components/mouse-tracker'; var Raphael = (0, _dependencyManager.getDep)('redraphael', 'plugin'), isVML = Raphael.type === 'VML', // TRACKER_FILL = 'rgba(255,0,0,' + (isIE ? 0.002 : 0.000001) + ')', // invisible but clickable mathMax = Math.max, mathMin = Math.min, mathRound = Math.round, eventMap = { 'datalabelclick': true, 'connectorclick': true, 'categoryclick': true, 'processclick': true, 'milestoneclick': true, 'labelclick': true, 'dataplotclick': true }, SEVENTYSTRING = _lib.preDefStr.SEVENTYSTRING, AUTO = _lib.preDefStr.AUTOSTRING, BOLD = 'bold', NORMAL = 'normal', POSITION_RIGHT = 'right', supportsPointer = 'onpointerover' in window.document, // POSITION_LEFT = 'left', // POSITION_CENTER = 'center', // POSITION_TOP = 'top', // POSITION_BOTTOM = 'bottom', // POSITION_MIDDLE = 'middle', POSITION_START = 'start', POSITION_END = 'end', assign = function assign() { for (var _len = arguments.length, param = Array(_len), _key = 0; _key < _len; _key++) { param[_key] = arguments[_key]; } var src = param[0], trgts = param.slice(1); trgts.forEach(function (trgt) { for (var key in trgt) { if (trgt.hasOwnProperty(key) && trgt[key] !== undefined) { src[key] = trgt[key]; } } }); return src; }, /** * Helper function to create a RedRaphael group. * @param {Object} attrs Attributes to be applied to the created group. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} chart The chart API * @return {Element} The group that was created. */ createGroup = function createGroup(attrs, parentContainer, chart) { var animationManager = chart.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: attrs, container: parentContainer, state: 'appearing', component: chart, label: 'group' }); }, /** * Helper function of triger chartclick when it is not followed by any drag activity * @param {Object} e The Event obect. */ _registerMouseDown = function _registerMouseDown(e) { var config = e.data.config; config._containerMouseState = 'mousedown'; // Storing the mouse down coordinates config._mdx1 = e.clientX !== _lib.UNDEF ? e.clientX : e.changedTouches && e.changedTouches[0].clientX; config.mdy1 = e.clientY !== _lib.UNDEF ? e.clientY : e.changedTouches && e.changedTouches[0].clientY; // Storing the time when touchstart started e.type === 'touchstart' && (config._touchStartedAt = new Date().getTime()); }, /** * Helper function of triger chartclick when it is not followed by any drag activity * @param {Object} e The Event obect. */ _registerMouseMove = function _registerMouseMove(e) { var config = e.data.config, x2 = e.clientX !== _lib.UNDEF ? e.clientX : e.changedTouches && e.changedTouches[0].clientX, y2 = e.clientY !== _lib.UNDEF ? e.clientY : e.changedTouches && e.changedTouches[0].clientY; // maintaning a minimum pixel gap of 2.5 to trigger mousemove if (Math.abs(config._mdx1 - x2) >= 2.5 || Math.abs(config.mdy1 - y2) >= 2.5) { e.data.config._containerMouseState = undefined; } }, /** * Helper function for ios click * @param {Object} e The Event obect. */ _onContainerClickIOS = function _onContainerClickIOS(e) { // We have to make sure that it is not a long tap if (new Date().getTime() - e.data.config._touchStartedAt < 500) { setTimeout(function () { onContainerClick(e); }); } }, onContainerClick = function onContainerClick(e) { var chart = e.data, fusionCharts = chart.getFromEnv('chartInstance'), oriEvent = e.originalEvent, config = chart.config, coordinate = (0, _lib.getMouseCoordinate)(chart.getFromEnv('chart-container'), oriEvent, chart), args; // If the last event was mousemove then do not trigger click if (!fusionCharts.ref || config._containerMouseState === 'mousemove') { return; } args = (0, _lib.extend2)({ height: fusionCharts.args.height, width: fusionCharts.args.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: fusionCharts.args.id, renderer: fusionCharts.args.renderer, container: fusionCharts.options.containerElement }, coordinate); /** * This event is fired when the chart is clicked. For touch devices, this event is fired when user * taps on the chart. * * This event provides useful information on the position of mouse relative to the chart and the page. * This can be used to position things like annotations based on where the chart is clicked. * * @see FusionCharts#event:chartRollOver * @see FusionCharts#event:chartRollOut * @see FusionCharts#event:chartMouseMove * * @event FusionCharts#chartClick * @since 3.4.0 * @group chart * * @param {string} container - The DOM element within which the chart has been rendered. * @param {string} id - The `id` of the chart that has triggered this event. * * @param {string} height - The height of the chart specified at the time of rendering the chart in * pixels or percent. * @param {string} width - The width of the chart specified at the time of rendering the chart in pixels * or percent. * * @param {number} chartX - The x-coordinate of the mouse relative to the position of the chart. * @param {number} chartY - The y-coordinate of the mouse relative to the position of the chart. * * @param {number} pageX - The x-coordinate of the mouse relative to the document. * @param {number} pageY - The y-coordinate of the mouse relative to the document. * * @param {number} pixelHeight - The height of the chart in pixels. This is equivalent to the * `offsetHeight` of the chart container. * @param {number} pixelWidth - The width of the chart in pixels. This is equivalent to the * `offsetWidth` of the chart container. * * @example * FusionCharts.ready(function () { * var chart = new FusionCharts({ * type: 'column2d', * dataFormat: 'jsonurl', * dataSource: 'chart-data.json', * renderAt: 'chart-container-div', * * events: { * chartClick: function (eventObj, argsObj) { * console.log('Chart clicked at ' + argsObj.chartX + ',' + argsObj.chartY); * } * } * }); * * chart.render(); * }); */ chart.fireChartInstanceEvent('chartclick', args); // If link is present at chart level and // If previously any hot element (clickable graphics) is clicked and clickURLOverridesPlotLinks is set true // then fire chart click or // If hotElemClicked is not clicked then fire chart click config.link && (config.hotElemClicked ? config.clickURLOverridesPlotLinks : true) && chart.getFromEnv('linkClickFN').call({ link: config.link }); config.hotElemClicked = false; }, chartHoverManager = function chartHoverManager(e) { var type = e.type, chart = e.data, listeners = chart.getFromEnv('eventListeners'); // rollover if ((type === 'mouseover' || type === 'touchstart') && chart.config.mouseStateIn === false) { chart.config.mouseStateIn = true; CommonAPI.onContainerRollOver(e); // On mouse rollover on the chart, attach window mouseover event listeners.push(_domEvent2['default'].listen(isVML ? document : window, 'mouseover', CommonAPI.winMouseHover, chart)); } }, toolbarPositionParser = function toolbarPositionParser(position) { switch (position) { case 'tr': case 'rt': case 'top right': case 'right top': position = 'tr'; break; case 'br': case 'rb': case 'bottom right': case 'right bottom': position = 'br'; break; case 'tl': case 'lt': case 'top left': case 'left top': position = 'tl'; break; case 'bl': case 'lb': case 'bottom left': case 'left bottom': position = 'bl'; break; default: position = 'tr'; } return position; }; /** * Create a toolbox with a context menu. * Add context menus for export and print options if enabled. * Create the chart Menu bar as a chart component. */ function _createToolBox2() { var chart = this, iapi = this, rtConfig = void 0, config = chart.config, chartAttrs = chart.getFromEnv('chart-attrib'), toolBarType = config.toolbarVAlign === 't' ? 'chartMenuBar' : 'actionBar', removeTBType = config.toolbarVAlign === 't' ? 'actionBar' : 'chartMenuBar', toolBar = void 0, hamburgerMenu = void 0, toolConf = chart.getFromEnv('tool-config'), printEnabled = config.printOption.enabled; rtConfig = iapi.config.realTimeConfig || {}; (0, _lib.componentFactory)(chart, _toolbox.ToolBar, removeTBType, 0, [chartAttrs]); (0, _lib.componentFactory)(chart, _toolbox.ToolBar, toolBarType, 1, [chartAttrs]); toolBar = chart.getChildren(toolBarType)[0]; chart.addToEnv('toolbar', toolBar); _helper.SymbolStore.register('ContextIcon', function (posx, posy, rad) { var x = posx, y = posy, r = rad * 2, space = mathRound(r / 4), halfWidth = mathRound(r / 2) * 0.7, startX = x - halfWidth, endX = x + halfWidth, startY = y + space, endY = y - space; return ['M', startX, y, 'L', endX, y, 'M', startX, startY, 'L', endX, startY, 'M', startX, endY, 'L', endX, endY]; }); hamburgerMenu = toolBar.attachChild(_toolbox.Hamburger, 'tool', 'hamburgerMenu-' + toolBar.getId() + '-' + chart.getId() + '-0'); chart.addToEnv('hamburger', hamburgerMenu); hamburgerMenu.configure(Object.assign({}, toolConf, { name: 'ContextIcon' })); hamburgerMenu._mouseOutEvent || (hamburgerMenu._mouseOutEvent = function () { this.getChild('listContainer').hide(); }); hamburgerMenu._mouseOverEvent || (hamburgerMenu._mouseOverEvent = function () { this.getChild('listContainer').show(); }); hamburgerMenu.addEventListener('fc-mouseover', hamburgerMenu._mouseOverEvent); hamburgerMenu.addEventListener('fc-mouseout', hamburgerMenu._mouseOutEvent); if (printEnabled) { hamburgerMenu.appendInMenu([{ name: 'Print', action: 'click', handler: function handler() { chart.getFromEnv('chartInstance').print(); } }]); } iapi._setRTmenu && iapi._setRTmenu(rtConfig.showRTmenuItem, rtConfig.useMessageLog); } /** * *@TODO this function should be removed after validating the realtime charts */ function _drawDataset() { var iapi = this, canvas = iapi.getChildren('canvas')[0]; canvas._mapChildren(function (child) { child.syncDraw(); }); } /** * Configures the chart component * @param {Object} dataObj User input json */ function configurer(dataObj) { var iapi = this; iapi.config.skipConfigureIteration = {}; iapi.parseChartAttr(dataObj); iapi.createComponent(dataObj); iapi._createToolBox(); iapi.setTooltipStyle(); iapi.configureChildren(); // after configure chart calls its async draw // iapi.asyncDraw(); } (0, _dependencyManager.addDep)({ name: 'commonAnimation', type: 'animationRule', extension: _common2['default'] }); /** * Base class for all cartesian charts and who depend on this class * Its not an standalone chart * @type {class} */ var CommonAPI = function (_BaseChart) { _inherits(CommonAPI, _BaseChart); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ CommonAPI.getName = function getName() { return 'CommonAPI'; }; /** * Function to handle various events related to data plots * @param {Object} elem The element on which the interaction is done * @param {Object} event The event object * @param {String} eventName The event's name that is to be raised * @param {Object} eventArguments The arguments passed in the event */ CommonAPI.prototype.plotEventHandler = function plotEventHandler(elem) { var event = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var eventName = arguments[2]; var eventArguments = arguments[3]; var chart = this, eventType = event.type, coordinate = (0, _lib.getMouseCoordinate)(chart.getFromEnv('chart-container'), event, chart), eventArgs = elem && elem.data('eventArgs') || eventArguments, args = (0, _lib.extend2)(coordinate, eventArgs), fireGroupEvent = chart.fireGroupEvent, env, linkClickFN, id = elem && elem.data('groupId'), // eslint-disable-next-line no-unused-vars cancelHover = function cancelHover(c, a) { event.FusionChartsPreventEvent = true; // Hack for IE as the global event object gets overwritten // causing the FusionChartsPreventEvent to be UNDEF. // todo - rectify this commented code. /* if (isIE && a.toolText && lib.toolTip) { lib.toolTip.preventTooltip(); } */ }; if ('index' in args && !('dataIndex' in args)) { args.dataIndex = args.index; } if ('value' in args && !('dataValue' in args)) { args.dataValue = args.value; } eventName = (0, _lib.pluck)(eventName, 'dataplotclick').toLowerCase(); // preventDefault in DataPlotRollOver if (eventName === 'dataplotrollover') { event.FusionChartsPreventEvent = false; if (fireGroupEvent) { /** * @event FusionCharts#dataplotRollOver * * @param {number} chartX - x-coordinate of the pointer relative to the chart. * @param {number} chartY - y-coordinate of the pointer relative to the chart. * @param {number} pageX - x-coordinate of the pointer relative to the page. * @param {number} pageY - y-coordinate of the pointer relative to the page. * @param {number} datasetIndex - The position of the dataset in order of its definition in source * data. * @param {string} datasetName - The `seriesName` of the dataset. * @param {number} dataIndex - The position of the data-plot in order of its definition in source * dataset. * @param {number} dataValue - The value of the data-plot that trigerred this event * @param {string} displayValue - The `displayValue` attribute that has been set for the data-plot. * @param {string} categoryLabel - The x-axis label that corresponds to the data-plot * @param {string} toolText - The tooltext that is displayed when hovered over the data-plot */ (0, _eventApi.raiseEventGroup)(id, eventName, args, chart.getFromEnv('chartInstance'), _lib.UNDEF, _lib.UNDEF, cancelHover); } else { chart.fireChartInstanceEvent(eventName, args, _lib.UNDEF, _lib.UNDEF, cancelHover); } } else { if (fireGroupEvent && !eventMap[eventName]) { /** * @event FusionCharts#dataplotRollOut * * @param {number} chartX - x-coordinate of the pointer relative to the chart. * @param {number} chartY - y-coordinate of the pointer relative to the chart. * @param {number} pageX - x-coordinate of the pointer relative to the page. * @param {number} pageY - y-coordinate of the pointer relative to the page. * @param {number} datasetIndex - The position of the dataset in order of its definition in source * data. * @param {string} datasetName - The `seriesName` of the dataset. * @param {number} dataIndex - The position of the data-plot in order of its definition in source * dataset. * @param {number} dataValue - The value of the data-plot that trigerred this event * @param {string} displayValue - The `displayValue` attribute that has been set for the data-plot. * @param {string} categoryLabel - The x-axis label that corresponds to the data-plot * @param {string} toolText - The tooltext that is displayed when hovered over the data-plot */ (0, _eventApi.raiseEventGroup)(id, eventName, args, chart.getFromEnv('chartInstance')); } else { /** * @event FusionCharts#dataplotClick * * @param {number} chartX - x-coordinate of the pointer relative to the chart. * @param {number} chartY - y-coordinate of the pointer relative to the chart. * @param {number} pageX - x-coordinate of the pointer relative to the page. * @param {number} pageY - y-coordinate of the pointer relative to the page. * @param {number} datasetIndex - The position of the dataset in order of its definition in source * data. * @param {string} datasetName - The `seriesName` of the dataset. * @param {number} dataIndex - The position of the data-plot in order of its definition in source * dataset. * @param {number} dataValue - The value of the data-plot that trigerred this event * @param {string} displayValue - The `displayValue` attribute that has been set for the data-plot. * @param {string} categoryLabel - The x-axis label that corresponds to the data-plot * @param {string} toolText - The tooltext that is displayed when hovered over the data-plot */ chart.fireChartInstanceEvent(eventName, args); } } if ((eventType === 'fc-click' || eventType === 'click' || eventType === 'mouseup' || eventType === 'touchend') && /click/i.test(eventName)) { // when chart is getting disposed need to check if env is present env = chart.getFromEnv(); linkClickFN = env && env.linkClickFN; args.link && linkClickFN && linkClickFN.call({ link: args.link }, true); } }; /** * constructor function of this class */ function CommonAPI() { _classCallCheck(this, CommonAPI); var _this = _possibleConstructorReturn(this, _BaseChart.call(this)); _this.addToEnv('stringConstants', { COMPONENT: 'component', CANVAS: 'canvas', CAPTION: 'caption' }); _this.addToEnv('getMouseCoordinate', _lib.getMouseCoordinate); _this._drawDataset = _drawDataset; _this.config.mouseStateIn = false; _this.registerFactory('canvas', _canvas2['default']); _this._firstConfigure = true; return _this; } /** * Sets the name of the component * @return {string} name */ CommonAPI.prototype.getName = function getName() { return 'Cartesian'; }; /** * function to preconfigure chart API * @param {Object} dataObj input json data */ CommonAPI.prototype.preConfigure = function preConfigure(dataObj) { var nf = this.getFromEnv('number-formatter'); // Add chartAttrs in the env this.addToEnv('chart-attrib', dataObj.chart); nf ? nf.configure() : this.addToEnv('number-formatter', new _numberFormatter2['default'](this)); _BaseChart.prototype.preConfigure.call(this, dataObj); }; /** * function to postconfigure chart API * @param {Object} dataObj - input json data */ CommonAPI.prototype.postConfigure = function postConfigure(dataObj) { _BaseChart.prototype.postConfigure.call(this, dataObj); this._firstConfigure = false; }; /** * restores the default configuration which are directly child of chart */ CommonAPI.prototype.setDefaults = function setDefaults() { _BaseChart.prototype.setDefaults.call(this); var nf = this.getFromEnv('number-formatter'); nf && nf.setDefaults && nf.setDefaults(); }; /** * Returns the type of the component * * @return {string} The type of the component */ CommonAPI.prototype.getType = function getType() { return 'chartAPI'; }; /** * Parse the chart attributes and store in chart's config * @param {Object} dataObj User input json */ CommonAPI.prototype.parseChartAttr = function parseChartAttr(dataObj) { var iapi = this, jsonData = dataObj || iapi.getFromEnv('dataSource'), chartAttrs = void 0, is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, config = void 0, isBar = iapi.isBar, inCanfontFamily = void 0, inCanfontSize = void 0, inCancolor = void 0, fontSize = void 0, colorM = iapi.getFromEnv('color-manager'), style = void 0, zeroPlaneColor = void 0, zeroPlaneAlpha = void 0, inCanvasStyle = void 0, inCanLineHeight = void 0, dataLabelStyle = void 0, fontBdrColor = void 0, showCanvasBase = void 0; if (!colorM) { colorM = new _colormanager2['default'](iapi); iapi.addToEnv('color-manager', colorM); } jsonData.chart = jsonData.chart || jsonData.graph || jsonData.map || {}; delete jsonData.map; delete jsonData.graph; chartAttrs = jsonData.chart; !chartAttrs && (chartAttrs = jsonData.chart = {}); config = iapi.config || (iapi.config = {}); (0, _lib.parseConfiguration)(chartAttrs, config, {}, { 'showvalues': true, 'crosslinecolor': true, 'drawcrosslineontop': true, 'crosslinealpha': true, 'drawcrossline': true }); config.showValues = (0, _lib.pluckNumber)(chartAttrs.showvalues, config.showvalues); // set the configuration for zooming config.viewPortConfig = { 'scaleY': 1, 'scaleX': 1, 'x': 0, 'y': 0 }; iapi.addToEnv('tool-config', assign({}, { scale: chartAttrs.toolbarbuttonscale, width: chartAttrs.toolbarbuttonwidth, height: chartAttrs.toolbarbuttonheight, radius: chartAttrs.toolbarbuttonradius, spacing: chartAttrs.toolbarbuttonspacing, marginTop: chartAttrs.toolbarbuttonmargintop, marginLeft: chartAttrs.toolbarbuttonmarginleft, marginRight: chartAttrs.toolbarbuttonmarginright, marginBottom: chartAttrs.toolbarbuttonmarginbottom, fill: chartAttrs.toolbarbuttoncolor, labelFill: chartAttrs.toolbarlabelcolor, symbolFill: chartAttrs.toolbarsymbolcolor, hoverFill: chartAttrs.toolbarbuttonhovercolor, stroke: chartAttrs.toolbarbuttonbordercolor, symbolStroke: chartAttrs.toolbarsymbolbordercolor, strokeWidth: chartAttrs.toolbarbuttonborderthickness, symbolStrokeWidth: chartAttrs.toolbarsymbolborderthickness, bSymbolPadding: chartAttrs.toolbarsymbolpadding, symbolHPadding: chartAttrs.toolbarsymbolhpadding, symbolVPadding: chartAttrs.toolbarsymbolvpadding, hAlign: chartAttrs.toolbarhalign, vAlign: chartAttrs.toolbarvalign })); // parse all 3d canvas attributes if (is3D) { if (isBar) { config.xDepth = 5; config.yDepth = 5; } else { config.xDepth = 10; config.yDepth = 10; } config.showCanvasBase = showCanvasBase = Boolean((0, _lib.pluckNumber)(chartAttrs.showcanvasbase, 1)); config.canvasBasePadding = (0, _lib.pluckNumber)(chartAttrs.canvasbasepadding, 2); config.canvasBaseDepth = showCanvasBase ? (0, _lib.pluckNumber)(chartAttrs.canvasbasedepth, 10) : 0; config.canvasBgDepth = (0, _lib.pluckNumber)(chartAttrs.canvasbgdepth, 3); } colorM && colorM.configure(); config.placeAxisLabelsOnTop = (0, _lib.pluckNumber)(chartAttrs.placexaxislabelsontop, 0); config.enableAnimation = (0, _lib.pluckNumber)(chartAttrs.animation, chartAttrs.defaultanimation, 1); config.showToolTip = (0, _lib.pluckNumber)(chartAttrs.showtooltip, 1); config.printOption = { enabled: (0, _lib.pluckNumber)(chartAttrs.printshowbutton, chartAttrs.showprintmenuitem, 0) }; config.drawCrossLineOnTop = (0, _lib.pluckNumber)(chartAttrs.drawcrosslineontop, 1); style = config.style = {}; // expose to environment // TODO: needs to be mo re clear. So that only one set of style is available in each level iapi.addToEnv('style', style); config.textDirection = chartAttrs.hasrtltext === '1' ? 'rtl' : _lib.BLANKSTRING; // ////////Chart font style//////////////////// // todo: init incanstyle, outcanstyle, captionStyle, subcaption style style.inCanfontFamily = inCanfontFamily = (0, _lib.pluck)(chartAttrs.basefont, 'Verdana,sans'); style.inCanfontSize = inCanfontSize = (0, _lib.pluckFontSize)(chartAttrs.basefontsize, 10); style.inCancolor = inCancolor = (0, _lib.pluck)(chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)); style.outCanfontFamily = (0, _lib.pluck)(chartAttrs.outcnvbasefont, inCanfontFamily); style.fontSize = fontSize = (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, inCanfontSize); style.outCanfontSize = fontSize + _lib.PXSTRING; style.outCancolor = (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, inCancolor).replace(/^#? ([a-f0-9]+)/ig, '#$1'); style.baseFontSize = inCanfontSize; style.inCanfontSize = inCanfontSize + _lib.PXSTRING; style.inCancolor = inCancolor.replace(/^#? ([a-f0-9]+)/ig, '#$1'); style.inCanvasStyle = inCanvasStyle = { fontFamily: inCanfontFamily, fontSize: inCanfontSize, color: inCancolor }; style.inCanLineHeight = inCanLineHeight = (0, _lib.setLineHeight)(inCanvasStyle); fontBdrColor = (0, _lib.getFirstValue)(chartAttrs.valuebordercolor, _lib.BLANKSTRING); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(chartAttrs.valueborderalpha, chartAttrs.valuealpha, 100)) : _lib.BLANKSTRING; config.reverseXAxis = iapi.config.allowreversexaxis && (0, _lib.pluckNumber)(chartAttrs.reversexaxis, 0); config.showBorder = (0, _lib.pluckNumber)(chartAttrs.showborder, is3D ? 0 : 1); config.borderWidth = mathMax(config.showBorder ? (0, _lib.pluckNumber)(chartAttrs.borderthickness, 1) : 0, 0); config.useplotgradientcolor = (0, _lib.pluckNumber)(chartAttrs.plotgradientcolor, config.useplotgradientcolor, 0); config.valuefontbold = (0, _lib.pluckNumber)(chartAttrs.valuefontbold, config.valuefontbold); config.dataLabelStyle = dataLabelStyle = { fontFamily: (0, _lib.pluck)(chartAttrs.valuefont, inCanfontFamily), fontSize: (0, _lib.pluck)(chartAttrs.valuefontsize, (0, _lib.pInt)(inCanfontSize, 10)) + _lib.PXSTRING, lineHeight: inCanLineHeight, color: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.valuefontcolor, inCancolor), (0, _lib.pluckNumber)(chartAttrs.valuefontalpha, chartAttrs.valuealpha, 100)), fontWeight: config.valuefontbold ? BOLD : NORMAL, fontStyle: (0, _lib.pluckNumber)(chartAttrs.valuefontitalic) ? 'italic' : NORMAL, // Set border as empty string when not required, // since IE will stop js execution if it is UNDEF or null. border: fontBdrColor || chartAttrs.valuebgcolor ? (0, _lib.pluckNumber)(chartAttrs.valueborderthickness, 1) + 'px solid' : _lib.BLANKSTRING, borderColor: fontBdrColor, borderThickness: (0, _lib.pluckNumber)(chartAttrs.valueborderthickness, 1), borderPadding: (0, _lib.pluckNumber)(chartAttrs.valueborderpadding, 2), borderRadius: (0, _lib.pluckNumber)(chartAttrs.valueborderradius, 0), backgroundColor: chartAttrs.valuebgcolor ? (0, _lib.convertColor)(chartAttrs.valuebgcolor, (0, _lib.pluckNumber)(chartAttrs.valuebgalpha, chartAttrs.valuealpha, 100)) : _lib.BLANKSTRING, borderDash: (0, _lib.pluckNumber)(chartAttrs.valueborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttrs.valueborderdashlen, 4), (0, _lib.pluckNumber)(chartAttrs.valueborderdashgap, 2)) : _lib.DASH_DEF }; (0, _lib.setLineHeight)(dataLabelStyle); config.legendposition = (0, _lib.pluck)(chartAttrs.legendposition, _lib.POSITION_BOTTOM); config.alignLegendWithCanvas = (0, _lib.pluckNumber)(chartAttrs.alignlegendwithcanvas, 1); // chart margins config.origMarginTop = (0, _lib.pluckNumber)(chartAttrs.charttopmargin, iapi.chartTopMargin, 15); config.origMarginLeft = (0, _lib.pluckNumber)(chartAttrs.chartleftmargin, iapi.chartLeftMargin, 15); config.origMarginBottom = (0, _lib.pluckNumber)(chartAttrs.chartbottommargin, iapi.chartBottomMargin, 15); config.origMarginRight = (0, _lib.pluckNumber)(chartAttrs.chartrightmargin, iapi.chartRightMargin, 15); config.origCanvasLeftMargin = (0, _lib.pluckNumber)(chartAttrs.canvasleftmargin, 0); config.origCanvasRightMargin = (0, _lib.pluckNumber)(chartAttrs.canvasrightmargin, 0); config.origCanvasTopMargin = (0, _lib.pluckNumber)(chartAttrs.canvastopmargin, 0); config.origCanvasBottomMargin = (0, _lib.pluckNumber)(chartAttrs.canvasbottommargin, 0); // Parsing space management attributes config.minChartWidthPercent = (0, _lib.pluckNumber)(chartAttrs.minchartwidth, iapi.minChartWidth, 50) / 100; config.minChartHeightPercent = (0, _lib.pluckNumber)(chartAttrs.minchartheight, iapi.minChartHeight, 50) / 100; config.minCanvasWidthPercent = (0, _lib.pluckNumber)(chartAttrs.mincanvaswidth, iapi.minCanvasWidth, 60) / 100; config.minCanvasHeightPercent = (0, _lib.pluckNumber)(chartAttrs.mincanvasheight, iapi.minCanvasHeight, 30) / 100; zeroPlaneColor = (0, _lib.pluck)(chartAttrs.zeroplanecolor, chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)); zeroPlaneAlpha = (0, _lib.pluck)(chartAttrs.zeroplanealpha, chartAttrs.divlinealpha, colorM.getColor('divLineAlpha')); config.zeroPlaneColor = (0, _lib.convertColor)(zeroPlaneColor, zeroPlaneAlpha); config.zeroPlaneBorderColor = (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.zeroplanebordercolor, zeroPlaneColor), (0, _lib.pluckNumber)(chartAttrs.zeroplaneshowborder, 1) ? zeroPlaneAlpha : 0); config.zeroPlaneShowBorder = (0, _lib.pluckNumber)(chartAttrs.zeroplaneshowborder, 1); // config.dataStreamURL = parseUnsafeString(chartAttrs.datastreamurl); config.realtimeEnabled = (0, _lib.pluckNumber)(chartAttrs.realtimeenabled, iapi.isRealTime); config.showLegend = (0, _lib.pluckNumber)(chartAttrs.showlegend, iapi.showLegend, 1); config.link = chartAttrs.clickurl; config.transposeAxis = (0, _lib.pluckNumber)(iapi.transposeAxis, chartAttrs.transposeaxis, 0); config.useEllipsesWhenOverflow = (0, _lib.pluckNumber)(chartAttrs.useellipseswhenoverflow, chartAttrs.useellipsewhenoverflow, 1); // config.skipZeroPlots = pluckNumber(chartAttrs.skipzeroplots, 1); config.drawTrendRegion = (0, _lib.pluckNumber)(chartAttrs.drawcrossline, 0); config.plotcolorintooltip = (0, _lib.pluckNumber)(chartAttrs.plotcolorintooltip, iapi.config.singleseries ? 0 : 1); // plotbinsize for large data config.plotbinsize = mathMin((0, _lib.pluckNumber)(chartAttrs.plotbinsize, iapi.plotbinsize, 0.5), 1); config.labelbinsize = mathMin((0, _lib.pluckNumber)(chartAttrs.labelbinsize, 1), 1); config.labelbinsize = config.plotbinsize > config.labelbinsize ? config.plotbinsize : config.labelbinsize; config.enableMouseOutEvent = (0, _lib.pluckNumber)(chartAttrs.enablemouseoutevent, iapi.enableMouseOutEvent, 1); config.plotSpacePercent = Math.max((0, _lib.pluckNumber)(chartAttrs.plotspacepercent, iapi.plotSpacePercent), 0); config.maxColWidth = Math.abs((0, _lib.pluckNumber)(chartAttrs.maxcolwidth, 50)); config.maxBarHeight = Math.abs((0, _lib.pluckNumber)(chartAttrs.maxbarheight, 50)); config.overlapColumns = (0, _lib.pluckNumber)(chartAttrs.overlapcolumns, chartAttrs.overlapbars, config.is3D ? 0 : 1); config.plotPaddingPercent = chartAttrs.plotpaddingpercent; config.tooltipgrayoutcolor = (0, _lib.pluck)(chartAttrs.tooltipgrayoutcolor, _lib.preDefStr.colors.AAAAAA); config.clickURLOverridesPlotLinks = (0, _lib.pluckNumber)(chartAttrs.clickurloverridesplotlinks, 0); // toolbar configuration used only by the chart config.toolbarX = (0, _lib.pluckNumber)(chartAttrs.toolbarx); config.toolbarY = (0, _lib.pluckNumber)(chartAttrs.toolbary); config.toolbarPosition = toolbarPositionParser((0, _lib.pluck)(chartAttrs.toolbarposition, 'tr').toLowerCase()); config.toolbarHAlign = (_lib.BLANKSTRING + chartAttrs.toolbarhalign).toLowerCase() === 'left' ? 'l' : config.toolbarPosition.charAt(1); config.toolbarVAlign = (_lib.BLANKSTRING + chartAttrs.toolbarvalign).toLowerCase() === 'bottom' ? 'b' : config.toolbarPosition.charAt(0); config.toolbarVMargin = (0, _lib.pluckNumber)(chartAttrs.toolbarvmargin, 6); config.toolbarHMargin = (0, _lib.pluckNumber)(chartAttrs.toolbarhmargin, 10); iapi.addToEnv('chartConfig', config); // linking the click function of rapheal objects iapi.addToEnv('linkClickFN', (0, _lib.getLinkAction)(iapi.getFromEnv('dataSource'), iapi)); iapi.addToEnv('dataLabelStyle', dataLabelStyle); }; /** * Create child components of chart * @param {Object} dataObj User input json */ CommonAPI.prototype.createComponent = function createComponent() { var iapi = this, config = iapi.config, skipConfigureIteration = void 0; skipConfigureIteration = config.skipConfigureIteration; iapi.createBaseComponent(); iapi.getFromEnv('animationManager').setAnimationState(iapi._firstConfigure ? 'initial' : 'update'); (0, _lib.componentFactory)(iapi, _caption2['default'], 'caption'); skipConfigureIteration.caption = true; (0, _lib.componentFactory)(iapi, _subCaption2['default'], 'subCaption'); skipConfigureIteration.subCaption = true; (0, _lib.componentFactory)(iapi, _background2['default'], 'background'); skipConfigureIteration.background = true; // Create dynamic components like message logger iapi._createConfigurableComponents && iapi._createConfigurableComponents(); // Update alert manager if (iapi.config.realtimeEnabled) { iapi._realTimeConfigure && iapi._realTimeConfigure(); } }; /** * Configure the child components */ CommonAPI.prototype.configureChildren = function configureChildren() { var iapi = this; iapi._mapChildren(function (child) { // components that already configure (listed in skipConfigureIteration) or removed // must not be configured if (!child.getState('removed') && iapi.config.skipConfigureIteration[child.getName()]) { child.configure && child.configure(); } }); }; /** * Function for creating the toolbox */ CommonAPI.prototype._createToolBox = function _createToolBox() { _createToolBox2.call(this); }; /** * function to create component and configure and also configure the chart * It creates components which are depend on data and configure them and also configure chart * It calls helper function namely, configure * @param {Object} dataObj contains json data of the chart */ CommonAPI.prototype.configureAttributes = function configureAttributes(dataObj) { configurer.call(this, dataObj); }; /** * function to set tooltip style from the chart API */ CommonAPI.prototype.setTooltipStyle = function setTooltipStyle() { var chartConfig = this.config, toolTipController = this.getFromEnv('toolTipController'); toolTipController.setStyle({ 'bgColor': (0, _lib.convertColor)(chartConfig.tooltipbgcolor || 'FFF', chartConfig.tooltipbgalpha || 100), 'rawBgColor': (chartConfig.tooltipbgcolor || 'FFF').replace(/\s+/g, '').replace(/^#?([a-f0-9]+)/ig, '#$1'), 'fontColor': (chartConfig.tooltipcolor || chartConfig.basefontcolor || '545454').replace(/\s+/g, '').replace(/^#?([a-f0-9]+)/ig, '#$1'), 'borderColor': (0, _lib.convertColor)(chartConfig.tooltipbordercolor || '666', chartConfig.tooltipborderalpha || 100), 'rawBorderColor': (chartConfig.tooltipbordercolor || '666').replace(/\s+/g, '').replace(/^#?([a-f0-9]+)/ig, '#$1'), 'bgAlpha': (0, _lib.pluckNumber)(chartConfig.tooltipbgalpha, 100), 'borderThickness': (0, _lib.pluckNumber)(chartConfig.tooltipborderthickness, 1), 'showToolTipShadow': (0, _lib.pluckNumber)(chartConfig.showtooltipshadow, chartConfig.showshadow, 1), 'borderRadius': (0, _lib.pluckNumber)(chartConfig.tooltipborderradius, 0), 'font-size': chartConfig.basefontsize || 10, 'font-family': chartConfig.basefont || this.getFromEnv('style').inCanfontFamily, 'padding': (0, _lib.pluckNumber)(chartConfig.tooltippadding || 3), 'borderAlpha': (0, _lib.pluckNumber)(chartConfig.tooltipborderalpha, 100) }); }; /** * parse defualt configuration of the chart */ CommonAPI.prototype.__setDefaultConfig = function __setDefaultConfig() { _BaseChart.prototype.__setDefaultConfig.call(this); var config = this.config; config.valuefontbold = 0; config.stickytracking = 1; // realtime related attributes // @todo ideally this should be moved to a realtime base chart config.usemessagelog = 0; config.zeroplanethickness = _lib.UNDEF; config.animationeffect = 'linear'; config.showshadow = 1; config.showhovereffect = _lib.UNDEF; config.plothovereffect = _lib.UNDEF; config.anchorhovereffect = _lib.UNDEF; config.plotborderdashed = _lib.UNDEF; config.stack100percent = _lib.UNDEF; config.showpercentvalues = _lib.UNDEF; config.showpercentintooltip = _lib.UNDEF; config.plotbordercolor = _lib.UNDEF; config.showtooltip = 1; config.seriesnameintooltip = 1; config.rotatevalues = 0; config.minimizetendency = 0; config.plotfillangle = 270; config.valuepadding = 2; config.useplotgradientcolor = 1; config.plotborderthickness = 1; config.plotfillalpha = SEVENTYSTRING; config.showvalues = 1; config.valueposition = AUTO; config.drawcrossline = _lib.UNDEF; config.tooltipsepchar = ', '; config.usedataplotcolorforlabels = 0; config.placevaluesinside = 0; config.showplotborder = 1; config.use3dlighting = 1; config.useroundedges = 0; config.plotspacepercent = 20; config.plotpaddingpercent = _lib.UNDEF; config.plotfillratio = _lib.UNDEF; config.maxcolwidth = 50; config.plotborderdashlen = 5; config.plotborderdashgap = 4; config.useScaleRecursively = true; config.formatnumberscale = 1; config.decimals = 2; config.decimalprecision = 10; config.tooltipbgcolor = 'FFF'; config.tooltipcolor = _lib.UNDEF; config.tooltipbordercolor = '666'; config.tooltipbgalpha = 100; config.tooltipborderthickness = 1; config.showtooltipshadow = _lib.UNDEF; config.basefontsize = 10; config.basefont = 'Verdana, sans'; config.tooltipborderradius = 0; config.tooltippadding = 3; config.tooltipborderalpha = 100; config.origw = _lib.UNDEF; config.origh = _lib.UNDEF; }; /** * this execute for onc time when the chart is rendered * @param {Object} dataObj chart JSON object */ CommonAPI.prototype.configure = function configure(dataObj) { dataObj.chart = dataObj.chart || dataObj.graph || dataObj.map || {}; _BaseChart.prototype.configure.call(this, dataObj); }; /** * function to check if the chart has the proper data or not * @return {boolean} if JSON data is valid or not */ CommonAPI.prototype._checkInvalidData = function _checkInvalidData() { var iapi = this, dataObj = iapi.getFromEnv('dataSource'), chartInstance = iapi.getFromEnv('chartInstance'); // Checking if the chart has proper data if (!iapi.isWidget && !iapi.isMap && !(dataObj.data && dataObj.data.length !== 0) && !dataObj.dataset && !dataObj.value && !dataObj.lineset && !dataObj.annotations && !dataObj.category && !(dataObj.tasks || dataObj.process) && !dataObj.axis) { iapi.setChartMessage(); iapi.drawChartMessage(); chartInstance.__state.dataReady = false; chartInstance.jsVars.hasNativeMessage = true; chartInstance.jsVars.drawCount += 1; return true; } }; /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ CommonAPI.prototype._checkInvalidSpecificData = function _checkInvalidSpecificData() { var jsonData = this.getFromEnv('dataSource'), datasetsJSON = jsonData.dataset, categories = jsonData.categories; if (!datasetsJSON || !categories || categories.length === 0 || !categories[0].category) { return true; } }; /** * Function to set or reset event listeners on container and canvas DOM. * If there are any previous event listeners attach to the chart container or canvas * then previous events listeners will be detached and new required event listeners * will be attached. */ CommonAPI.prototype.setChartEvents = function setChartEvents() { var chart = this, listeners = chart.getFromEnv('eventListeners'), dataSource = chart.getFromEnv('dataSource'), chartAttrs = dataSource && dataSource.chart, canvas = chart.getFromEnv('paper') && chart.getFromEnv('paper').canvas, container = chart.getFromEnv('chart-container'), // EnableChartMouseMoveEvent attribute to enable chartMouseMove event enableMouseMove = chartAttrs && (0, _lib.pluckNumber)(chartAttrs.enablechartmousemoveevent, 0); if (!(chartAttrs || canvas)) { return; } // In case of Ipad we will use touchend event as a substitute for click as // all touch events are preventDefaulted so click is not triggered _domEvent2['default'].unlisten(container, supportsPointer ? 'click' : 'touchend', supportsPointer ? onContainerClick : _onContainerClickIOS); // Local fix for not triggering click after any dragevent is triggered on the container // for non-touch devices. listeners.push(_domEvent2['default'].listen(container, 'mousedown touchstart', _registerMouseDown, chart)); listeners.push(_domEvent2['default'].listen(container, 'mousemove touchmove', _registerMouseMove, chart)); listeners.push(_domEvent2['default'].listen(container, supportsPointer ? 'click' : 'touchend', supportsPointer ? onContainerClick : _onContainerClickIOS, chart)); // Remove mouseover, touchstart, mouseout or touchend events if attached previously _domEvent2['default'].unlisten(canvas, 'mouseover', chartHoverManager, chart); _domEvent2['default'].unlisten(canvas, 'touchstart', chartHoverManager, chart); _domEvent2['default'].unlisten(canvas, 'mouseout', chartHoverManager, chart); _domEvent2['default'].unlisten(canvas, 'touchend', chartHoverManager, chart); // Attach mouseover, touchstart, mouseout or touchend events. listeners.push(_domEvent2['default'].listen(canvas, 'mouseover touchstart mouseout touchend', chartHoverManager, chart)); // Remove mousemove and touchmove events if previously attached. _domEvent2['default'].unlisten(container, 'mousemove', CommonAPI.onContainerMouseMove, chart); _domEvent2['default'].unlisten(container, 'touchmove', CommonAPI.onContainerMouseMove, chart); if (enableMouseMove) { // Attach mousemove and touchmove events. listeners.push(_domEvent2['default'].listen(container, 'mousemove touchmove', CommonAPI.onContainerMouseMove, chart)); } }; /** * Generalised getter function got chart API * @param {string} where plcae from where the object will be found * @param {string} what name of the object * @return {Object} return specific object from specific place */ CommonAPI.prototype.get = function get(where, what) { var place = this[where]; return what ? place && place[what] : place; }; CommonAPI.prototype.prepareAttributes = function prepareAttributes() { if (this.config.hasChartMessage) { return; } // Beginning of parsing cycle. Positions will be calculated and stored during phase _BaseChart.prototype.prepareAttributes.call(this); }; /** * function to clear applied css property */ CommonAPI.prototype.disposeChartStyleSheet = function disposeChartStyleSheet() { var chart = this, paper = chart.getFromEnv('paper'); paper && paper.cssClear(); }; /** * function to render css style applied on paper */ CommonAPI.prototype.createChartStyleSheet = function createChartStyleSheet() { var chart = this, paper = chart.getFromEnv('paper'); paper.cssRender(); }; /** * Function called when the chart is disposed */ CommonAPI.prototype._dispose = function _dispose() { var listeners = this.getFromEnv('eventListeners'), len = listeners && listeners.length; // Function to unlisten chart-events // clearing all the events when the chart is disposed. while (len--) { listeners[len].unlisten(); } _BaseChart.prototype._dispose.call(this); }; /** * allocate space for canvas * @param {Object} dimensions contains left, right, top, bottom co-ordinate (relative) */ CommonAPI.prototype._allocateSpace = function _allocateSpace(dimensions) { var iapi = this, canvas = iapi.getChildren('canvas'), canvasConfig = canvas && canvas[0].config, config = iapi.config, canvasHeight = config.canvasHeight, canvasWidth = config.canvasWidth, canvasTop, canvasLeft, availableHeight = config.availableHeight, availableWidth = config.availableWidth; canvasLeft = config.canvasLeft += dimensions.left || 0; canvasTop = config.canvasTop += dimensions.top || 0; canvasWidth = config.canvasWidth = mathMax(canvasWidth - ((dimensions.left || 0) + (dimensions.right || 0)), 0); canvasHeight = config.canvasHeight = mathMax(canvasHeight - ((dimensions.top || 0) + (dimensions.bottom || 0)), 0); config.availableHeight = mathMax(availableHeight - ((dimensions.top || 0) + (dimensions.bottom || 0)), 0); config.availableWidth = mathMax(availableWidth - ((dimensions.left || 0) + (dimensions.right || 0)), 0); config.canvasRight = canvasLeft + canvasWidth; config.canvasBottom = canvasTop + canvasHeight; if (canvasConfig) { canvasConfig.canvasPaddingLeft = mathMax(canvasConfig.canvasPaddingLeft, dimensions.paddingLeft || 0); canvasConfig.canvasPaddingRight = mathMax(canvasConfig.canvasPaddingRight, dimensions.paddingRight || 0); canvasConfig.canvasPaddingTop = mathMax(canvasConfig.canvasPaddingTop, dimensions.paddingTop || 0); canvasConfig.canvasPaddingBottom = mathMax(canvasConfig.canvasPaddingBottom, dimensions.paddingBottom || 0); } canvas && canvas[0].setDimension({ top: canvasTop, left: canvasLeft, width: canvasWidth, height: canvasHeight }); }; /** * Returns the postion for the caption placement * @param {number} centerX center position of charts * @return {number} extra spaces */ CommonAPI.prototype._fetchCaptionPos = function _fetchCaptionPos(centerX) { var extraSpace, iapi = this, iapiConfig = iapi.config, totalWidth = iapiConfig.width, chartMenuBar = iapi.getChildren('chartMenuBar') && iapi.getChildren('chartMenuBar')[0], chartMenuLogicalSpace = chartMenuBar ? chartMenuBar.getLogicalSpace() : {}, toolBoxWidth = chartMenuLogicalSpace.width || 0, caption = iapi.getChildren('caption') && iapi.getChildren('caption')[0], captionConfig = caption.config, captionWidth = captionConfig.width, isHalign = iapiConfig.toolbarHAlign === 'l', rightWidth = iapiConfig.width - centerX, availableWidth = isHalign ? centerX : rightWidth, origMarginRight = iapiConfig.origMarginRight, origMarginLeft = iapiConfig.origMarginLeft, offsetX = isHalign ? origMarginLeft : origMarginRight; // check if even after placing the caption // space available on right. if (captionConfig.align === _lib.POSITION_MIDDLE) { extraSpace = availableWidth - captionWidth / 2 - offsetX - toolBoxWidth; } else if (captionConfig.align === 'start') { // left aligned extraSpace = isHalign ? -1 : totalWidth - iapiConfig.canvasLeft - offsetX - captionWidth - toolBoxWidth + captionConfig.horizontalPadding; } else { // right-aligned. extraSpace = isHalign ? totalWidth - (origMarginRight + origMarginLeft + toolBoxWidth + captionWidth) : -1; } return extraSpace; }; /** * function to * @param {number} availableHeight available hieght to alocate * @param {number} availableWidth available width to alocate * @return {Object} dimension is needed */ CommonAPI.prototype._manageCaptionSpacing = function _manageCaptionSpacing(availableHeight, availableWidth) { var iapi = this, caption = iapi.getChildren('caption')[0], dimension; dimension = caption.manageSpace(availableHeight, availableWidth); return dimension; }; /** * function calculate toolbar hieght and allocate required space for toolbar * @param {number} availableHeight available height basically here the value is approx. chart height * @return {Object} details of region space taken by toolbar and caption */ CommonAPI.prototype._manageChartMenuBar = function _manageChartMenuBar(availableHeight) { var captionDimensions, iapi = this, iapiConfig = iapi.config, chartMenuBar = iapi.getChildren('chartMenuBar') && iapi.getChildren('chartMenuBar')[0], hardCodedTBYPosition = iapiConfig.toolbarY !== undefined, chartMenuLogicalSpace = chartMenuBar ? chartMenuBar.getLogicalSpace() : { height: 0, width: 0 }, caption = iapi.getChildren('caption') && iapi.getChildren('caption')[0], captionConfig = caption.config, isCaptionOnTop = captionConfig.isOnTop, chartCenterX = iapiConfig.width / 2, canvasRight = iapiConfig.canvasRight, // For Non-cartesian charts(e.g. Pie series) canvasCenter coincides with chartCenterX canvasCenterX = canvasRight ? (iapiConfig.canvasLeft + canvasRight) / 2 : chartCenterX, extraSpace = 0, availableWidth, centerX = captionConfig.alignWithCanvas ? canvasCenterX : chartCenterX; hardCodedTBYPosition && (chartMenuLogicalSpace.height = 0); chartMenuBar && chartMenuBar.setDimension({ x: iapiConfig.toolbarX !== undefined ? iapiConfig.toolbarX : (0, _lib.pluckNumber)(iapiConfig.toolbarHAlign === 'l' ? 0 : +iapiConfig.width), y: iapiConfig.toolbarY !== undefined ? iapiConfig.toolbarY : (0, _lib.pluckNumber)(iapiConfig.toolbarVAlign === 't' ? 0 : +iapiConfig.height), width: chartMenuLogicalSpace.width, height: chartMenuLogicalSpace.height }); delete captionConfig._offsetHeight; // Calculate available width based on alignCaption with canvas // If alignCaptionWithCanvas is set to 0, use full chart width // Else, only use canvasWidth availableWidth = captionConfig.alignWithCanvas ? iapiConfig.canvasWidth : iapiConfig.width - iapiConfig.origMarginLeft - iapiConfig.origMarginRight; if (isCaptionOnTop) { // place caption with a constrain on both height and width. // manage the space requirements for the caption. captionDimensions = iapi._manageCaptionSpacing(availableHeight, availableWidth); // If the toolbox isOnTop extraSpace = iapi._fetchCaptionPos(centerX); // not enough space on right is available. Place the caption and toolbox in two-tiers. captionConfig._offsetHeight = extraSpace < 0 ? chartMenuLogicalSpace.height : 0; captionDimensions.top = extraSpace < 0 ? (0, _lib.pluckNumber)(captionDimensions.top, 0) + chartMenuLogicalSpace.height : mathMax(captionDimensions.top, chartMenuLogicalSpace.height); iapi._allocateSpace(captionDimensions); } else { // reduce the canvas height by the toolbox required height. iapi._allocateSpace({ top: chartMenuLogicalSpace.height }); captionDimensions = iapi._manageCaptionSpacing(availableHeight, availableWidth); // allocate the space for caption. iapi._allocateSpace(captionDimensions); } return { top: chartMenuLogicalSpace ? mathMax(chartMenuLogicalSpace.height, captionDimensions.top) : captionDimensions.top, bottom: captionDimensions.bottom }; }; /** * calculate margins and space for and mange space for components */ CommonAPI.prototype._manageSpace = function _manageSpace() { var iapi = this, canvas = iapi.getChildren('canvas') && iapi.getChildren('canvas')[0], canvasConfig = canvas && canvas.config, config = iapi.config, width = iapi.getFromEnv('chartWidth'), height = iapi.getFromEnv('chartHeight'), minCanvasWidth, minCanvasHeight, marginTop, marginLeft, marginBottom, marginRight, canvasHeight, canvasWidth, minChartHeight, minChartWidth, diff, sum; // Setting the initial chart dimensions. config.width = width; config.height = height; config.minChartHeight = minChartHeight = config.minChartHeightPercent * height; config.minChartWidth = minChartWidth = config.minChartWidthPercent * width; config.minCanvasWidth = minCanvasWidth = config.minCanvasWidthPercent * minChartWidth; config.minCanvasHeight = minCanvasHeight = config.minCanvasHeightPercent * minChartHeight; config.marginTop = marginTop = config.origMarginTop; config.marginLeft = marginLeft = config.origMarginLeft; config.marginBottom = marginBottom = config.origMarginBottom; config.marginRight = marginRight = config.origMarginRight; config.canvasMarginTop = config.origCanvasTopMargin; config.canvasMarginLeft = config.origCanvasLeftMargin; config.canvasMarginBottom = config.origCanvasBottomMargin; config.canvasMarginRight = config.origCanvasRightMargin; config.canvasHeight = canvasHeight = config.height - config.marginTop - config.marginBottom; config.canvasWidth = canvasWidth = config.width - config.marginLeft - config.marginRight; config.availableHeight = canvasHeight - minCanvasHeight; config.availableWidth = canvasWidth - minCanvasWidth; // Check for minimum chart height if (canvasHeight < minChartHeight) { diff = height - minChartHeight; config.canvasHeight = minChartHeight; sum = marginTop + marginBottom; config.marginTop = diff * marginTop / sum; config.marginBottom = diff * marginBottom / sum; config.availableHeight = minChartHeight - minCanvasHeight; } // Check for minimum chart width if (canvasWidth < minChartWidth) { diff = width - minChartWidth; sum = marginRight + marginLeft; config.canvasWidth = minChartWidth; config.marginLeft = diff * marginLeft / sum; config.marginRight = diff * marginRight / sum; config.availableWidth = minChartWidth - minCanvasWidth; } config.canvasLeft = config.marginLeft; config.canvasTop = config.marginTop; if (canvasConfig) { canvasConfig.canvasPaddingLeft = mathMin(canvasConfig.origCanvasLeftPad, mathRound(0.1 * config.height)); canvasConfig.canvasPaddingRight = mathMin(canvasConfig.origCanvasRightPad, mathRound(0.1 * config.height)); canvasConfig.canvasPaddingTop = mathMin(canvasConfig.origCanvasTopPad, mathRound(0.1 * config.height)); canvasConfig.canvasPaddingBottom = mathMin(canvasConfig.origCanvasBottomPad, mathRound(0.1 * config.height)); } // manage space iapi._spaceManager(); }; /** * All numeric calculations to be done here */ CommonAPI.prototype._preDraw = function _preDraw() { var iapi = this; iapi._mapChildren(function (child) { if (!child.getState('removed')) { child.preDraw && child.preDraw(); } }); // set axis limit call from those charts of which datasets are directly child of the chart components iapi._setAxisLimits && iapi._setAxisLimits(); /** Exception for gantt chart**/ iapi._createToolBoxGantt && iapi._createToolBoxGantt(); /******************************/ }; /** * Function to clear the realTime timers */ CommonAPI.prototype._clearTimers = function _clearTimers() { var iapi = this, realTimeConfig = iapi.config && iapi.config.realTimeConfig, timers = iapi.config.timers, setTimeout = timers && timers.setTimeout, setInterval = timers && timers.setInterval, timer; realTimeConfig && (realTimeConfig.refreshIntervalFlag = false); for (timer in setTimeout) { clearTimeout(setTimeout[timer]); } for (timer in setInterval) { clearInterval(setInterval[timer]); } }; /** * Function to set cursor for the chart in case chart link is present. */ CommonAPI.prototype.setChartCursor = function setChartCursor() { var chart = this, link = chart.config.link, style = chart.getFromEnv('paper').canvas.style; // Set the cursor based on the presense of link. Note that IE and // other browsers have separate css value. if (Raphael.svg) { style.cursor = link ? _lib.POINTER : 'default'; } else { chart.getFromEnv('paper').canvas.style.cursor = link ? _lib.HAND : 'default'; } }; /** * function to create chart level containers */ CommonAPI.prototype._createLayers = function _createLayers() { var iapi = this, parentGroup, animationManager = iapi.getFromEnv('animationManager'); //* **** Create elements or components required for drawing // create elements if they are not available parentGroup = iapi.getContainer('parentgroup') || iapi.addContainer('parentgroup', animationManager.setAnimation({ el: 'group', attr: { name: 'parentgroup' }, component: iapi })); !iapi.getChildContainer('backgroundGroup') && iapi.addChildContainer('backgroundGroup', createGroup({ name: 'background' }, parentGroup, iapi)); !iapi.getChildContainer('axisBottomGroup') && iapi.addChildContainer('axisBottomGroup', createGroup({ name: 'axisbottom' }, parentGroup, iapi)); !iapi.getChildContainer('belowPlotGroup') && iapi.addChildContainer('belowPlotGroup', createGroup({ name: 'belowplot' }, parentGroup, iapi)); !iapi.getChildContainer('plotGroup') && iapi.addChildContainer('plotGroup', createGroup({ name: 'plots' }, parentGroup, iapi)); !iapi.getChildContainer('axisTopGroup') && iapi.addChildContainer('axisTopGroup', createGroup({ name: 'axistop' }, parentGroup, iapi)); !iapi.getChildContainer('sumLabelsLayer') && iapi.addChildContainer('sumLabelsLayer', createGroup({ name: 'sumlabels', 'class': 'fusioncharts-datalabels' }, parentGroup, iapi)); !iapi.getChildContainer('datalabelsGroup') && iapi.addChildContainer('datalabelsGroup', createGroup({ name: 'datalabel' }, parentGroup, iapi)); !iapi.getChildContainer('abovePlotGroup') && iapi.addChildContainer('abovePlotGroup', createGroup({ name: 'aboveplot' }, parentGroup, iapi)); !iapi.getChildContainer('captionGroup') && iapi.addChildContainer('captionGroup', createGroup({ name: 'caption' }, parentGroup, iapi)); !iapi.getChildContainer('defaultGroup') && iapi.addChildContainer('defaultGroup', createGroup({ name: 'chartdefault' }, parentGroup, iapi)); !iapi.getChildContainer('defaultShadowGroup') && iapi.addChildContainer('defaultShadowGroup', createGroup({ name: 'chartdefault-shadow' }, parentGroup, iapi)); !iapi.getChildContainer('trackerGroup') && iapi.addChildContainer('trackerGroup', createGroup({ name: 'tracker' }, parentGroup, iapi)); !iapi.getChildContainer('toolbar-master') && iapi.addChildContainer('toolbar-master', createGroup({ name: 'toolbar-master' }, parentGroup, iapi)); // !iapi.getChildContainer('buttonGroup') && // iapi.addChildContainer('buttonGroup', animationManager.setAnimation({ // el: 'group', // container: parentGroup, // attr: {name: 'buttons'}, // component: iapi // })); !iapi.getChildContainer('logoGroup') && iapi.addChildContainer('logoGroup', animationManager.setAnimation({ el: 'group', attr: { name: 'logo' }, component: iapi })); }; /** * function to parse label css and apply */ CommonAPI.prototype._setDataLabelStyle = function _setDataLabelStyle() { var iapi = this, style = iapi.config.dataLabelStyle, labelCSS = { fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight, fontStyle: style.fontStyle }, datalabelsGroup = iapi.getChildContainer('datalabelsGroup'); datalabelsGroup.css(labelCSS); }; /** * function to calculate caption width and hieght */ CommonAPI.prototype._manageCaptionPosition = function _manageCaptionPosition() { var iapi = this, chartConfig = iapi.config, components = iapi.getChildren(), caption = components.caption && components.caption[0], subCaption = components.subCaption && components.subCaption[0], captionConfig = caption.config, widgetValueHeight = captionConfig.widgetValueHeight || 0, subCaptionConfig = subCaption.config, captionX = void 0, captionY = void 0, subCaptionY = void 0, canvasWidth = chartConfig.canvasWidth, capAlign = captionConfig.align, hasCaption = captionConfig.text, alignWtCanvas = captionConfig.alignWithCanvas, hPadding = captionConfig.horizontalPadding, width = chartConfig.width, canvasLeft = chartConfig.canvasLeft, canvasRight = chartConfig.canvasRight, marginRight = chartConfig.marginRight, marginLeft = chartConfig.marginLeft, marginTop = chartConfig.marginTop, canvasCentre = (mathRound(canvasLeft) || 0) + (0, _lib.pluckNumber)(canvasWidth, width) / 2, interCaptionGap = 2, captionLineHeight = captionConfig.height, subCaptionLineHeight = subCaptionConfig.height, legendConfig = components.legend && components.legend[0] && components.legend[0].config || {}, legendHeight = legendConfig.height || 0, legendPadding = legendConfig.legendPadding || 0, legendPos = chartConfig.legendposition, gradientLegend = iapi.getFromEnv('gLegend') || {}, gradientLegendHeight = 0, showLegendAttr = !!(gradientLegend.conf || {}).showLegend, borderWidth = iapi.config.borderWidth, actionBar = components.actionBar, actionBarHeight = 0, actionBarSpace = void 0; if (!legendConfig.isActive) { legendHeight = 0; } if (showLegendAttr && iapi.config.gLegendEnabled) { gradientLegendHeight = gradientLegend.getLogicalSpace().height; } switch (capAlign) { case POSITION_END: captionX = alignWtCanvas ? canvasRight - hPadding : width - hPadding; break; case POSITION_START: captionX = alignWtCanvas ? canvasLeft + hPadding : hPadding; break; default: captionX = alignWtCanvas ? canvasCentre : marginLeft + (width - marginLeft - marginRight) * 0.5 || width / 2; } if (captionConfig.isOnTop) { captionY = (borderWidth || 0) + (marginTop || 0); } else { if (legendPos.toLowerCase() === POSITION_RIGHT) { legendPadding = 0; legendHeight = 0; gradientLegendHeight = 0; } if (actionBar) { actionBarSpace = actionBar[0].getLogicalSpace && actionBar[0].getLogicalSpace() || {}; actionBarHeight = actionBarSpace.height; if (actionBarHeight === _lib.UNDEF || actionBarHeight === Infinity || actionBarHeight < 0) { actionBarHeight = 0; } } captionY = iapi.config.height - iapi.config.marginBottom - captionLineHeight - (subCaptionLineHeight || 0) - (borderWidth || 0) - (legendPadding || 0) - (legendHeight || 0) - gradientLegendHeight - widgetValueHeight - actionBarHeight; } captionY += captionConfig._offsetHeight || 0; caption.setDimention({ x: captionX, y: captionY }); subCaptionY = hasCaption ? captionY + captionLineHeight + interCaptionGap : captionY || marginTop || 0; subCaption.setDimention({ x: captionX, y: subCaptionY }); }; /** * function to handle draw related job of various components * this function call draw of all the components which are child of the chart components */ CommonAPI.prototype._updateVisuals = function _updateVisuals() { var iapi = this, // container = iapi.getFromEnv('chart-container'), coreOptions = iapi.getFromEnv('core-options'), paper = iapi.getFromEnv('paper'), animationManager = iapi.getFromEnv('animationManager'), // tooltip = components.tooltip, // animationObj = iapi.get(configStr, animationObjStr), config = iapi.config, attr, width = iapi.getFromEnv('chartWidth'), height = iapi.getFromEnv('chartHeight'); // config.animationStarted = true; // In FC user can set the global core option SVGDefinitionURL as 'absolute' to make all definations in absolute URL. // This fix some issues in some browsers. // As FusionCharts.js is independent of Redraphael and this is the forst place where RedRaphael is getting used, we are configuring this attribute here. if (coreOptions && !coreOptions._SVGDefinitionURLUpdated) { if (/^\s*absolute\s*$/i.test(coreOptions.SVGDefinitionURL)) { // Assign the URL in R._url so that it uses that url only for the SVG definition. Raphael._url = (Raphael._g && Raphael._g.win || window).location.href.replace(/#.*?$/, _lib.BLANKSTRING); } // Mart a flag so that we only execute this for the first time. coreOptions._SVGDefinitionURLUpdated = true; } if (!paper) { paper = new Raphael(iapi.getFromEnv('chart-container'), width, height); paper.setHTMLClassName('fusioncharts-div'); iapi.addToEnv('paper', paper); paper.setConfig('stroke-linecap', _lib.ROUND); iapi.setChartEvents(); } else { // Fix for IE8 paper animation. if (!_lib.hasSVG && (config._prevWidth || config._prevHeight)) { paper.setSize(config._prevWidth, config._prevHeight); } attr = { width: width, height: height }; // animationStarted = true; // iapi._chartAnimation(true, fireCallBack); // paper.animateWith(dummyObj, animObj, attr, animationDuration, animType); animationManager.setAnimation({ el: paper, attr: attr, component: iapi }); } config._prevWidth = width; config._prevHeight = height; // Setting the cursor in case of chart link iapi.setChartCursor(); // create drawing layers iapi._createLayers(); // Set style for dataLabels iapi._setDataLabelStyle(); // adding the parent group in configuration of chartmenubar if it is present // iapi.getChildren('chartMenuBar') && (iapi.getChildren('chartMenuBar').config.parentLayer = iapi.getContainer('parentgroup')); iapi._drawCreditLabel(); }; /** * function to draw chart menu bar * @param {Ojecct} toolBarName The instance of the toolbar */ CommonAPI.prototype.allocateDimensionOfChartMenuBar = function allocateDimensionOfChartMenuBar() { var iapi = this, config = iapi.config, toolBar = iapi.getFromEnv('toolbar'), tbConfig = toolBar.config, hDirection = tbConfig.hDirection, vDirection = tbConfig.vDirection, logicalSpace = toolBar.getLogicalSpace(), _toolBar$getDimension = toolBar.getDimension(), y = _toolBar$getDimension.y, x = _toolBar$getDimension.x; if (config.toolbarVAlign === 't') { y += config.toolbarVMargin * vDirection + mathMin(0, logicalSpace.height * vDirection); x += config.toolbarHMargin * hDirection - mathMax(0, logicalSpace.width * hDirection); x = config.toolbarHAlign === 'l' ? x + logicalSpace.width : x - logicalSpace.width; } else { y = config.height - config.marginBottom - logicalSpace.height; x = config.toolbarVAlign === 'b' && config.toolbarHAlign === 'r' ? config.width - config.marginRight - logicalSpace.width : config.marginLeft; } config.toolbarX !== undefined && (x = config.toolbarX); config.toolbarY !== undefined && (y = config.toolbarY); toolBar.setDimension({ x: x, y: y, width: logicalSpace.width, height: logicalSpace.height }); toolBar.manageSpace(); }; /** * function to manage all draw draw related jobList * this function handle all the draw related jobs like space management, * post space management and draw */ CommonAPI.prototype.draw = function draw() { var iapi = this, chartObj = iapi.getFromEnv('chartInstance'); if (iapi.config.hasChartMessage) { iapi._hide(); iapi.drawChartMessage(); iapi.fireChartInstanceEvent('nodatatodisplay', {}, [chartObj.id]); chartObj.jsVars.drawCount += 1; chartObj.__state.dataReady = false; chartObj.jsVars.hasNativeMessage = true; } else { iapi._hideChartMessage(); iapi._clearTimers && iapi._clearTimers(); iapi.config.plotOverFlow = false; // show the chart if hidden iapi._show(); // draw elements finally iapi._updateVisuals(); iapi.setState('initiated', true); chartObj.jsVars.drawCount += 1; chartObj.jsVars.hasNativeMessage = false; } }; /** * does all the space managerment related jobs */ CommonAPI.prototype.manageSpace = function manageSpace() { var iapi = this; if (iapi.config.hasChartMessage) { return; } // do the final calculations before drawing iapi._preDraw(); // iapi._createToolBox(); // if api has function to add Toolbar; call it iapi.addToolbar && iapi.addToolbar(); // allocate space to all components iapi._manageSpace(); // after space allocation provide final positions to all components iapi._postSpaceManagement && iapi._postSpaceManagement(); }; /** * function to set visiblity true for parentgroup container of chart */ CommonAPI.prototype._show = function _show() { this.getContainer('parentgroup') && this.getContainer('parentgroup').show(); }; /** * function to calculate actionBar height * @return {bottom} conyains bottom with actionBar height */ CommonAPI.prototype._manageActionBarSpace = function _manageActionBarSpace() { var iapi = this, config = iapi.config, actionBar = iapi.getChildren('actionBar'), actionBarSpace = actionBar && actionBar[0] && actionBar[0].getLogicalSpace() || {}, actionBarHeight = actionBarSpace.height || 0; config.actionBarHeight = actionBarHeight; return { bottom: actionBarHeight }; }; /** * function to set visiblity false for parentgroup container of chart */ CommonAPI.prototype._hide = function _hide() { this.getContainer('parentgroup') && this.getContainer('parentgroup').hide(); }; /** * Triggers the mouse move event on the chart * @param {Event} e The event object associated with the mouse move */ CommonAPI.onContainerMouseMove = function onContainerMouseMove(e) { var chart = e.data, fusionCharts = chart.getFromEnv('chartInstance'), oriEvent = e.originalEvent, coordinate = (0, _lib.getMouseCoordinate)(chart.getFromEnv('chart-container'), oriEvent, chart), args; if (!fusionCharts.ref) { return; } args = (0, _lib.extend2)({ height: fusionCharts.args.height, width: fusionCharts.args.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: fusionCharts.args.id, renderer: fusionCharts.args.renderer, container: fusionCharts.options.containerElement }, coordinate); /** * This event is triggered whenever user moves the mouse pointer over a chart. The event * arguments pass useful information such as the pointer location relative to both chart and the page, * which can be utilised to perform various actions on the chart such as position an annotation or * integrate charts with custom tooltip libraries. * * > This event is not fired by default and needs to be enabled for individual charts by setting the * > value of chart attribute `enableChartMouseMoveEvent` to `1`. * * @see FusionCharts#event:chartRollOver * @see FusionCharts#event:chartRollOut * @see FusionCharts#event:chartClick * @event FusionCharts#chartMouseMove * @since 3.4.0 * @group chart * * @param {string} container - The DOM element within which the chart has been rendered. * @param {string} id - The `id` of the chart that has triggered this event. * * @param {string} height - The height of the chart specified at the time of rendering the chart in * pixels or percent. * @param {string} width - The width of the chart specified at the time of rendering the chart in pixels * or percent. * * @param {number} chartX - The x-coordinate of the mouse relative to the position of the chart. * @param {number} chartY - The y-coordinate of the mouse relative to the position of the chart. * * @param {number} pageX - The x-coordinate of the mouse relative to the document. * @param {number} pageY - The y-coordinate of the mouse relative to the document. * * @param {number} pixelHeight - The height of the chart in pixels. This is equivalent to the * `offsetHeight` of the chart container * @param {number} pixelWidth - The width of the chart in pixels. This is equivalent to the * `offsetWidth` of the chart container */ chart.fireChartInstanceEvent('chartMouseMove', args); }; /** * Triggers the mouse roll over event on the chart * @param {Event} e The event object associated with the mouse roll over */ CommonAPI.onContainerRollOver = function onContainerRollOver(e) { var chart = e.data, fusionCharts = chart.getFromEnv('chartInstance'), oriEvent = e.originalEvent, coordinate = (0, _lib.getMouseCoordinate)(chart.getFromEnv('chart-container'), oriEvent, chart), args; if (!fusionCharts.ref) { return; } args = (0, _lib.extend2)({ height: fusionCharts.args.height, width: fusionCharts.args.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: fusionCharts.args.id, renderer: fusionCharts.args.renderer, container: fusionCharts.options.containerElement }, coordinate); /** * This event is fired when the mouse pointer moves over the chart. For touch devices, * this event is raised when user taps on to the chart after previously tapping onto anywhere outside * the chart. * * One can listen to this event and track when user is pointing to a chart and perform relevant actions * such as highlighting information anywhere else on the page that is relevant to the chart. * @see FusionCharts#event:chartRollOut * @see FusionCharts#event:chartClick * @see FusionCharts#event:chartMouseMove * @event FusionCharts#chartRollOver * @since 3.4.0 * @group chart * * @param {string} container - The DOM element within which the chart has been rendered. * @param {string} id - The `id` of the chart that has triggered this event. * * @param {string} height - The height of the chart specified at the time of rendering the chart in * pixels or percent. * @param {string} width - The width of the chart specified at the time of rendering the chart in pixels * or percent. * * @param {number} chartX - The x-coordinate of the mouse relative to the position of the chart. * @param {number} chartY - The y-coordinate of the mouse relative to the position of the chart. * * @param {number} pageX - The x-coordinate of the mouse relative to the document. * @param {number} pageY - The y-coordinate of the mouse relative to the document. * * @param {number} pixelHeight - The height of the chart in pixels. This is equivalent to the * `offsetHeight` of the chart container * @param {number} pixelWidth - The width of the chart in pixels. This is equivalent to the * `offsetWidth` of the chart container * * @example * // Create a chart and display the caption of the chart over which the mouse has been hovered. The * // event is attached to the FusionCharts global `addEventListener` function so that it is fired for * // all charts rendered on that page Once this event listener has been attached, any chart rendered on * // page will cause a console log when hovered or tapped. * FusionCharts.addEventListener('chartRollOver', function (event) { * var chart = event.sender, // access the chart that raised this event * caption = chart && chart.getChartAttribute(CAPTION); // get the chart caption * * // Output the caption in JavaScript console * console.log('Mouse entered on the chart with caption: ' + caption); * }); */ chart.fireChartInstanceEvent('chartRollOver', args); }; /** * Triggers the mouse roll out event on the chart * @param {Event} e The event object associated with the mouse roll out */ CommonAPI.onContainerRollOut = function onContainerRollOut(e) { var chart = e.chart, fusionCharts = chart.getFromEnv('chartInstance'), oriEvent = e.event, coordinate = (0, _lib.getMouseCoordinate)(chart.getFromEnv('chart-container'), oriEvent, chart), args; if (!fusionCharts.ref) { return; } args = (0, _lib.extend2)({ height: fusionCharts.args.height, width: fusionCharts.args.width, pixelHeight: chart.getFromEnv('chartWidth'), pixelWidth: chart.getFromEnv('chartHeight'), id: fusionCharts.args.id, renderer: fusionCharts.args.renderer, container: fusionCharts.options.containerElement }, coordinate); /** * This event is fired when the mouse pointer moves out of the chart. For touch devices, * this event is raised when user taps on to anywhere outside the chart after previously tapping on the * chart. * * One can listen to this event and track when user is no longer pointing to a particular chart. * @see FusionCharts#event:chartRollOver * @see FusionCharts#event:chartClick * @see FusionCharts#event:chartMouseMove * @event FusionCharts#chartRollOut * @since 3.4.0 * @group chart * * @param {string} container - The DOM element within which the chart has been rendered. * @param {string} id - The `id` of the chart that has triggered this event. * * @param {string} height - The height of the chart specified at the time of rendering the chart in * pixels or percent. * @param {string} width - The width of the chart specified at the time of rendering the chart in pixels * or percent. * * @param {number} chartX - The x-coordinate of the mouse relative to the position of the chart. * @param {number} chartY - The y-coordinate of the mouse relative to the position of the chart. * * @param {number} pageX - The x-coordinate of the mouse relative to the document. * @param {number} pageY - The y-coordinate of the mouse relative to the document. * * @param {number} pixelHeight - The height of the chart in pixels. This is equivalent to the * `offsetHeight` of the chart container * @param {number} pixelWidth - The width of the chart in pixels. This is equivalent to the * `offsetWidth` of the chart container * * @example * // Create a chart and display the caption of the chart over which the mouse has been hovered. The * // event is attached to the FusionCharts global `addEventListener` function so that it is fired for * // all charts rendered on that page Once this event listener has been attached, any chart rendered on * // page will cause a console log when hovered out or tapped away. * FusionCharts.addEventListener('chartRollOut', function (event) { * var chart = event.sender, // access the chart that raised this event * caption = chart && chart.getChartAttribute(CAPTION); // get the chart caption * * // Output the caption in JavaScript console * console.log('Mouse left the chart with caption: ' + caption); * }); */ chart.fireChartInstanceEvent('chartRollOut', args); }; /** * Detaches the mouseover handler from the chart * @param {Event} e The event object associated with the rollout */ CommonAPI.winMouseHover = function winMouseHover(e) { var event = e.originalEvent, tgt = event.target || event.originalTarget || event.srcElement || event.relatedTarget || event.fromElement, chart = e.data, paper = chart.getFromEnv('paper'), eve = { chart: chart, event: e.originalEvent }; // On mouse rollout of the chart, detach window mouseover event if (isVML) { if (!paper.getById(tgt.parentNode.raphaelid)) { CommonAPI.onContainerRollOut(eve); chart.config.mouseStateIn = false; _domEvent2['default'].unlisten(document, 'mouseover', CommonAPI.winMouseHover); } } else { if (!tgt.viewportElement) { chart.config.mouseStateIn = false; CommonAPI.onContainerRollOut(eve); _domEvent2['default'].unlisten(window, 'mouseover', CommonAPI.winMouseHover); } } }; return CommonAPI; }(_baseChart2['default']); exports['default'] = CommonAPI; exports._drawDataset = _drawDataset; exports._createToolBox = _createToolBox2; exports.configurer = configurer; /***/ }), /* 363 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var canvas = void 0; (0, _lib.componentFactory)(chart, _canvas2['default'], 'canvas', chart.config.showVolumeChart ? 2 : 1); canvas = chart.getChildren('canvas'); for (var i = 0, len = canvas.length; i < len; i++) { canvas[i].configure(); } }; var _canvas = __webpack_require__(364); var _canvas2 = _interopRequireDefault(_canvas); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 364 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _canvas = __webpack_require__(365); var _canvas2 = _interopRequireDefault(_canvas); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var mathMax = Math.max, MAX_MITER_LINEJOIN = 2, miterStr = _lib.preDefStr.miterStr, NONE = _lib.preDefStr.noneStr, ROUND = _lib.preDefStr.ROUND, clipSumValue = 'clip-sum-value', clipCanvasInitStr = 'clip-canvas-init', clipCanvasStr = 'clip-canvas', /** * Helper function to create a RedRaphael group. * @param {string} groupName Name of the group to be created. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} dataset The canvas * @return {Element} The group that was created. */ _createGroup = function _createGroup(groupName, parentContainer, canvas) { var animationManager = canvas.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: { name: groupName }, container: parentContainer, component: canvas, label: 'group' }); }; (0, _dependencyManager.addDep)({ name: 'canvasAnimation', type: 'animationRule', extension: _canvas2['default'] }); /** * Canvas is responsible for create the groups where the chart is going to render. * Canvas has also ability to add input buttons, all input components have to be added to * canvas to activate them. Ex. ZoomIn,ZoomOut etc Button in zoomscatter chart. * Before adding any input component to canvas it is required to attach axes to canvas, * so that input components can recognize what axis is zoomable or pannable. */ var Canvas = function (_ComponentInterface) { _inherits(Canvas, _ComponentInterface); /** * constructor fn */ function Canvas() { _classCallCheck(this, Canvas); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); var canvas = _this; // axisRefComp = new AxisRefVisuals(); canvas.config = {}; canvas.config.axes = canvas.config.axes || []; // canvas needs axes for its own requirement thats why we are storing axes in linked items canvas.setLinkedItem('axes', []); canvas.setLinkedItem('primaryAxis', {}); // canvas.attachChild(axisRefComp, 'axisRefVisuals'); canvas.addToEnv('canvasConfig', _this.config); return _this; } /** * Sets the name of the component * @return {string} name */ Canvas.prototype.getName = function getName() { return 'canvas'; }; /** * Sets the type of the component * @return {string} type */ Canvas.prototype.getType = function getType() { return 'canvas'; }; Canvas.prototype.createGroup = function createGroup() { var canvas = this, chart = canvas.getFromEnv('chart'), chartChildContainer = chart.getChildContainer(), parentGroup = chart.getContainer('parentgroup'), // axisBottomGroup = chartChildContainer.axisBottomGroup, canvasDimensions = canvas.getEffectiveDimensions(), chartAttr = canvas.getFromEnv('chart-attrib'), isAreaOverColumns = (0, _lib.pluckNumber)(chartAttr.areaovercolumns, 1), // sumLabelsLayer = chartChildContainer.sumLabelsLayer, floorContainer = canvas.getChildContainer('axisReferenceVisualsFloor'), bottomContainer = canvas.getChildContainer('axisReferenceVisualsBottom'), middleContainer = canvas.getChildContainer('axisReferenceVisualsMiddle'), topContainer = canvas.getChildContainer('axisReferenceVisualsTop'), ceilContainer = canvas.getChildContainer('axisReferenceVisualsCeil'), areaContainer = canvas.getChildContainer('areaGroup'), areaShadowContainer = canvas.getChildContainer('areaShadowGroup'), columnContainer = canvas.getChildContainer('columnGroup'), columnShadowContainer = canvas.getChildContainer('columnShadowGroup'), plotGroup = chartChildContainer.plotGroup, clipPath = [canvasDimensions.left, canvasDimensions.top, canvasDimensions.width, canvasDimensions.height].toString(); // axis ref visuals container will be clipped except for top and bottom container // because we keep plot lines in bottom container and the zero plane is kept // in top for column charts and bottom in middle charts // the clipping has been removed so that when canvas border is removed the limit // plot lines can be ssen !canvas.getContainer('canvasGroup') && canvas.addContainer('canvasGroup', _createGroup('canvas', parentGroup, canvas)).insertAfter(chartChildContainer.backgroundGroup); if (!bottomContainer) { bottomContainer = canvas.addChildContainer('axisReferenceVisualsBottom', _createGroup('axisReferenceVisualsBottom', parentGroup, canvas)).insertAfter(chartChildContainer.axisBottomGroup); } if (!floorContainer) { floorContainer = canvas.addChildContainer('axisReferenceVisualsFloor', _createGroup('axisReferenceVisualsFloor', parentGroup, canvas)).insertAfter(chartChildContainer.axisBottomGroup); } floorContainer.attr({ 'clip-rect': clipPath }); !canvas.getChildContainer('crossline') && canvas.addChildContainer('crossline', _createGroup('crossline', parentGroup, canvas)).insertBefore(chartChildContainer.plotGroup); !canvas.getChildContainer('crosslineBottom') && canvas.addChildContainer('crosslineBottom', _createGroup('crosslineBottom', parentGroup, canvas)).insertBefore(chartChildContainer.plotGroup); !canvas.getChildContainer('crosslineTop') && canvas.addChildContainer('crosslineTop', _createGroup('crosslineTop', parentGroup, canvas)).insertBefore(chartChildContainer.abovePlotGroup); !canvas.getChildContainer('datalabelsGroup') && canvas.addChildContainer('datalabelsGroup', _createGroup('canvasdatalabel', chart.getChildContainer('datalabelsGroup'), canvas)); if (!middleContainer) { middleContainer = canvas.addChildContainer('axisReferenceVisualsMiddle', _createGroup('axisReferenceVisualsMiddle', parentGroup, canvas)).insertBefore(chartChildContainer.plotGroup); } middleContainer.attr({ 'clip-rect': clipPath }); if (!topContainer) { topContainer = canvas.addChildContainer('axisReferenceVisualsTop', _createGroup('axisReferenceVisualsTop', parentGroup, canvas)).insertBefore(chartChildContainer.datalabelsGroup); } !canvas.getChildContainer('quadrantGroup') && canvas.addChildContainer('quadrantGroup', _createGroup('quadrant', parentGroup, canvas)).insertAfter(middleContainer); if (!ceilContainer) { canvas.addChildContainer('axisReferenceVisualsCeil', _createGroup('axisReferenceVisualsCeil', parentGroup, canvas)).insertBefore(chartChildContainer.datalabelsGroup); } !canvas.getChildContainer('sumLabelsLayer') && canvas.addChildContainer('sumLabelsLayer', chartChildContainer.sumLabelsLayer); // Create containers for columns and their shadows if (!columnShadowContainer) { columnShadowContainer = canvas.addChildContainer('columnShadowGroup', _createGroup('column-shadow-group', plotGroup, canvas)); } if (!columnContainer) { columnContainer = canvas.addChildContainer('columnGroup', _createGroup('column', plotGroup, canvas)); } // Create containers for area and its shadow if (!areaShadowContainer) { areaShadowContainer = canvas.addChildContainer('areaShadowGroup', _createGroup('area-shadow-group', plotGroup, canvas)); } if (!areaContainer) { areaContainer = canvas.addChildContainer('areaGroup', _createGroup('area', plotGroup, canvas)); } // Depending on the value of the 'areaOverColumns' attribute, swap the groups for area and // column if (!isAreaOverColumns) { areaShadowContainer.insertBefore(columnShadowContainer); areaContainer.insertBefore(columnShadowContainer); } else { columnShadowContainer.insertBefore(areaShadowContainer); columnContainer.insertBefore(areaShadowContainer); } !canvas.getChildContainer('lineShadowGroup') && canvas.addChildContainer('lineShadowGroup', _createGroup('line-shadow-group', plotGroup, canvas)); !canvas.getChildContainer('lineGroup') && canvas.addChildContainer('lineGroup', _createGroup('line', plotGroup, canvas)); !canvas.getChildContainer('defaultShadowGroup') && canvas.addChildContainer('defaultShadowGroup', _createGroup('default-shadow-group', plotGroup, canvas)); !canvas.getChildContainer('defaultGroup') && canvas.addChildContainer('defaultGroup', _createGroup('default', plotGroup, canvas)); }; /** * function to check the given cordinate is with in canvas or not * @param {number} x - x coordinate * @param {number} y - y coordinate * @return {boolean} whether the coordinate is with in canvas or not */ Canvas.prototype.isWithinCanvas = function isWithinCanvas(x, y) { var canvas = this, conf = canvas.config, left = conf.canvasLeft, right = left + conf.canvasWidth, top = conf.canvasTop, bottom = top + conf.canvasHeight; return x >= left && x <= right && y >= top && y <= bottom; }; /** * this function calculate the colaborative space and padding required by the datasets */ Canvas.prototype.setCanvasPadding = function setCanvasPadding() { var iapi = this, canvasConfig = iapi.config, dimensions; dimensions = iapi.getCanvasPadding(); canvasConfig.canvasPaddingLeft = mathMax(canvasConfig.canvasPaddingLeft, dimensions.paddingLeft || 0); canvasConfig.canvasPaddingRight = mathMax(canvasConfig.canvasPaddingRight, dimensions.paddingRight || 0); canvasConfig.canvasPaddingTop = mathMax(canvasConfig.canvasPaddingTop, dimensions.paddingTop || 0); canvasConfig.canvasPaddingBottom = mathMax(canvasConfig.canvasPaddingBottom, dimensions.paddingBottom || 0); }; Canvas.prototype.getEffectiveDimensions = function getEffectiveDimensions() { var canvas = this, config = canvas.config, left = config.canvasLeft, top = config.canvasTop, width = config.canvasWidth, height = config.canvasHeight, paddingLeft = config.canvasPaddingLeft, paddingTop = config.canvasPaddingTop, paddingRight = config.canvasPaddingRight, paddingBottom = config.canvasPaddingBottom; return { left: left, top: top, width: width, height: height, paddingLeft: paddingLeft, paddingTop: paddingTop, paddingRight: paddingRight, paddingBottom: paddingBottom }; }; Canvas.prototype.setDimension = function setDimension(dim) { var canvas = this, config = canvas.config; config.canvasTop = dim.top; config.canvasLeft = dim.left; config.canvasWidth = dim.width; config.canvasHeight = dim.height; }; Canvas.prototype.getCanvasPadding = function getCanvasPadding() { var iapi = this, dim, key, chartConfig = iapi.getFromEnv('chartConfig'), canvasWidth = chartConfig.canvasWidth, canvasConfig = iapi.config, paddingLeft, paddingRight, spaceLimit = canvasConfig.maxPaddingPercent * canvasWidth / 100, returnDimension = { paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 }; iapi._mapChildren(function (child) { dim = child.getCanvasPadding && child.getCanvasPadding() || {}; for (key in dim) { if (dim.hasOwnProperty(key)) { returnDimension[key] = mathMax(dim[key], returnDimension[key]); } } }); paddingLeft = returnDimension.paddingLeft || 0; paddingRight = returnDimension.paddingRight || 0; if (spaceLimit < paddingLeft) { returnDimension.paddingLeft = spaceLimit; } if (spaceLimit < paddingRight) { returnDimension.paddingRight = spaceLimit; } return returnDimension; }; /** * function to configure itself and its children */ Canvas.prototype.configureAttributes = function configureAttributes() { var overrideConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var canvas = this, chart = canvas.getLinkedParent(), chartConfig = canvas.getFromEnv('chartConfig'), canvasBorderThickness, canBGAlpha, showCanvasBorder, shadow, canvasConfig = canvas.config, chartAttrs = canvas.getFromEnv('chart-attrib'), colorM = canvas.getFromEnv('color-manager'), is3D = chartConfig.is3D, oriCanvasBorderThickness, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, isRoundEdges = canvasConfig.isRoundEdges = (0, _lib.pluckNumber)(chartAttrs.useroundedges, 0), showAxisLine = (0, _lib.pluckNumber)(chartAttrs.showxaxisline, chartAttrs.showyaxisline, chartAttrs.showaxislines, 0), hideAxisLine = showAxisLine ? 0 : 1; canvasConfig.canvasBorderRadius = (0, _lib.pluckNumber)(chartAttrs.plotborderradius, isRoundEdges ? 2 : 0); showCanvasBorder = canvasConfig.showCanvasBorder = Boolean((0, _lib.pluckNumber)(chartAttrs.showcanvasborder, hideAxisLine, canvasBorderThickness, isRoundEdges ? 0 : 1)); // Storing original canvasBorderThickness for future reference oriCanvasBorderThickness = canvasConfig.oriCanvasBorderThickness = mathMax((0, _lib.pluckNumber)(chartAttrs.canvasborderthickness, isRoundEdges ? 0 : (0, _lib.pluckNumber)(chart.canvasborderthickness, 2), 0)); canvasBorderThickness = canvasConfig.canvasBorderWidth = is3D ? 0 : showCanvasBorder ? oriCanvasBorderThickness : 0; canvasConfig.canvasBorderColor = (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.canvasbordercolor, colorM.getColor(_lib.canvasBorderColorStr)), (0, _lib.pluck)(chartAttrs.canvasborderalpha, colorM.getColor('canvasBorderAlpha'))); canBGAlpha = canvasConfig.canBGAlpha = (0, _lib.pluck)(chartAttrs.canvasbgalpha, colorM.getColor(_lib.canvasBGAlphaStr)); canvasConfig.canBGColor = { FCcolor: { color: (0, _lib.pluck)(chartAttrs.canvasbgcolor, colorM.getColor(palleteString.canvasBgColor)), alpha: (0, _lib.pluck)(chartAttrs.canvasbgalpha, 100), angle: (0, _lib.pluck)(chartAttrs.canvasbgangle, 0), ratio: (0, _lib.pluck)(chartAttrs.canvasbgratio) } }; shadow = canvasConfig.shadow = (0, _lib.pluckNumber)(chartAttrs.showshadow, isRoundEdges, 0) && isRoundEdges ? { enabled: true, opacity: canBGAlpha / 100 } : 0; canvasConfig.shadowOnCanvasFill = shadow && shadow.enabled; // canvas padding canvasConfig.canvasPadding = (0, _lib.pluckNumber)(chartAttrs.canvaspadding, 0); canvasConfig.origCanvasTopPad = (0, _lib.pluckNumber)(chartAttrs.canvastoppadding, 0); canvasConfig.origCanvasBottomPad = (0, _lib.pluckNumber)(chartAttrs.canvasbottompadding, 0); canvasConfig.origCanvasLeftPad = (0, _lib.pluckNumber)(chartAttrs.canvasleftpadding, 0); canvasConfig.origCanvasRightPad = (0, _lib.pluckNumber)(chartAttrs.canvasrightpadding, 0); // override canvasConfig in case of sparkcharts which has their own _parseCanvasCosmetics method that returns few canvas configurations Object.assign(canvasConfig, overrideConfig); // Adding the input component array canvas.config.inputComponents = []; canvas.config.maxPaddingPercent = 12.5; canvas._mapChildren(function (child) { if (child.getState('removed') || child.getType && child.getType() === 'dataset' || child.getType() === 'axisRefVisuals') { return; } child.configure && child.configure(); }); }; /* * dispose all inputs attached */ Canvas.prototype.disposeAllInputs = function disposeAllInputs() { this.config.inputComponents.forEach(function (input) { input.dispose(); }); this.config.inputComponents.length = 0; }; Canvas.prototype.axisExists = function axisExists(axis) { var axisArr = this.getLinkedItem('axes'), i = void 0, ii = void 0, status = false; for (i = 0, ii = axisArr.length; i < ii; i++) { if (axisArr[i].axis === axis) { status = true; break; } } return status; }; Canvas.prototype.attachAxis = function attachAxis(axis, isY, config) { var axisArr = this.getLinkedItem('axes'), axisType = isY ? 'yAxis' : 'xAxis', axes = this.getFromEnv(axisType) || []; if (!this.axisExists(axis)) { axisArr.push({ axis: axis, isY: isY, config: config || {} }); axes.push(axis); this.addToEnv(axisType, axes); } return this; }; /** * Function for setting the primary axis wrt to the canvas * @param {string} type xAxis/yAxis * @param {Object} axis The axis object */ Canvas.prototype.setPrimaryAxis = function setPrimaryAxis(type, axis) { var primaryAxis = this.getLinkedItem('primaryAxis'); primaryAxis[type] = this.getLinkedItem('axes').find(function (obj) { return obj.axis === axis; }); }; /** * If primary axis is set then only the primary axis are returned else all the axis * @return {Object} Axis */ Canvas.prototype.getAxes = function getAxes() { var primaryAxis; if (Object.keys(primaryAxis = this.getLinkedItem('primaryAxis')).length) { return [primaryAxis.xAxis, primaryAxis.yAxis]; } return this.getLinkedItem('axes').slice(0); }; Canvas.prototype.detachAxis = function detachAxis(axis, _index) { var axisArr = this.getLinkedItem('axes'), index = Infinity; if (_index) { return axisArr.splice(_index, 1); } axisArr.forEach(function (axisOb, i) { if (axisOb.axis === axis) { index = i; } }); return axisArr.splice(index, 1); }; Canvas.prototype.preDraw = function preDraw() { this._mapChildren(function (child) { if (!child.getState('removed')) { child.preDraw && child.preDraw(); } }); }; Canvas.prototype.draw = function draw() { this.createGroup(); !this.getFromEnv('chart').config.skipCanvasDrawing && this.drawCanvas(); }; Canvas.prototype.drawCanvas = function drawCanvas() { var canvas = this, chart = canvas.getFromEnv('chart'), isBar = chart.isBar, jsonData = chart.getFromEnv('dataSource'), chartAttrs = jsonData.chart, animationManager = canvas.getFromEnv('animationManager'), chartConfig = chart.config, config = canvas.config, clip = config.clip = {}, clipCanvas = void 0, dsGroup = chart.getChildContainer('plotGroup'), dataLabelsLayer = chart.getChildContainer('datalabelsGroup'), canvasBorderElementCheck = canvas.getGraphicalElement('canvasBorderElement'), canvasBorderElement = void 0, // animationObj = chart.get(configStr, animationObjStr), // animType = animationObj.animType, // animObj = animationObj.animObj, // dummyObj = animationObj.dummyObj, // animationDuration = animationObj.duration, canvasElementCheck = canvas.getGraphicalElement('canvasElement'), canvasElement = void 0, canvasLeft = config.canvasLeft || (config.canvasLeft = chartConfig.canvasLeft), canvasTop = config.canvasTop || (config.canvasTop = chartConfig.canvasTop), canvasWidth = config.canvasWidth || (config.canvasWidth = chartConfig.canvasWidth), canvasHeight = config.canvasHeight || (config.canvasHeight = chartConfig.canvasHeight), xDepth = config.xDepth = chartConfig.xDepth || 0, yDepth = config.yDepth = chartConfig.yDepth || 0, canvasGroup = canvas.getContainer('canvasGroup'), quadrantGroup = canvas.getChildContainer('quadrantGroup'), canvasBorderRadius = config.canvasBorderRadius, canvasBorderWidth = config.canvasBorderWidth, borderWHlf = canvasBorderWidth * 0.5, canvasBorderColor = config.canvasBorderColor, canBGColor = config.canBGColor, canBGAlpha = config.canBGAlpha, shadow = config.shadow, canvasBgColor = void 0, attr = void 0, showCanvasBg = config.showCanvasBG = Boolean((0, _lib.pluckNumber)(chartAttrs.showcanvasbg, 1)), shadowOnCanvasFill = config.shadowOnCanvasFill, showCanvasBorder = config.showCanvasBorder, gutter = void 0, clipAniamtionFn = void 0; canvasBgColor = canBGColor; attr = { x: canvasLeft - borderWHlf, y: canvasTop - borderWHlf, width: canvasWidth + canvasBorderWidth, height: canvasHeight + canvasBorderWidth, r: canvasBorderRadius, 'stroke-width': canvasBorderWidth, stroke: canvasBorderColor, 'stroke-linejoin': canvasBorderWidth > MAX_MITER_LINEJOIN ? ROUND : miterStr }; if (showCanvasBorder) { canvasBorderElementCheck && canvasBorderElementCheck.show(); canvasBorderElement = animationManager.setAnimation({ el: canvasBorderElementCheck || 'rect', component: canvas, attr: { x: canvasLeft - borderWHlf, y: canvasTop - borderWHlf, width: canvasWidth + canvasBorderWidth, height: canvasHeight + canvasBorderWidth, r: canvasBorderRadius, 'stroke-width': canvasBorderWidth, stroke: canvasBorderColor, 'stroke-linejoin': canvasBorderWidth > MAX_MITER_LINEJOIN ? ROUND : miterStr }, label: 'rect', container: canvasGroup }).shadow(shadow); if (!canvasBorderElementCheck) { canvas.addGraphicalElement('canvasBorderElement', canvasBorderElement); } } else if (canvasBorderElementCheck) { canvas.removeGraphicalElement(canvasBorderElementCheck); animationManager.setAnimation({ el: canvasBorderElementCheck, component: canvas, callback: function callback() { canvasBorderElementCheck.hide(); } }); } // gutter added so that plot borders are not hidden when showCanvasBorder is set to 0 gutter = showCanvasBorder ? 0 : config.oriCanvasBorderThickness; // create a clip-rect to clip canvas for later use clip[clipCanvasStr] = [mathMax(0, canvasLeft - xDepth - gutter), mathMax(0, canvasTop - yDepth - gutter), mathMax(1, canvasWidth + xDepth * 2 + 2 * gutter), mathMax(1, canvasHeight + yDepth + 2 * gutter)]; clip[clipSumValue] = [mathMax(0, canvasLeft - xDepth), isBar ? canvasTop : 0, mathMax(1, isBar ? chartConfig.width - canvasLeft : canvasWidth + xDepth * 2), mathMax(1, isBar ? canvasHeight + yDepth : canvasTop + canvasHeight)]; clip[clipCanvasInitStr] = [mathMax(0, canvasLeft - xDepth), mathMax(0, canvasTop - yDepth), 1, mathMax(1, canvasHeight + yDepth * 2)]; clipCanvas = clip[clipCanvasStr].slice(0); clipAniamtionFn = function clipAniamtionFn(el, clipping) { animationManager.setAnimation({ el: el, attr: { 'clip-rect': clipping }, label: 'container', component: canvas, state: el.attrs['clip-rect'] ? 'updating' : 'appearing' }); }; if (!chartConfig.skipClipping) { clipAniamtionFn(dsGroup, clipCanvas); clipAniamtionFn(dataLabelsLayer, clipCanvas); clipAniamtionFn(quadrantGroup, clipCanvas); clipAniamtionFn(canvas.getChildContainer('sumLabelsLayer'), clip[clipSumValue]); } if (showCanvasBg) { attr = { x: canvasLeft, y: canvasTop, width: canvasWidth, height: canvasHeight, r: canvasBorderRadius, 'stroke-width': 0, 'stroke': NONE, fill: (0, _lib.toRaphaelColor)(canvasBgColor) }; canvasElementCheck && canvasElementCheck.show(); canvasElement = animationManager.setAnimation({ el: canvasElementCheck || 'rect', attr: attr, label: 'rect', container: canvasGroup, component: canvas }); if (!canvasElementCheck) { canvas.addGraphicalElement('canvasElement', canvasElement); } if (shadowOnCanvasFill) { canvasElement.shadow({ opacity: canBGAlpha / 100 }); } else { canvasElement.shadow(false); } } else { canvasElementCheck && animationManager.setAnimation({ el: canvasElementCheck, component: canvas, callback: function callback() { canvasElementCheck.hide(); } }); } }; return Canvas; }(_componentInterface.ComponentInterface); exports['default'] = Canvas; /***/ }), /* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { 'initial.canvas.canvas': function initialCanvasCanvas() { return { 'rect.appearing': function rectAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'initial' }]; }, '*': null }; }, 'update.canvas.canvas': { 'rect.updating': [{ slot: 'middle' }] } }; /***/ }), /* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(367); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var mathMax = Math.max, mathMin = Math.min, mathCeil = Math.ceil, PXSTRING = 'px', POSITION_RIGHT = 'right', POSITION_LEFT = 'left', POSITION_CENTER = 'center', POSITION_TOP = 'top', POSITION_BOTTOM = 'bottom', POSITION_MIDDLE = 'middle', POSITION_START = 'start', POSITION_END = 'end'; (0, _dependencyManager.addDep)({ name: 'captionAnimation', type: 'animationRule', extension: _index2['default'] }); var Caption = function (_ComponentInterface) { _inherits(Caption, _ComponentInterface); function Caption() { _classCallCheck(this, Caption); return _possibleConstructorReturn(this, _ComponentInterface.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ Caption.prototype.getType = function getType() { return 'caption'; }; /** * Sets the name of the component * @return {string} name */ Caption.prototype.getName = function getName() { return 'caption'; }; Caption.prototype.configure = function configure() { var iapi = this.getFromEnv('chart'), chartAttrs = iapi.getFromEnv('chart-attrib'), caption = this, captionConfig = caption.config || {}, style = iapi.getFromEnv('style'), outCanfontFamily = style.outCanfontFamily, outCancolor = style.outCancolor, fontSize = style.fontSize, align = ['top', 'center']; caption.config.text = (0, _lib.parseUnsafeString)(chartAttrs.caption); captionConfig.style = { fontFamily: (0, _lib.pluck)(chartAttrs.captionfont, outCanfontFamily), color: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.captionfontcolor, outCancolor).replace(/^#? ([a-f0-9]+)/ig, '#$1')), fontSize: (0, _lib.pluckNumber)(chartAttrs.captionfontsize, fontSize + 3) + PXSTRING, fontWeight: (0, _lib.pluckNumber)(chartAttrs.captionfontbold) === 0 ? _lib.NORMAL : _lib.BOLD }; if (!captionConfig.align) { captionConfig.align = ''; } captionConfig.align = (0, _lib.pluck)(chartAttrs.captionposition, chartAttrs.captionalignment, POSITION_CENTER); if (captionConfig.align) { align = captionConfig.align.split('-'); align[0] && (align[0] = align[0].toLowerCase()); align[1] && (align[1] = align[1].toLowerCase()); if (align.length < 2) { align[1] = align[0]; } } switch (align[0]) { case POSITION_TOP: captionConfig.isOnTop = 1; break; case POSITION_BOTTOM: captionConfig.isOnTop = 0; break; default: captionConfig.isOnTop = (0, _lib.pluckNumber)(chartAttrs.captionontop, 1); } switch (align[1]) { case POSITION_RIGHT: captionConfig.align = POSITION_END; break; case POSITION_LEFT: captionConfig.align = POSITION_START; break; default: captionConfig.align = POSITION_MIDDLE; } // Spark charts configuration captionPosition and captionOnRight captionConfig.isOnLeft = !(0, _lib.pluckNumber)(chartAttrs.captiononright, 0); captionConfig.captionPosition = (0, _lib.getValidValue)(chartAttrs.captionposition, POSITION_TOP).toLowerCase(); captionConfig.alignWithCanvas = (0, _lib.pluckNumber)(chartAttrs.aligncaptionwithcanvas, iapi.config.alignCaptionWithCanvas, 1); captionConfig.horizontalPadding = (0, _lib.pluckNumber)(chartAttrs.captionhorizontalpadding, captionConfig.alignWithCanvas ? 0 : 15); captionConfig.drawCaption = true; (0, _lib.setLineHeight)(captionConfig.style); }; Caption.prototype.allocatePosition = function allocatePosition() { var caption = this, chart = caption.getFromEnv('chart'); chart._manageCaptionPosition(); }; /** * Draws captions * * @memberof Caption */ Caption.prototype.draw = function draw() { var caption = this, iapi = this.getFromEnv('chart'), chartConfig = iapi.config, animationManager = iapi.getFromEnv('animationManager'), textDirection = iapi.config.textDirection, captionGroup = iapi.getChildContainer().captionGroup, smartLabel = iapi.getFromEnv('smartLabel'), captionElement = caption.getGraphicalElement('captionElement'), toolTipController = caption.getFromEnv('toolTipController'), captionConfig = caption.config, captionStyle = captionConfig.style, hasCaption = captionConfig.text, captionX = captionConfig.x, align = captionConfig.align, captionAttrObj, captionState; // if definition has caption, we proceed creating one and if there // is no caption we remove any previously created caption element. if (hasCaption) { captionAttrObj = { text: captionConfig.text, fill: captionStyle.color, x: captionX, y: captionConfig.y, 'text-anchor': align || POSITION_MIDDLE, 'vertical-align': captionConfig.verticalAlign || POSITION_TOP, visibility: captionConfig.drawCaption ? _lib.visibleStr : _lib.hiddenStr, direction: textDirection }; // If caption is not present, create it. captionElement = caption.addGraphicalElement('captionElement', animationManager.setAnimation({ el: captionElement || 'text', attr: captionAttrObj, container: captionGroup, state: captionState, component: caption, label: 'text' })); captionElement.css(captionStyle); if (chartConfig.showtooltip) { toolTipController.enableToolTip(captionElement, captionConfig.originalText); } else { toolTipController.disableToolTip(captionElement); } if (smartLabel) { smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle(captionStyle); } } else if (captionElement) { // TODO: Investigate captionElement.remove() function animationManager.setAnimation({ el: captionElement, component: caption, callback: function callback() { this.hide(); }, doNotRemove: true }); // caption._graphics.captionElement = captionElement.remove(); } chartConfig.savedCaption = captionElement; }; Caption.prototype.manageSpace = function manageSpace(availableHeight, availableWidth) { var iapi = this.getFromEnv('chart'), chartConfig = iapi.config, caption = iapi.getChildren('caption')[0], subCaption = iapi.getChildren('subCaption')[0], captionConfig = caption.config, subCaptionConfig = subCaption.config, chartAttrs = iapi.getFromEnv('dataSource').chart, SmartLabel = iapi.getFromEnv('smartLabel'), allowedHeight = availableHeight, titleText = (0, _lib.parseUnsafeString)(chartAttrs.caption), subTitleText = (0, _lib.parseUnsafeString)(chartAttrs.subcaption), captionPadding = (0, _lib.pluckNumber)(chartAttrs.captionpadding, 10), oriCapPadding = captionPadding, isPaddingReduced = false, captionObj, subcaptionObj, totalHeight = 0, capStyle, dimensions, subCapStyle, difference = 0, extraSpace = 0, captionLineHeight = 0, subCaptionLineHeight = 0, topGutterWidth = 5, canvas = iapi.getChildren('canvas'), canvasBorderThickness = mathMax(canvas && canvas[0].config.canvasBorderThickness, 0), captionWidth = 0, subCaptionWidth = 0; // text below 3px is not properly visible if (allowedHeight > 3) { if (captionPadding < canvasBorderThickness) { captionPadding = canvasBorderThickness + 2; } if (titleText !== _lib.BLANKSTRING) { // calculatethe single line's height capStyle = captionConfig.style; captionLineHeight = mathCeil((0, _lib.pluckNumber)(parseFloat(capStyle.fontHeight, 10), parseFloat(capStyle.lineHeight, 10), 12)); } if (subTitleText !== _lib.BLANKSTRING) { subCapStyle = subCaptionConfig.style; subCaptionLineHeight = (0, _lib.pluckNumber)(parseInt(subCapStyle.fontHeight, 10), parseInt(subCapStyle.lineHeight, 10), 12); } if (captionLineHeight > 0 || subCaptionLineHeight > 0) { // calculate the min height required allowedHeight = mathMax(allowedHeight, 0); totalHeight = captionLineHeight + subCaptionLineHeight + captionPadding; // now decide whether it has space shgaortfall or excess if (totalHeight > allowedHeight) { difference = allowedHeight - totalHeight; isPaddingReduced = true; // first reduce the padding if (difference < captionPadding) { captionPadding = mathMax(difference, 5); } else { // if the difference is more then padding then remove the subcap also difference -= captionPadding; captionPadding = 0; // if the subcap is gretter then diff add the remaning space to the extraSpace if (subCaptionLineHeight > difference) { extraSpace = subCaptionLineHeight - difference + 10; subCaptionLineHeight = 0; subCaptionConfig._originalText = subCaptionConfig.text; subCaptionConfig.text = _lib.BLANKSTRING; } else { difference -= subCaptionLineHeight; subCaptionLineHeight = 0; // now remove the caption also if (captionLineHeight > difference) { extraSpace = captionLineHeight - difference; } } } } else { extraSpace = allowedHeight - totalHeight; } // //// now place the elements SmartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); if (captionLineHeight > 0) { // set the caption style and get the caption's requared space SmartLabel.setStyle(capStyle); captionLineHeight += extraSpace; captionObj = SmartLabel.getSmartText(titleText, availableWidth, captionLineHeight); extraSpace = captionLineHeight - captionObj.height; captionConfig.height = captionLineHeight = captionObj.height; captionConfig.text = captionObj.text; captionConfig.originalText = captionObj.tooltext ? captionObj.tooltext : false; captionWidth = captionObj.width; } if (subCaptionLineHeight > 0) { // set the caption style and get the caption's requared space SmartLabel.setStyle(subCapStyle); subCaptionLineHeight += extraSpace; subcaptionObj = SmartLabel.getSmartText(subTitleText, availableWidth, subCaptionLineHeight); extraSpace = subCaptionLineHeight - subcaptionObj.height; subCaptionLineHeight = subcaptionObj.height; subCaptionConfig.text = subcaptionObj.text; subCaptionConfig.height = subcaptionObj.height; subCaptionConfig.originalText = subcaptionObj.tooltext ? subcaptionObj.tooltext : false; subCaptionWidth = subcaptionObj.width; } if (isPaddingReduced && extraSpace > 0) { captionPadding += mathMin(oriCapPadding - captionPadding, extraSpace); } captionConfig.captionPadding = captionPadding; captionConfig.height = captionLineHeight; captionConfig.width = captionWidth; subCaptionConfig.width = subCaptionWidth; subCaptionConfig.height = subCaptionLineHeight; // //now add the top margin totalHeight = captionLineHeight + subCaptionLineHeight + captionPadding; } if (totalHeight > chartConfig.canvasHeight) { totalHeight = 0; captionConfig.drawCaption = false; } else { captionConfig.drawCaption = true; } // totalHeight = totalHeight || canvasBorderThickness; if (captionConfig.isOnTop) { dimensions = { top: totalHeight }; } else { dimensions = { bottom: totalHeight, top: topGutterWidth }; } } else { dimensions = { bottom: 0, top: 0 }; captionConfig.drawCaption = false; } return dimensions; }; Caption.prototype.setDimention = function setDimention(pos) { var caption = this, captionConfig = caption.config; captionConfig.x = pos.x; captionConfig.y = pos.y; }; return Caption; }(_componentInterface.ComponentInterface); exports['default'] = Caption; /***/ }), /* 367 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { 'initial.caption.caption': function initialCaptionCaption() { return { 'text.appearing': function textAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'initial' }]; } }; } }; /***/ }), /* 368 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _caption = __webpack_require__(366); var _caption2 = _interopRequireDefault(_caption); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(369); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var mathMax = Math.max, PXSTRING = 'px', POSITION_CENTER = 'center', POSITION_TOP = 'top', POSITION_BOTTOM = 'bottom', POSITION_MIDDLE = 'middle'; (0, _dependencyManager.addDep)({ name: 'subcaptionAnimation', type: 'animationRule', extension: _index2['default'] }); var SubCaption = function (_Caption) { _inherits(SubCaption, _Caption); function SubCaption() { _classCallCheck(this, SubCaption); return _possibleConstructorReturn(this, _Caption.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ SubCaption.prototype.getType = function getType() { return 'caption'; }; /** * Sets the name of the component * @return {string} name */ SubCaption.prototype.getName = function getName() { return 'subCaption'; }; /** * Configures attributes of subcaption * * @memberof SubCaption */ SubCaption.prototype.configure = function configure() { var subCaption = this, chart = subCaption.getFromEnv('chart'), chartAttrs = chart.getFromEnv('chart-attrib'), subCaptionConfig = subCaption.config || {}, style = chart.getFromEnv('style'), caption = chart.getChildren('caption')[0], outCanfontFamily = style.outCanfontFamily, outCancolor = style.outCancolor, fontSize = style.fontSize, align = ['top', 'center']; subCaptionConfig.text = (0, _lib.parseUnsafeString)(chartAttrs.subcaption); if (!subCaptionConfig.align) { subCaptionConfig.align = ''; } subCaptionConfig.align = (0, _lib.pluck)(chartAttrs.captionposition, chartAttrs.captionalignment, POSITION_CENTER); if (caption.config.align) { align = caption.config.align.split('-'); align[0] && (align[0] = align[0].toLowerCase()); align[1] && (align[1] = align[1].toLowerCase()); if (align.length < 2) { align[1] = align[0]; } } switch (align[0]) { case POSITION_TOP: subCaptionConfig.isOnTop = 1;break; case POSITION_BOTTOM: subCaptionConfig.isOnTop = 0;break; default: subCaptionConfig.isOnTop = (0, _lib.pluckNumber)(chartAttrs.captionontop, 1); } subCaptionConfig.alignWithCanvas = (0, _lib.pluckNumber)(chart.aligncaptionwithcanvas, chartAttrs.aligncaptionwithcanvas, 1); subCaptionConfig.horizontalPadding = (0, _lib.pluckNumber)(chartAttrs.captionhorizontalpadding, caption.config.alignWithCanvas ? 0 : 15); subCaptionConfig.style = { fontFamily: (0, _lib.pluck)(chartAttrs.subcaptionfont, chartAttrs.captionfont, outCanfontFamily), color: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.subcaptionfontcolor, chartAttrs.captionfontcolor, outCancolor).replace(/^#? ([a-f0-9]+)/ig, '#$1')), fontSize: (0, _lib.pluckNumber)(chartAttrs.subcaptionfontsize, (0, _lib.pluckNumber)(mathMax((0, _lib.pluckNumber)(chartAttrs.captionfontsize) - 3, -1), fontSize) + (0, _lib.pluckNumber)(chart.subTitleFontSizeExtender, 1)) + PXSTRING, fontWeight: (0, _lib.pluckNumber)(chartAttrs.subcaptionfontbold, chart.subTitleFontWeight, chartAttrs.captionfontbold) === 0 ? _lib.NORMAL : _lib.BOLD }; (0, _lib.setLineHeight)(subCaptionConfig.style); }; /** * Draws sub caption * * @memberof SubCaption */ SubCaption.prototype.draw = function draw() { var subCaption = this, chart = subCaption.getFromEnv('chart'), animationManager = chart.getFromEnv('animationManager'), caption = chart.getChildren('caption')[0], chartConfig = chart.config, textDirection = chartConfig.textDirection, captionGroup = chart.getChildContainer().captionGroup, subCaptionElement = subCaption.getGraphicalElement('subCaptionElement'), toolTipController = subCaption.getFromEnv('toolTipController'), subCaptionConfig = subCaption.config, subCaptionStyle = subCaptionConfig.style, hasSubCaption = subCaptionConfig.text, align = caption.config.align, subCaptionAttrObj = void 0, subCaptionState = void 0; if (hasSubCaption) { subCaptionAttrObj = { text: subCaptionConfig.text, fill: subCaptionStyle.color, x: subCaptionConfig.x, y: subCaptionConfig.y, 'text-anchor': align || POSITION_MIDDLE, 'vertical-align': POSITION_TOP, direction: textDirection, visibility: caption.config.drawCaption ? _lib.visibleStr : _lib.hiddenStr }; subCaptionElement = subCaption.addGraphicalElement('subCaptionElement', animationManager.setAnimation({ el: subCaptionElement || 'text', attr: subCaptionAttrObj, container: captionGroup, state: subCaptionState, component: subCaption, hookFn: function hookFn() { this.css(subCaptionStyle); }, label: 'text' })); subCaptionElement.css(subCaptionStyle); if (chartConfig.showtooltip) { toolTipController.enableToolTip(subCaptionElement, subCaptionConfig.originalText); } else { toolTipController.disableToolTip(subCaptionElement); } } else { subCaptionElement && subCaption.removeGraphicalElement(subCaptionElement); } chartConfig.savedSubCaption = subCaptionElement; }; SubCaption.prototype.setDimention = function setDimention(pos) { this.config.x = pos.x; this.config.y = pos.y; }; return SubCaption; }(_caption2['default']); exports['default'] = SubCaption; /***/ }), /* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _index = __webpack_require__(367); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { 'initial.caption.subCaption': _index2['default']['initial.caption.caption'] }; /***/ }), /* 370 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(371); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var stringConstants = { BACKGROUNDLOADED: 'BackgroundLoaded', BACKGROUNDLOADERROR: 'BackgroundLoadError', clipRectStr: 'clip-rect' }, POSITION_TOP = 'top', POSITION_BOTTOM = 'bottom', POSITION_MIDDLE = 'middle', POSITION_RIGHT = 'right', POSITION_LEFT = 'left', TILE = 'tile', FILL = 'fill', FIT = 'fit', noneStr = void 0, DASH_DEF = noneStr = 'none', getHandler = function getHandler(_this) { var config = _this.config; return { load: function load() { var bgImageDisplayMode = config.bgImageDisplayMode, bgImageVAlign = config.bgImageVAlign, bgImageHAlign = config.bgImageHAlign, bgImageScale = config.bgImageScale, bgSWFAlpha = config.bgSWFAlpha, bgSWF = config.bgSWF, backgroundImage = _this.getGraphicalElement('backgroundImage'), imgRef = backgroundImage._.RefImg, chart = _this.getFromEnv('chart'); /** * This event is fired for external background image for a chart has loaded succesfully. These * background images are applied using the `bgImage` chart attribute. In case loading fails, the * { @link FusionCharts#event.backgroundLoadError } event is fired. * * To know more about how to load and configure chart background image, see: * { @tutorial configuring-your-chart-border-and-background }. * * > This event is not fired if `bgImage` attribute is not provided. * @see FusionCharts#event:backgroundLoadError * @event FusionCharts#backgroundLoaded * @group chart * @param { string } url - URL of the background image * @param { number } bgImageAlpha - The value of the image alpha * @param { string } bgImageDisplayMode - The mode in which the images are displayed in background * of the chart * @param { string } bgImageVAlign - The vertical alignment of the background image * @param { string } bgImageHAlign -The horizontal alignment of the background image */ chart.fireChartInstanceEvent(stringConstants.BACKGROUNDLOADED, { url: bgSWF, bgImageAlpha: bgSWFAlpha, bgImageDisplayMode: bgImageDisplayMode, bgImageVAlign: bgImageVAlign, bgImageHAlign: bgImageHAlign, bgImageScale: bgImageScale, imageheight: imgRef.height, imagewidth: imgRef.width }); }, error: function error(e) { var bgImageDisplayMode = config.bgImageDisplayMode, bgImageVAlign = config.bgImageVAlign, bgImageHAlign = config.bgImageHAlign, bgImageScale = config.bgImageScale, bgSWFAlpha = config.bgSWFAlpha, bgSWF = config.bgSWF, chart = _this.getFromEnv('chart'); /** * This event is fired for external background image for a chart failed to load. These * background images are applied using the `bgImage` chart attribute. * * The cause of failure can be network connectivity issues or invalid value passed to the * `bgImage` attribute. There can also be errors due to cross-domain policies and other security * restrictions enforced by browsers. * * To know more about how to load and configure chart background image, see: * { @tutorial configuring-your-chart-border-and-background }. * * > This event is not fired if `bgImage` attribute is not provided. * @see FusionCharts#event:backgroundLoaded * @event FusionCharts#backgroundLoadError * @group chart * * @param { string } url - The URL of the background image * @param { number } bgImageAlpha - The alpha value of the image. * @param { string } error - Contains error message. * @param { string } bgImageDisplayMode - The mode in which the images are displayed in the * background of the chart. * @param { string } bgImageVAlign - Vertical alignment of the background image. * @param { string } bgImageHAlign - Horizontal alignment of the background image. * @param { number } bgImageScale - The value of the scaling of the image. */ chart.fireChartInstanceEvent(stringConstants.BACKGROUNDLOADERROR, { url: bgSWF, bgImageAlpha: bgSWFAlpha, error: e, bgImageDisplayMode: bgImageDisplayMode, bgImageVAlign: bgImageVAlign, bgImageHAlign: bgImageHAlign, bgImageScale: bgImageScale }); } }; }, COMMA = ',', BLANKSTRING = ''; (0, _dependencyManager.addDep)({ name: 'backgroundAnimation', type: 'animationRule', extension: _index2['default'] }); /** * class definition of background component */ var Background = function (_ComponentInterface) { _inherits(Background, _ComponentInterface); /** * constructor fn */ function Background() { _classCallCheck(this, Background); var _this2 = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this2.config.handler = getHandler(_this2); return _this2; } /** * Sets the name of the component * @return {string} name */ Background.prototype.getName = function getName() { return 'background'; }; /** * Sets the type of the component * @return {string} type */ Background.prototype.getType = function getType() { return 'background'; }; /** * fetches applied cosmetics of background component * @return { Object } contains fcolor object */ Background.prototype._getBackgroundCosmetics = function _getBackgroundCosmetics() { var backGroundComp = this, chartAttrs = backGroundComp.getFromEnv('chart-attrib'), colorM = backGroundComp.getFromEnv('color-manager'), is3D = backGroundComp.getFromEnv('chartConfig').is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D; return { FCcolor: { color: (0, _lib.pluck)(chartAttrs.bgcolor, colorM.getColor(palleteString.bgColor)), alpha: (0, _lib.pluck)(chartAttrs.bgalpha, colorM.getColor(palleteString.bgAlpha)), angle: (0, _lib.pluck)(chartAttrs.bgangle, colorM.getColor(palleteString.bgAngle)), ratio: (0, _lib.pluck)(chartAttrs.bgratio, colorM.getColor(palleteString.bgRatio)) } }; }; /** * function to create component and configure and also configure the chart * It creates components which are depend on data and configure them and also configure chart * It calls helper function namely, configure * @param {Object} dataObj contains json data of the chart */ Background.prototype.configureAttributes = function configureAttributes() { var backGroundComp = this, config = backGroundComp.config, chartAttrs = backGroundComp.getFromEnv('chart-attrib'), chartConfig = backGroundComp.getFromEnv('chartConfig'), is3D = chartConfig.is3D, colorM = backGroundComp.getFromEnv('color-manager'), chartBorderWidth, showBorder, bgImageVAlign, bgImageHAlign, bgImageDisplayMode = config.bgImageDisplayMode = (0, _lib.pluck)(chartAttrs.bgimagedisplaymode, noneStr).toLowerCase(); config.bgSWF = (0, _lib.pluck)(chartAttrs.bgimage, chartAttrs.bgswf); config.bgSWFAlpha = (0, _lib.pluckNumber)(chartAttrs.bgimagealpha, chartAttrs.bgswfalpha, 100); showBorder = config.showBorder = (0, _lib.pluckNumber)(chartAttrs.showborder, chartConfig.showBorder, is3D ? 0 : 1); config.borderWidth = Math.max(showBorder ? (0, _lib.pluckNumber)(chartAttrs.borderthickness, 1) : 0, 0); config.borderRadius = (0, _lib.pluckNumber)(chartAttrs.borderradius, 0); config.borderDashStyle = (0, _lib.pluckNumber)(chartAttrs.borderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttrs.borderdashlen, 4), (0, _lib.pluckNumber)(chartAttrs.borderdashgap, 2), chartBorderWidth) : DASH_DEF; config.borderAlpha = (0, _lib.pluck)(chartAttrs.borderalpha, is3D ? '100' : colorM && colorM.getColor('borderAlpha')); config.borderColor = (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.bordercolor, is3D ? '#666666' : colorM && colorM.getColor('borderColor')), config.borderAlpha); config.bgImageVAlign = bgImageVAlign = (0, _lib.getValidValue)(chartAttrs.bgimagevalign, BLANKSTRING).toLowerCase(); config.bgImageHAlign = bgImageHAlign = (chartAttrs.bgimagehalign || BLANKSTRING).toLowerCase(); config.bgImageScale = (0, _lib.pluckNumber)(chartAttrs.bgimagescale, 100); config.containerBackgroundColor = (0, _lib.getContainerBackgroundColor)(backGroundComp.getFromEnv('chartInstance')); config.backgroundColor = backGroundComp._getBackgroundCosmetics(); if (bgImageDisplayMode === TILE || bgImageDisplayMode === FILL || bgImageDisplayMode === FIT) { if (bgImageVAlign !== POSITION_TOP && bgImageVAlign !== POSITION_MIDDLE && bgImageVAlign !== POSITION_BOTTOM) { config.bgImageVAlign = POSITION_MIDDLE; } if (bgImageHAlign !== POSITION_LEFT && bgImageHAlign !== POSITION_MIDDLE && bgImageHAlign !== POSITION_RIGHT) { config.bgImageHAlign = POSITION_MIDDLE; } } else { if (bgImageVAlign !== POSITION_TOP && bgImageVAlign !== POSITION_MIDDLE && bgImageVAlign !== POSITION_BOTTOM) { config.bgImageVAlign = POSITION_TOP; } if (bgImageHAlign !== POSITION_LEFT && bgImageHAlign !== POSITION_MIDDLE && bgImageHAlign !== POSITION_RIGHT) { config.bgImageHAlign = POSITION_LEFT; } } }; /** * handles draw job of this component */ Background.prototype.draw = function draw() { var backGroundComp = this, paper = backGroundComp.getFromEnv('paper'), backgroundElementDummy = backGroundComp.getGraphicalElement('backgroundElement'), backgroundElement, borderElementDummy = backGroundComp.getGraphicalElement('borderElement'), borderElement, config = backGroundComp.config, chart = backGroundComp.getFromEnv('chart'), chartConfig = backGroundComp.getFromEnv('chartConfig'), attrObj, backgroundColor = config.backgroundColor, animationManager = backGroundComp.getFromEnv('animationManager'), backgroundImageDummy = backGroundComp.getGraphicalElement('backgroundImage'), backgroundImage, bgSWF = config.bgSWF, backgroundGroup = chart.getChildContainer('backgroundGroup'), chartWidth = chartConfig.width, chartHeight = chartConfig.height, chartBorderWidth = config.borderWidth || 0, borderRadius = config.borderRadius, borderDashStyle = config.borderDashStyle, borderColor = config.borderColor, bgSWFAlpha = config.bgSWFAlpha, imgClipRect = chartBorderWidth + COMMA + chartBorderWidth + COMMA + (chartWidth - chartBorderWidth * 2) + COMMA + (chartHeight - chartBorderWidth * 2), bgImageDisplayMode = config.bgImageDisplayMode, bgImageVAlign = config.bgImageVAlign, bgImageHAlign = config.bgImageHAlign, bgImageScale = config.bgImageScale, height, width; paper.canvas.style.backgroundColor = config.containerBackgroundColor; width = chartWidth - chartBorderWidth * 2; height = chartHeight - chartBorderWidth * 2; attrObj = { x: chartBorderWidth, y: chartBorderWidth, width: width < 0 ? 0 : width, height: height > 0 ? height : 0, stroke: _lib.preDefStr.noneStr, fill: (0, _lib.toRaphaelColor)(backgroundColor) }; // Create/reuse bckgroundelement backgroundElement = animationManager.setAnimation({ el: backgroundElementDummy || 'rect', attr: attrObj, container: backgroundGroup, component: backGroundComp, label: 'rect' }); backgroundElement.show(); if (!backgroundElementDummy) { backGroundComp.addGraphicalElement('backgroundElement', backgroundElement); } width = chartWidth - chartBorderWidth; height = chartHeight - chartBorderWidth; attrObj = { x: chartBorderWidth / 2, y: chartBorderWidth / 2, width: width < 0 ? 0 : width, height: height > 0 ? height : 0, stroke: borderColor, 'stroke-width': chartBorderWidth, 'stroke-dasharray': borderDashStyle, fill: _lib.preDefStr.noneStr, r: borderRadius || 0 }; // Create/reuse chart borderelement borderElement = animationManager.setAnimation({ el: borderElementDummy || 'rect', attr: attrObj, container: backgroundGroup, component: backGroundComp, label: 'rect' }); borderElement.show(); if (!borderElementDummy) { backGroundComp.addGraphicalElement('borderElement', borderElement); } if (bgSWF && !backGroundComp.getState('removed')) { // create/reuse imagegrid backgroundImage = animationManager.setAnimation({ el: backgroundImageDummy || 'imagegrid', attr: { imagegrid: [bgImageDisplayMode, bgImageVAlign, bgImageHAlign, bgImageScale, chartBorderWidth, chartWidth, chartHeight], src: bgSWF, opacity: bgSWFAlpha * 0.01, 'clip-rect': imgClipRect }, container: backgroundGroup, component: backGroundComp, label: 'imagegrid' }); backgroundImage.show(); if (!backgroundImageDummy) { // if background image is not created previsouly then create one and add as graphical element backGroundComp.addGraphicalElement('backgroundImage', backgroundImage); // add onload and onerror event handler backgroundImage.on('load', config.handler.load); backgroundImage.on('error', config.handler.error); } } else { backgroundImageDummy && backGroundComp.removeGraphicalElement(backgroundImageDummy); } }; return Background; }(_componentInterface.ComponentInterface); exports['default'] = Background; /***/ }), /* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { 'initial.background.background': function initialBackgroundBackground() { return { 'rect.appearing': function rectAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'initial' }]; } }; } }; /***/ }), /* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _chartPaletteColors = __webpack_require__(373); var defaultPaletteOptions = _interopRequireWildcard(_chartPaletteColors); var _isArray = __webpack_require__(374); var _isArray2 = _interopRequireDefault(_isArray); 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"); } } /** * parseColorMix method parses the color mix formula and returns * an array of colors depending of the constituents specified in * the formula. * @param aColor Actual color on which calculations will be based on. * @param mix Formula containing the mix of colors. * Example: ('943A0A','{light-50},FFFFFF,{color},{dark-25}') * @return Array of colors containing the required mix of colors (in RGB) - not HEX */ function parseColorMix(aColor, mix) { // Create a return array var rtnArr = [], strConsts = ColorManager.stringConstants, dashIndex, intensity, // Now, split into main tokens tokens, colors, j, defToken, defColor, token, color, removeBrecReg, i; // Remove all spaces from the formula mix = mix.replace(/\s/g, strConsts.BLANK); // Convert to lower case for case insensitive comparison mix = mix.toLowerCase(); // If mix is blank, UNDEF or null, return the single color if (mix === strConsts.BLANK || mix === null || typeof mix === 'undefined') { rtnArr = [aColor]; } else { // Now, split into main tokens tokens = mix.split(strConsts.COMMASTRING); // split COlors into Array colors = aColor.split(strConsts.COMMASTRING); j = Math.max(tokens.length, colors.length, 1); defToken = tokens[0]; defColor = colors[0]; removeBrecReg = /[\{\}]/ig; // Iterate through each token to check what it is. for (i = 0; i < j; i++) { // Remove { and } from token. token = (tokens[i] || defToken).replace(removeBrecReg, ''); color = colors[i] || defColor; // Now, based on what token is, we take action if (token === 'color') { // If actual color rtnArr.push(color); } else if (token.substr(0, 5) === 'light') { // Need to find lighter shade // First find the intensity, which the user has specified. // Get dash index dashIndex = token.indexOf('-'); intensity = dashIndex === -1 ? 1 : token.substr(dashIndex + 1, token.length - dashIndex); // Now in actual method, 0 means lightest and 1 means normal. So, we've to reverse intensity = 100 - intensity; // Push the lighter color in array rtnArr.push((0, _lib.getLightColor)(color, intensity)); } else if (token.substr(0, 4) === 'dark') { // Need to find darker shade // First find the intensity, which the user has specified. // Get dash index dashIndex = token.indexOf('-'); intensity = dashIndex === -1 ? 1 : token.substr(dashIndex + 1, token.length - dashIndex); // Now in actual method, 0 means darkest and 1 means normal. So, we've to reverse intensity = 100 - intensity; // Push the darker color in array rtnArr.push((0, _lib.getDarkColor)(color, intensity)); } else { // User has himself given a normal hex color code. // So, convert and append rtnArr.push(token); } } } // Return array return rtnArr; } /** * parseAlphaList method takes a list of alphas separated * by comma and returns an array of the individual alphas * @param strAlphas List of alphas separated by comma e.g., * 20,30,40 etc. * @param numColors Number of colors for which we've to build * the alpha list * @return An array whose each cell contains a single * alpha value (validated). */ function parseAlphaList(strAlphas, numColors) { // Input list of alpha // Extract the input alphas var arrInputAlphas = strAlphas.toString().split(ColorManager.stringConstants.COMMASTRING), // Final list arrAlphas = [], // Count of valid alphas alpha, usedAlpha = 100, // Loop variable i; // Change the alpha matrix to number (from string base) for (i = 0; i < numColors; i++) { // Get the alpha alpha = (0, _lib.pluckNumber)(arrInputAlphas[i]); // Now, if the alpha is non-numeric or UNDEF, we set our own values // alpha = (isNaN(alpha) || (alpha == UNDEF)) ? 100 : Number(alpha); if (ColorManager.defined(alpha)) { usedAlpha = alpha; } // Store it in the array arrAlphas[i] = usedAlpha; } // Return the array return arrAlphas.join(); } /** * parseRatioList method takes a list of color division ratios * (on base of 100%) separated by comma and returns an array of * the individual ratios (on base of 255 hex). * @param strRatios List of ratios (on base of 100%) separated by * comma e.g., 20,40,40 or 5,5,90 etc. * @param numColors Number of colors for which we've to build * the ratio list * @return An array whose each cell contains a single * ratio value (on base of 255 hex). */ function parseRatioList(strRatios, numColors) { // Arrays to store input and final ratio // Split the user input ratios var arrInputRatios = strRatios.split(ColorManager.stringConstants.COMMASTRING), arrRatios = [], // Sum of ratios sumRatio = 0, ratio, // Loop variable i; // First, check if all ratios are numbers and calculate sum for (i = 0; i < numColors; i++) { // Get the ratio ratio = arrInputRatios[i]; // Now, if the ratio is non-numeric or UNDEF, we set our own values ratio = isNaN(ratio) || typeof ratio === 'undefined' ? 0 : Math.abs(Number(ratio)); // If ratio is greater than 100, restrict it to 100 ratio = ratio > 100 ? 100 : ratio; // Allot it to final array arrRatios[i] = ratio; // Add to sum sumRatio += ratio; } // Total ratio inputted by user should not exceed 100 sumRatio = sumRatio > 100 ? 100 : sumRatio; // If more colors are present than the number of ratios, we need to // proportionately append the rest of values if (arrInputRatios.length < numColors) { for (i = arrInputRatios.length; i < numColors; i++) { arrRatios[i] = (100 - sumRatio) / (numColors - arrInputRatios.length); } } // Now, convert ratio percentage to actual values from 0 to 255 (Hex base) arrRatios[-1] = 0; // Return the ratios array return arrRatios.join(); } var ColorManager = function () { function ColorManager(chart) { _classCallCheck(this, ColorManager); this.parseColorMix = parseColorMix; this.parseAlphaList = parseAlphaList; this.parseRatioList = parseRatioList; this.linkedItems = { iapi: chart }; this.configure(); this.paletteColors = ['AFD8F8', 'F6BD0F', '8BBA00', 'FF8E46', '008E8E', 'D64646', '8E468E', '588526', 'B3AA00', '008ED6', '9D080D', 'A186BE', 'CC6600', 'FDC689', 'ABA000', 'F26D7D', 'FFF200', '0054A6', 'F7941C', 'CC3300', '006600', '663300', '6DCFF6']; } ColorManager.prototype.configure = function configure() { var cm = this, strConsts = ColorManager.stringConstants, iapi = cm.linkedItems.iapi, dataObj = iapi.getFromEnv('dataSource'), FCChartObj = dataObj.chart || {}, pO = cm.paletteOptions = (0, _lib.extend2)((0, _lib.extend2)({}, defaultPaletteOptions), iapi.defaultPaletteOptions || {}, false, true), themeColor = cm.themeEnabled = FCChartObj.palettethemecolor; cm.paletteIndex = (FCChartObj.palette > 0 && FCChartObj.palette < 6 ? FCChartObj.palette : (0, _lib.pluckNumber)(iapi.paletteIndex, 1)) - 1; cm.iterator = 0; cm.paletteColors = pO.paletteColors[cm.themeEnabled ? 0 : cm.paletteIndex]; if (ColorManager.defined(FCChartObj.palettecolors) && FCChartObj.palettecolors !== strConsts.BLANK) { cm.paletteColors = (0, _isArray2['default'])(FCChartObj.palettecolors) ? FCChartObj.palettecolors.slice() : FCChartObj.palettecolors.split(/\s*\,\s*/); } cm.paletteLen = cm.paletteColors.length; cm.useFlatColors = (0, _lib.pluckNumber)(FCChartObj.useflatdataplotcolor, iapi.useFlatColor, 0); if (themeColor) { cm.paletteIndex = 5; // Color pO.bgColor[5] = (0, _lib.getLightColor)(themeColor, 35) + strConsts.COMMASTRING + (0, _lib.getLightColor)(themeColor, 10); pO.bgAngle[5] = 270; pO.bgRatio[5] = strConsts.BGRATIOSTRING; pO.bgAlpha[5] = '50,50'; pO.canvasBgColor[5] = strConsts.COLOR_WHITE; pO.canvasBgAngle[5] = 0; pO.canvasBgAlpha[5] = strConsts.HUNDREDSTRING; pO.canvasBgRatio[5] = strConsts.BLANK; // Color pO.canvasBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 80); pO.canvasBorderAlpha[5] = 100; pO.showShadow[5] = 1; // Color??? pO.divLineColor[5] = (0, _lib.getDarkColor)(themeColor, 20); pO.divLineAlpha[5] = 40; // Color pO.altHGridColor[5] = (0, _lib.getLightColor)(themeColor, 20); pO.altHGridAlpha[5] = 15; // Color pO.altVGridColor[5] = (0, _lib.getLightColor)(themeColor, 80); pO.altVGridAlpha[5] = 10; pO.anchorBgColor[5] = strConsts.COLOR_WHITE; pO.toolTipBgColor[5] = strConsts.COLOR_WHITE; // Color pO.toolTipBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 80); // Color pO.baseFontColor[5] = themeColor.split && themeColor.split(strConsts.COMMASTRING)[0]; // Color pO.borderColor[5] = (0, _lib.getDarkColor)(themeColor, 60); pO.borderAlpha[5] = 50; pO.legendBgColor[5] = strConsts.COLOR_WHITE; // Color pO.legendBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 80); pO.plotGradientColor[5] = strConsts.COLOR_WHITE; // Color pO.plotBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 85); // Color pO.plotFillColor[5] = (0, _lib.getDarkColor)(themeColor, 85); // -------------- For 3D Chart --------------// pO.bgColor3D[5] = strConsts.COLOR_WHITE; pO.bgAlpha3D[5] = strConsts.HUNDREDSTRING; pO.bgAngle3D[5] = 90; pO.bgRatio3D[5] = strConsts.BLANK; // Color ??? pO.canvasBgColor3D[5] = (0, _lib.getLightColor)(themeColor, 20); // Color ??? pO.canvasBaseColor3D[5] = (0, _lib.getLightColor)(themeColor, 40); // Color ??? pO.divLineColor3D[5] = (0, _lib.getDarkColor)(themeColor, 20); pO.divLineAlpha3D[5] = 40; // Color ??? pO.legendBgColor3D[5] = strConsts.COLOR_WHITE; // Color ??? pO.legendBorderColor3D[5] = (0, _lib.getDarkColor)(themeColor, 80); pO.toolTipbgColor3D[5] = strConsts.COLOR_WHITE; // Color ??? pO.toolTipBorderColor3D[5] = (0, _lib.getDarkColor)(themeColor, 80); // Color ??? pO.baseFontColor3D[5] = themeColor.split && themeColor.split(strConsts.COMMASTRING)[0]; pO.anchorBgColor3D[5] = strConsts.COLOR_WHITE; // Gauges pO.tickColor && (pO.tickColor[5] = (0, _lib.getDarkColor)(themeColor, 90)); pO.trendDarkColor && (pO.trendDarkColor[5] = (0, _lib.getDarkColor)(themeColor, 90)); pO.trendLightColor && (pO.trendLightColor[5] = (0, _lib.getLightColor)(themeColor, pO.TrendLightShadeOffset)); pO.msgLogColor && (pO.msgLogColor[5] = (0, _lib.getLightColor)(themeColor, 80)); // Chart specific colors // Angular Gauge Chart pO.dialColor && (pO.dialColor[5] = (0, _lib.getDarkColor)(themeColor, 95) + ',FFFFFF,' + (0, _lib.getDarkColor)(themeColor, 95)); pO.dialBorderColor && (pO.dialBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 95) + ',FFFFFF,' + (0, _lib.getDarkColor)(themeColor, 95)); pO.pivotColor && (pO.pivotColor[5] = (0, _lib.getLightColor)(themeColor, 95) + ',FFFFFF,' + (0, _lib.getLightColor)(themeColor, 95)); pO.pivotBorderColor && (pO.pivotBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 95) + ',FFFFFF,' + (0, _lib.getDarkColor)(themeColor, 95)); // Linear Gauge pO.pointerBorderColor && (pO.pointerBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 75)); pO.pointerBgColor && (pO.pointerBgColor[5] = (0, _lib.getDarkColor)(themeColor, 75)); // Thermometer gauge pO.thmBorderColor && (pO.thmBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 90)); pO.thmFillColor && (pO.thmFillColor[5] = (0, _lib.getLightColor)(themeColor, 55)); // Thermometer gauge pO.gaugeBorderColor && (pO.gaugeBorderColor[5] = (0, _lib.getDarkColor)(themeColor, 90)); pO.gaugeFillColor && (pO.gaugeFillColor[5] = (0, _lib.getLightColor)(themeColor, 55)); // Cylinder gauge pO.cylFillColor && (pO.cylFillColor[5] = (0, _lib.getLightColor)(themeColor, 55)); pO.periodColor && (pO.periodColor[5] = (0, _lib.getLightColor)(themeColor, 10)); // Methods for win loss chart only ??? pO.winColor && (pO.winColor[5] = '666666'); pO.lossColor && (pO.lossColor[5] = 'CC0000'); pO.drawColor && (pO.drawColor[5] = '666666'); pO.scorelessColor && (pO.scorelessColor[5] = 'FF0000'); // Gantt Chart pO.gridColor && (pO.gridColor[5] = (0, _lib.getLightColor)(themeColor, 30)); pO.categoryBgColor && (pO.categoryBgColor[5] = (0, _lib.getLightColor)(themeColor, 10)); pO.dataTableBgColor && (pO.dataTableBgColor[5] = (0, _lib.getLightColor)(themeColor, 10)); pO.gridResizeBarColor && (pO.gridResizeBarColor[5] = (0, _lib.getDarkColor)(themeColor, 90)); pO.scrollBarColor && (pO.scrollBarColor[5] = (0, _lib.getLightColor)(themeColor, 50)); } }; /** * getColor find the relevant required color from a given entity/element * key eg. bgColor, canvasBgColor, plotBorderColor etc. * @param {string} key the name of entity/element to retrieve color * @return {string} hexcolor */ ColorManager.prototype.getColor = function getColor(key) { // Return color return this.paletteOptions[key][this.paletteIndex]; }; /** * getPlotColor find the relevant required color for chart's dataplot * from a given index or auto generate after incrementing index by 1 * @param {number} index of the color in paletteColors Array * @return {string} hexcolor */ ColorManager.prototype.getPlotColor = function getPlotColor(index) { var cm = this, paletteColors = cm.paletteColors, strColor = cm.useFlatColors ? cm.getColor('plotFillColor') : paletteColors[index % cm.paletteLen]; // Get the color if (!strColor) { // If iterator is out of bound, reset it to 0 if (cm.iterator === cm.paletteLen) { cm.iterator = 0; } strColor = paletteColors[cm.iterator]; // Increment iterator cm.iterator += 1; } // Return color return strColor; }; return ColorManager; }(); ColorManager.stringConstants = { BLANK: '', COMMASTRING: ',', BGRATIOSTRING: '0,100', COLOR_WHITE: 'FFFFFF', HUNDREDSTRING: '100' }; ColorManager.defined = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; exports['default'] = ColorManager; /***/ }), /* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var paletteColorsArr = ['AFD8F8', 'F6BD0F', '8BBA00', 'FF8E46', '008E8E', 'D64646', '8E468E', '588526', 'B3AA00', '008ED6', '9D080D', 'A186BE', 'CC6600', 'FDC689', 'ABA000', 'F26D7D', 'FFF200', '0054A6', 'F7941C', 'CC3300', '006600', '663300', '6DCFF6'], BGRATIOSTRING = '0,100', COLOR_WHITE = 'FFFFFF', HUNDREDSTRING = '100', BLANK = '', verticalRotation = 270, OPAQUE = 100; var paletteColors = exports.paletteColors = [paletteColorsArr, paletteColorsArr, paletteColorsArr, paletteColorsArr, paletteColorsArr], bgColor = exports.bgColor = ['CBCBCB,E9E9E9', 'CFD4BE,F3F5DD', 'C5DADD,EDFBFE', 'A86402,FDC16D', 'FF7CA0,FFD1DD'], bgAngle = exports.bgAngle = [verticalRotation, verticalRotation, verticalRotation, verticalRotation, verticalRotation], bgRatio = exports.bgRatio = [BGRATIOSTRING, BGRATIOSTRING, BGRATIOSTRING, BGRATIOSTRING, BGRATIOSTRING], bgAlpha = exports.bgAlpha = ['50,50', '60,50', '40,20', '20,10', '30,30'], canvasBgColor = exports.canvasBgColor = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], canvasBgAngle = exports.canvasBgAngle = [0, 0, 0, 0, 0], canvasBgAlpha = exports.canvasBgAlpha = [HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING], canvasBgRatio = exports.canvasBgRatio = [BLANK, BLANK, BLANK, BLANK, BLANK], canvasBorderColor = exports.canvasBorderColor = ['545454', '545454', '415D6F', '845001', '68001B'], canvasBorderAlpha = exports.canvasBorderAlpha = [OPAQUE, OPAQUE, OPAQUE, 90, OPAQUE], showShadow = exports.showShadow = [0, 1, 1, 1, 1], divLineColor = exports.divLineColor = ['717170', '7B7D6D', '92CDD6', '965B01', '68001B'], divLineAlpha = exports.divLineAlpha = [40, 45, 65, 40, 30], altHGridColor = exports.altHGridColor = ['EEEEEE', 'D8DCC5', '99C4CD', 'DEC49C', 'FEC1D0'], altHGridAlpha = exports.altHGridAlpha = [50, 35, 10, 20, 15], altVGridColor = exports.altVGridColor = ['767575', 'D8DCC5', '99C4CD', 'DEC49C', 'FEC1D0'], altVGridAlpha = exports.altVGridAlpha = [10, 20, 10, 15, 10], anchorBgColor = exports.anchorBgColor = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], toolTipBgColor = exports.toolTipBgColor = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], toolTipBorderColor = exports.toolTipBorderColor = ['545454', '545454', '415D6F', '845001', '68001B'], baseFontColor = exports.baseFontColor = ['555555', '60634E', '025B6A', 'A15E01', '68001B'], borderColor = exports.borderColor = ['767575', '545454', '415D6F', '845001', '68001B'], borderAlpha = exports.borderAlpha = [50, 50, 50, 50, 50], legendBgColor = exports.legendBgColor = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], legendBorderColor = exports.legendBorderColor = ['545454', '545454', '415D6F', '845001', 'D55979'], plotGradientColor = exports.plotGradientColor = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], plotBorderColor = exports.plotBorderColor = ['333333', '8A8A8A', COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], plotFillColor = exports.plotFillColor = ['767575', 'D8DCC5', '99C4CD', 'DEC49C', 'FEC1D0'], // -------------- For 3D Chart --------------// bgColor3D = exports.bgColor3D = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], bgAlpha3D = exports.bgAlpha3D = [HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING, HUNDREDSTRING], bgAngle3D = exports.bgAngle3D = [90, 90, 90, 90, 90], bgRatio3D = exports.bgRatio3D = [BLANK, BLANK, BLANK, BLANK, BLANK], canvasBgColor3D = exports.canvasBgColor3D = ['DDE3D5', 'D8D8D7', 'EEDFCA', 'CFD2D8', 'FEE8E0'], canvasBaseColor3D = exports.canvasBaseColor3D = ['ACBB99', 'BCBCBD', 'C8A06C', '96A4AF', 'FAC7BC'], divLineColor3D = exports.divLineColor3D = ['ACBB99', 'A4A4A4', 'BE9B6B', '7C8995', 'D49B8B'], divLineAlpha3D = exports.divLineAlpha3D = [OPAQUE, OPAQUE, OPAQUE, OPAQUE, OPAQUE], legendBgColor3D = exports.legendBgColor3D = ['F0F3ED', 'F3F3F3', 'F7F0E8', 'EEF0F2', 'FEF8F5'], legendBorderColor3D = exports.legendBorderColor3D = ['C6CFB8', 'C8C8C8', 'DFC29C', 'CFD5DA', 'FAD1C7'], toolTipbgColor3D = exports.toolTipbgColor3D = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE], toolTipBorderColor3D = exports.toolTipBorderColor3D = ['49563A', '666666', '49351D', '576373', '681C09'], baseFontColor3D = exports.baseFontColor3D = ['49563A', '4A4A4A', '49351D', '48505A', '681C09'], anchorBgColor3D = exports.anchorBgColor3D = [COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE, COLOR_WHITE]; /***/ }), /* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * Returns true if the provided parameter is an array * * @param {*} x The parameter to be checked * * @return {Boolean} */ exports["default"] = function (x) { return Array.isArray(x); }; /***/ }), /* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { '*.*.*': { '*.disappearing': [{ finalAttr: { opacity: 0 }, slot: 'initial', callback: function callback() { this.hide(); } }] } }; /***/ }), /* 376 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var canvas = chart.getChildren('canvas')[0], axisRefVisualCartesian = canvas.getChildren('axisRefVisualCartesian')[0], zoomObj = { zoomable: true, pannable: true }, config = chart._feedAxesRawData(), yAxis = void 0, xAxis = void 0, redraw = function redraw(e) { var sender = e.sender; axisRefVisualCartesian.addexplicitDrawItems(sender.getId(), sender); axisRefVisualCartesian.asyncDraw(); }; (0, _lib.componentFactory)(chart, _numeric2['default'], 'yAxis', 1, config.yAxisConf); (0, _lib.componentFactory)(chart, _category2['default'], 'xAxis', 1, config.xAxisConf); yAxis = chart.getChildren('yAxis')[0]; xAxis = chart.getChildren('xAxis')[0]; yAxis.setLinkedItem('canvas', canvas); xAxis.setLinkedItem('canvas', canvas); axisRefVisualCartesian.setLinkedItem(yAxis.getId(), yAxis); axisRefVisualCartesian.setLinkedItem(xAxis.getId(), xAxis); axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, xAxis); axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, yAxis); canvas.attachAxis(xAxis, false, chart.zoomX ? zoomObj : {}); canvas.attachAxis(yAxis, true, chart.zoomY ? zoomObj : {}); chart._setCategories(); }; var _lib = __webpack_require__(125); var _numeric = __webpack_require__(377); var _numeric2 = _interopRequireDefault(_numeric); var _category = __webpack_require__(422); var _category2 = _interopRequireDefault(_category); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 377 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesianLabelManager = __webpack_require__(378); var _cartesianLabelManager2 = _interopRequireDefault(_cartesianLabelManager); var _lib = __webpack_require__(125); var _range = __webpack_require__(398); var _range2 = _interopRequireDefault(_range); var _linear = __webpack_require__(399); var _linear2 = _interopRequireDefault(_linear); var _commonApi = __webpack_require__(386); var _domainUpdater = __webpack_require__(421); var _domainUpdater2 = _interopRequireDefault(_domainUpdater); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0; /** * The Cartesian Axis is a special kind of axis which is used to uniquely identify points in a plane * using two numbers. * * This class takes care of all cosmetics and calculations related to rendering a cartesian axis on * a chart. In addition it also takes care of drawing the ticks, the labels and the scroll bars of * the axis. * @class */ var NumericAxis = function (_CartesianLabelManage) { _inherits(NumericAxis, _CartesianLabelManage); /** * Instantiates the axis with some instance members */ function NumericAxis() { _classCallCheck(this, NumericAxis); var _this = _possibleConstructorReturn(this, _CartesianLabelManage.call(this)); _this.config.scale = new _linear2['default'](); return _this; } /** * Sets the name of the component * @return {string} name */ NumericAxis.prototype.getName = function getName() { return 'numeric'; }; NumericAxis.prototype.generateTicks = function generateTicks() { var scale = this.getScale(), axisConfig = this.config, divLines = axisConfig.numDivLines + 1, _scale$getDomain = scale.getDomain(), scaleMin = _scale$getDomain[0], scaleMax = _scale$getDomain[1], ticks = void 0, axisRange = axisConfig.axisRange, min = axisRange.min, max = axisRange.max, dataLimit = axisConfig.dataLimit, tickInterval = void 0, diff = void 0; if (scaleMin === min && scaleMax === max) { (0, _domainUpdater2['default'])(dataLimit.min, dataLimit.max, scale, axisConfig); return axisConfig.ticks; } else { ticks = scale.ticks(divLines); tickInterval = Math.abs(ticks[1] - ticks[0]); if (scaleMin === min && ticks.indexOf(min) === -1) ticks.unshift(min); if (scaleMax === max && ticks.indexOf(max) === -1) ticks.push(max); if (diff = Math.abs(min % tickInterval)) min -= diff; if (diff = Math.abs(max % tickInterval)) max -= diff; axisConfig._allTicks = (0, _range2['default'])(min, max, tickInterval).concat(max); axisRange.tickInterval = tickInterval; return ticks; } }; NumericAxis.prototype.setTickValues = function setTickValues(tickValues) { this.config.userTicks = tickValues || []; this.config.tickValues = { tickValue: [] }; }; NumericAxis.prototype._parseTickValues = function _parseTickValues(tickValues) { var axis = this, chart = axis.getFromEnv('chart'), axisConfig = axis.config, len = tickValues && tickValues.length, countCat = 0, tickArr, tickObj, index, tickX; // Initialize the tickvalues object axisConfig.tickValues = {}; // this will store only the tickvalues not the vline tickArr = axisConfig.tickValues.tickValue = []; // Storing ticks and vline for (index = 0; index < len; index += 1) { tickObj = (0, _lib.extend2)({}, tickValues[index]); // For ticks axis which gets placed with x (Candlestick). // for normal ticks tickX = NaN tickX = Number(tickObj.x); if (!tickObj.vline) { // parse and store style (0, _commonApi.extractStyleInfo)(tickObj, chart); // if (tickX === tickX) if (tickX || tickX === 0) { // If tickX is present, save the integer value tickObj.x = tickX; // And set a flag to indicate irregular tick axis axisConfig.irregularCatAxis = true; } else { continue; } tickArr.push(tickObj); tickArr[countCat].label = (0, _lib.parseUnsafeString)(tickArr[countCat].label); countCat += 1; } } // oriCatLen is the number of categories in the user given category array excluding the vlines axisConfig.oriCatLen = countCat; }; /** * Calculate the categories on basis of xAxisLabelMode values */ NumericAxis.prototype.calculateTicksOnLabelMode = function calculateTicksOnLabelMode() { var axis = this, axisConfig = axis.config, xAxisLabelMode = axisConfig.xAxisLabelMode, tickArr = Object.assign([], axisConfig.userTicks), numberFormatter = axis.getFromEnv('number-formatter'), numberFormatterFn, tempCat, i, j, len, ticks, numericLineStyle; if (xAxisLabelMode === 'mixed' || xAxisLabelMode === 'auto') { tempCat = []; numberFormatterFn = numberFormatter.xAxis; if (xAxisLabelMode === 'mixed') { for (i = 0, len = tickArr.length; i < len; i += 1) { tempCat[tickArr[i].x || tickArr[i].y || i] = true; } } else { tickArr = []; } numericLineStyle = axis.getAxisConfig(); ticks = axisConfig.ticks; for (j = 0; j < ticks.length; ++j) { i = ticks[j]; if (!tempCat[i]) { tickArr.push({ 'label': _lib.BLANKSTRING + numberFormatterFn.call(numberFormatter, i), 'x': i, 'showverticalline': i === 0 ? numericLineStyle.showZeroPlane : 1, 'isNumeric': true, linecolor: i === 0 ? numericLineStyle.zeroPlaneColor : numericLineStyle.divLineColor, linealpha: i === 0 ? numericLineStyle.zeroPlaneAlpha : numericLineStyle.divLineAlpha, linethickness: i === 0 ? numericLineStyle.zeroPlaneThickness : numericLineStyle.divLineThickness, linedashed: numericLineStyle.divLineIsDashed, linedashLen: numericLineStyle.divLineDashLen, linedashgap: numericLineStyle.divLineDashGap }); } } } axis._parseTickValues(tickArr); }; NumericAxis.prototype.getInterval = function getInterval() { return this.config.axisRange.tickInterval; }; /** * Function to set the axis range from (used for axis drawing) out side. * @param {Object} data Axis range object the values to be changed */ NumericAxis.prototype._setAxisRange = function _setAxisRange(data) { var min = data.min, max = data.max, axisConfig = this.config, axisRange = axisConfig.axisRange, dataLimit = axisConfig.dataLimit, dependentLimit, limitChanged, decrease, dependentInfo = axisConfig.dependentInfo; if (min > max) { return; } if (dataLimit.min !== min || dataLimit.max !== max) limitChanged = true; if (axisConfig.visibleMin !== UNDEF && !axisConfig.setPadding && !limitChanged) { axisConfig.setPadding = false; } else { var _extent = (0, _lib.extent)([min, max, dataLimit.min, dataLimit.max]); // for candle stick the xAxis is same and the limits for both dataset // of different canvas should be considered min = _extent[0]; max = _extent[1]; dataLimit.min = min; dataLimit.max = max; this.fireEvent('dataLimitSet', Object.assign({}, dataLimit)); // if the axis is dependent upon some info from other axis if (dependentInfo) { // if the axis is dependent upon limit when syncaxislimits is on if (dependentInfo.limit) { dependentLimit = dependentInfo.dataLimit; // if the axis has got the required dependent info then it will further calculate if (dependentLimit) { var _extent2 = (0, _lib.extent)([min, max, dependentLimit.min, dependentLimit.max]); min = _extent2[0]; max = _extent2[1]; axisConfig.isDataLimitSet = true; } else { return; } } if (dependentInfo.count) { if (dependentInfo.numDivLines === UNDEF) { return; } } } (0, _domainUpdater2['default'])(min, max, this.getScale(), axisConfig); decrease = axisConfig.isZeroTickForced ? 3 : 2; this.fireEvent('divlinesSet', axisConfig.ticks.length - decrease); axisConfig.tickValues && this.calculateTicksOnLabelMode(); this.setVisibleConfig(axisRange.min, axisRange.max); } }; return NumericAxis; }(_cartesianLabelManager2['default']); NumericAxis.prototype.setDataLimit = _commonApi.setDataLimit; exports['default'] = NumericAxis; /***/ }), /* 378 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesian = __webpack_require__(379); var _cartesian2 = _interopRequireDefault(_cartesian); var _lib = __webpack_require__(125); var _commonApi = __webpack_require__(386); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } // padding between two labels when they are rotated var ROTATED_LABEL_PADDING = 3, ROTATED_LABEL_MIN_GAP = 10; var CartesainLabelManager = function (_Cartesian) { _inherits(CartesainLabelManager, _Cartesian); function CartesainLabelManager() { _classCallCheck(this, CartesainLabelManager); return _possibleConstructorReturn(this, _Cartesian.apply(this, arguments)); } /** * Function will give the hidth height of the maximum label present * @param {number} maxHeight The maximum height of the label * @return {Object} Object Containing the width and height of the max length label */ CartesainLabelManager.prototype._getHMaxLabelDimention = function _getHMaxLabelDimention(maxHeight) { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, smartLabel = chart.getFromEnv('smartLabel'), axisRange = axisConfig.axisRange, labels = axisConfig.labels, labelDisplay = axisConfig.labelDisplay, slantLabel = axisConfig.slantLabel, labelStyle = labels.style, userMaxLabelHeight = axisConfig.maxLabelHeight, increment = axis.getInterval(), staggerLines = axisConfig.staggerLines, labelStep = axisConfig.labelStep, canvasLeft = chartConfig.canvasLeft, canvasRight = chartConfig.canvasRight, rWidthAdjstFactor = staggerLines - 2, labelHeightAllotment, sWidthAdjstFactor, staggerLineAvailed, max = axisRange.max, min = axisRange.min, maxTextSize = 0, allCategories = axisConfig.tickValues && axisConfig.tickValues.tickValue, allCategoryLen = allCategories && allCategories.length, distributedColumns = chart.distributedColumns, labelGap, categoryLength = 0, singleCategory, overriddenStyle, intervalWidth, maxLabelObj = { text: _lib.UNDEF, width: 0, style: _lib.UNDEF }, maxLabelHeight = 0, smartLabelText, axisXPadding = 4, getAllottedWidth, getAllottedHeight, confMeasurement, updateCategoryMeta = _lib.stubFN, finalRotationDecision = _lib.stubFN, reCalculateStaggerLines = _lib.stubFN, testString = 'WWW', W = 'W', minPxPerLabel = 60, categoryAxisMeasurement = {}, maxText, countValue, firstValue, firstLabel, lastLabel, i, count, text, value, numberFormatterFn, retObj, cumulativeSum = 0, defTextPadding = 2, reCalrequired = false, skipCount = 0, defaultSpanRadius = 2, lastStepX, forceHeight, categoryCalculationInitiated = false, refSmartText, limit, minIrrPx, prevCategory, lastMinIrrStep = Number.POSITIVE_INFINITY, firstCategory, lastCategory, catLength, isZoomed, prevStyleStr, currStyleStr, ticks = axisConfig.ticks, ln, tick, minIrrStep = Number.POSITIVE_INFINITY; // minimum-irregular-step // special flag which is true only for marimekko charts as category labels are uneven in it if (distributedColumns) { for (i = 0; i < allCategoryLen; i++) { if (allCategories[i + 1]) { if (allCategories[i].x) { // calculate plotwidth as the distance between two successive category labels allCategories[i].plotWidth = axis.getPixel(allCategories[i + 1].x - allCategories[i].x) - axis.getPixel(0); } } else { // for the last label take canvasRight as the right boundary allCategories[i].plotWidth = axis.getPixel(chartConfig.canvasRight - allCategories[i].x) - axis.getPixel(0); } } } if (axisConfig.tickValues && (!allCategories || allCategories.length === 0)) { return { width: 0, height: 0 }; } if (labelDisplay === 'rotate') { axisConfig.rotateLabels = 1; } if (!axisConfig.tickValues) { axisConfig.irregularCatAxis = false; } axisConfig.sWidthAdjstFactor = sWidthAdjstFactor = rWidthAdjstFactor === 0 ? 1 : rWidthAdjstFactor === 1 ? 1.5 : rWidthAdjstFactor; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle({ fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }); /** * Gets the distance between the left and right margins * @param {number} x Any integer between min or max * @param {string} position The side which sould be taken as reference for calculation. Can be 'left' * or 'right' * @return {number} The distance from a point to left or right extremes */ function getMarginalDistance(x, position) { switch (position.toLowerCase()) { case 'left': return Math.abs(axis._getCustomPixel(x)); case 'right': return Math.abs(chartConfig.width - axis._getCustomPixel(x)); } } if (axisConfig.irregularCatAxis) { allCategories.sort(function (m, n) { return m.x - n.x; }); // If it is an irregular cat axis the calculation of intervalWidth would not be straight // forward. // Finds the minimum difference between all the legend for (i = 0, categoryLength = allCategories.length; i < categoryLength; i++) { singleCategory = allCategories[i]; if (typeof lastStepX !== 'undefined') { minIrrStep = Math.abs(singleCategory.x - lastStepX); minIrrPx = Math.abs(axis._getCustomPixel(min) - axis._getCustomPixel(min + minIrrStep)); smartLabel.setStyle(Object.assign({}, singleCategory.style)); refSmartText = smartLabel.getOriSize(W); limit = refSmartText.width; // (limit * 1.2) calculates extra space around the label. 10% of the original size to // the left and 10% to the right if (minIrrPx < limit * 1.2) { singleCategory.label = ''; minIrrStep = lastMinIrrStep; continue; } // Saves individual interval width on right side for each labels insted of the common // one prevCategory._individualIWR = minIrrPx; // Saves individual interval width on left side for each labels insted of the common // one singleCategory._individualIWL = minIrrPx; lastMinIrrStep = minIrrStep; } prevCategory = singleCategory; lastStepX = singleCategory.x; } if (minIrrStep === Number.POSITIVE_INFINITY) { // If only one label is found // Minimum step would be minimum of distance from the point to the right side and // from the leftside minIrrStep = Math.floor(Math.min(singleCategory.x, max - singleCategory.x)); // The final minIrrStep would be the maximum of the previous calculation and the // defaultSpanRadius, as the defaultSpanRadius would be the least space available minIrrStep = Math.max(minIrrStep, 2 * defaultSpanRadius); } for (i = 0, categoryLength = allCategories.length; i < categoryLength; i++) { singleCategory = allCategories[i]; // Since now there is a scope of leaving space for the end values so making width infinite // will truncate the end labels unnecessarily if (!i) { singleCategory._individualIWL = Infinity; // getMarginalDistance(singleCategory.x, 'left'); } if (i === categoryLength - 1) { singleCategory._individualIWR = Infinity; // getMarginalDistance(singleCategory.x, 'right'); } singleCategory.individualIW = Math.min(singleCategory._individualIWL, singleCategory._individualIWR); } // Intermediate intervalWidth calculation to get the intervalWidth w.r.t minIrrStep only without // considering the marginal labels overflow intervalWidth = Math.abs(axis._getCustomPixel(min) - axis._getCustomPixel(min + minIrrStep)); // Takes care of the marginal labels overflow by calculating the minimum of the left available, // right available space and previously get intervalWidth intervalWidth = Math.min(2 * getMarginalDistance(allCategories[0].x, 'left'), 2 * getMarginalDistance(allCategories[categoryLength - 1].x, 'right'), intervalWidth); } else { intervalWidth = Math.abs(axis._getCustomPixel(min) - axis._getCustomPixel(min + increment)); } // Override the max height if the user has given his own value maxHeight = userMaxLabelHeight || maxHeight; /* * The root definitation of measurements functions of the category axis. * If a new measurement object is created by a id, a new object is created if not already saved in * store. If the object is created first time, the new object will get the properties of the root. * The new measurement could override any existing feature. * * __root__ is an internal property. */ categoryAxisMeasurement.__root__ = { /* * Get the allotted height for individual label. * @param categoryIndex {Integer} - index of the category */ getHeight: function getHeight(i) { var cat = allCategories[i], lineHeight = cat._ovrStyle.lineHeight, lineHeightInt = parseInt(lineHeight.replace(/(\d+)px/, '$1'), 10); return lineHeightInt; }, /* * Get the allotted height for individual label. */ getWidth: function getWidth() { return maxHeight; }, getCalculatedLabelStep: function getCalculatedLabelStep(allCatArr) { var _i = 0, _l = allCatArr.length, _maxSpan = Number.NEGATIVE_INFINITY, _maxCatObj = {}, styleStr, style, label, _cat, _catLabel, key, possibleLabelsNo, labelCount = 0, referenceSide, slHeight, _fStep; // If style is not present, initialize with {} for (_i = 0; _i < _l; _i++) { _cat = allCatArr[_i]; _cat.style = _cat.style || {}; } if (axisConfig.irregularCatAxis) { return axisConfig.labelStep; } for (_i = 0; _i < _l; _i++) { _cat = allCatArr[_i]; // // @todo validate whether the neighbour labels should use the space of an emty label // if (!(_cat && _cat.label)) { // continue; // } if (!_cat) { continue; } _cat.label || (_cat.label = ''); _catLabel = _cat.oriLabel || _cat.label; overriddenStyle = { fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }; labelCount++; _cat.style = _cat.style || {}; (0, _lib.extend2)(overriddenStyle, _cat.style); styleStr = overriddenStyle.fontSize + overriddenStyle.fontFamily + overriddenStyle.lineHeight + overriddenStyle.fontWeight; if (_maxCatObj[styleStr]) { if (_catLabel.length > _maxCatObj[styleStr].label.length) { _maxCatObj[styleStr].label = _catLabel; } } else { _maxCatObj[styleStr] = { label: _catLabel, style: overriddenStyle }; } } for (key in _maxCatObj) { if (_maxCatObj.hasOwnProperty(key)) { style = _maxCatObj[key].style; label = _maxCatObj[key].label; style.lineHeight = (0, _lib.setLineHeight)(style); smartLabel.setStyle(style); axisConfig.rotateLabels && (slHeight = parseInt(style.lineHeight.replace(/(\d+)px/, '$1'), 10)); smartLabelText = smartLabel.getSmartText(label, _lib.UNDEF, slHeight); referenceSide = axisConfig.rotateLabels === 0 ? smartLabelText.width > minPxPerLabel ? minPxPerLabel : smartLabelText.width : smartLabelText.height; _maxSpan = Math.max(referenceSide, _maxSpan); } } possibleLabelsNo = Math.floor(Math.abs(axis._getCustomPixel(max) - axis._getCustomPixel(min)) / _maxSpan); // intervalWidth will be recalculated with the label step _fStep = Math.max(Math.ceil(labelCount / possibleLabelsNo), axisConfig.labelStep); intervalWidth = Math.abs(axis._getCustomPixel(min) - axis._getCustomPixel(min + _fStep)); if (labelCount <= possibleLabelsNo) { return axisConfig.labelStep; } // intervalWidth = axisConfig.rotateLabels === 0 ? Math.min(intervalWidth, minPxPerLabel) : // intervalWidth; // intervalWidth -= axisXPadding; return _fStep; } }; // This is the container where all other properties / states are set and get. This is to reduce // number of attributed directly put on categoryAxisMeasurement object categoryAxisMeasurement._inProp = {}; /* * Get a copy of the default configuration created by the id. If the configration was retrieved * using some id previously, and same is requested, it returns the saved one. If it was never * requested before a new copy is created and returned. */ categoryAxisMeasurement.getCopyById = function (id) { var cam = this, propStore = cam._inProp, root = cam.__root__, copyStore = propStore.copyStore, copyById; copyStore = copyStore || {}; copyById = copyStore[id]; // If a copy is found in core, return it if (copyById) { return copyById; } // Create a new copy copying all the properties from the root and retirn it (0, _lib.extend2)(copyById = copyStore[id] = {}, root); return copyById; }; if (axisConfig.tickValues) { // Category axis label orientation switch (labelDisplay) { case 'rotate': if (slantLabel) { labels.rotation = 300; } else { labels.rotation = 270; } confMeasurement = categoryAxisMeasurement.getCopyById('rotate'); break; case 'stagger': confMeasurement = categoryAxisMeasurement.getCopyById('stagger'); confMeasurement.getHeight = function (categoryIndex) { var allCat, cat, catStyle, metrics; allCat = axisConfig.tickValues.tickValue; cat = allCat[categoryIndex]; catStyle = cat && cat.style || (cat.style = {}); overriddenStyle = { fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }; (0, _lib.extend2)(overriddenStyle, catStyle); smartLabel.setStyle(overriddenStyle); metrics = smartLabel.getOriSize(cat.label); return metrics.height; }; confMeasurement.getWidth = function (cat) { // for stagger mode the axis padding will be 1 pixel axisXPadding = 1; return cat.individualIW ? cat.individualIW : 2 * intervalWidth * sWidthAdjstFactor - axisXPadding; }; reCalculateStaggerLines = function reCalculateStaggerLines(categories) { var category, categoryLength = categories.length, lastElement, defLineHeight, lastCSum = 0, index, rSum, calStaggerLines, itrStep, smartTestText; smartLabel.setStyle(labelStyle); smartTestText = smartLabel.getOriSize(testString); defLineHeight = smartTestText.height; // If the cumulative sum of the last element is same or less than the sum of // heights of all the elements, the value of staggerLines can be derived // mathematically from a equation. // If n be the number of labels in stagger and l be the height of one label and // h is the allotted height to draw the labels. // n = floor(h / l) lastElement = categories[categoryLength - 1]; if (Math.floor(lastElement._cumulativeSum) <= Math.ceil(categoryLength * (defLineHeight + defTextPadding))) { // Calulate the stagger lines from the equation calStaggerLines = Math.floor(maxHeight / defLineHeight); // If the value of the staggerLines is less than the maximum stagger possible, // keep the one user has given staggerLines = calStaggerLines - staggerLines < 0 ? calStaggerLines : staggerLines; } else { // Calculate the max staggerLine if all of the labels have same style. This // reduces the number of iterations calStaggerLines = Math.floor(maxHeight / (defLineHeight + 2 * defTextPadding)); do { // Reset last cumulative sum to zero if the staggerLines needs to be // re-calculated lastCSum = 0; itrStep = calStaggerLines; for (index = itrStep - 1, categoryLength = categories.length; index < categoryLength;) { // Since the step is more than one, it is possible that the last couple // of elements remain un iterated. This detects this and if it happens // moves to the left if (categoryLength - index < calStaggerLines) { index = categoryLength - 1; } category = categories[index]; // Get the height of the block, if it was placed in stagger rSum = category._cumulativeSum - lastCSum; if (~~rSum > -~maxHeight) { // If the block length is greater than the allotted height, break // the flow reCalrequired = true; break; } else { reCalrequired = false; } lastCSum = category._cumulativeSum; index += itrStep; } } while (calStaggerLines-- && reCalrequired); calStaggerLines++; // If the value of the staggerLines is less than the maximum stagger possible, // keep the one user has given staggerLines = Math.min(staggerLines, calStaggerLines); } axisConfig.drawnStaggerLines = staggerLines; }; updateCategoryMeta = function updateCategoryMeta(categories) { var category, catStyle, categoryLength, catLineHeight, index, nonSkipCount = 0; for (index = 0, categoryLength = categories.length; index < categoryLength; index++) { category = categories[index]; if (category.stepSkipped) { continue; } catStyle = category && category.style || {}; if (!(catLineHeight = catStyle.lineHeight)) { catLineHeight = labelStyle.lineHeight; } staggerLineAvailed = nonSkipCount++ % staggerLines; if (staggerLineAvailed) { category.labelPadding = catLineHeight.replace(/px/i, '') * staggerLineAvailed; } else { category.labelPadding = 0; } } }; break; case 'none': confMeasurement = categoryAxisMeasurement.getCopyById('none'); // The user does not need any of management to happen hence unlimited space is returned. confMeasurement.getHeight = _lib.stubFN; confMeasurement.getWidth = _lib.stubFN; finalRotationDecision = _lib.stubFN; if (axisConfig.rotateLabels) { if (slantLabel) { labels.rotation = 300; } else { labels.rotation = 270; } // If rotation is applied, the label is calculated with unlimited space but when // rendered, the chart resizes to its maximum limit, keeping the label space // unmanaged forceHeight = maxHeight; } confMeasurement.getCalculatedLabelStep = function () { return axisConfig.labelStep; }; break; default: // If labelDisplay is automatic confMeasurement = categoryAxisMeasurement.getCopyById('auto'); confMeasurement.getHeight = function () { return maxHeight; }; confMeasurement.getWidth = function (cat) { return cat.individualIW ? cat.individualIW : intervalWidth - 2 * axisXPadding; }; finalRotationDecision = function finalRotationDecision(style, categories) { var autoWrapLimit, absMaxSmartText, i, categoryLength, category, catStyle, chartAttr = chart.getFromEnv('chart-attrib'), userRotation = (0, _lib.pluckNumber)(chartAttr && chartAttr.rotatelabels); if (axisConfig.irregularCatAxis) { return; } smartLabel.setStyle(style); absMaxSmartText = smartLabel.getOriSize(testString); autoWrapLimit = absMaxSmartText.width; if (autoWrapLimit >= intervalWidth && userRotation !== 0) { labels.rotation = slantLabel ? 300 : 270; labels.forceRotate = true; confMeasurement = categoryAxisMeasurement.getCopyById('rotate'); getAllottedWidth = confMeasurement.getWidth; getAllottedHeight = confMeasurement.getHeight; maxLabelObj.width = 0; for (i = 0, categoryLength = categories.length; i < categoryLength; i++) { category = categories[i]; if (!(category && (category.label || category.oriLabel)) || (0, _lib.pluckNumber)(category.showlabel, axisConfig.showLabels, 1) === 0 || category.stepSkipped === true) { continue; } catStyle = category._ovrStyle; smartLabel.setStyle({ fontSize: catStyle.fontSize, fontFamily: catStyle.fontFamily, lineHeight: catStyle.lineHeight, fontWeight: catStyle.fontWeight }); smartLabelText = smartLabel.getSmartText(category.oriLabel, getAllottedWidth(category), getAllottedHeight(i)); category.label = smartLabelText.text; category.labelTooltext = smartLabelText.tooltext; category._sLabel = smartLabelText; // @todo Don't do it from here. Do it from the loop from where it is getting // called if (maxLabelObj.width < smartLabelText.width) { maxLabelObj.text = smartLabelText.text; maxLabelObj.width = smartLabelText.width; maxLabelObj.height = smartLabelText.height; maxLabelObj.style = catStyle; } } maxText = maxLabelObj.text; } }; break; } getAllottedWidth = confMeasurement.getWidth; getAllottedHeight = confMeasurement.getHeight; labelStep = axisConfig.labels.step = axisConfig.labelStep = axisConfig._oriLabelStep; labelStep = axisConfig.labels.step = axisConfig.labelStep = confMeasurement.getCalculatedLabelStep(allCategories); firstValue = (0, _cartesian.minimumEnquiry)(allCategories); for (i = firstValue, countValue = 0, count = 0, categoryLength = allCategories.length; i < categoryLength; i++, countValue++) { singleCategory = allCategories[i]; if (!(singleCategory && (singleCategory.label || singleCategory.oriLabel)) || (0, _lib.pluckNumber)(singleCategory.showlabel, axisConfig.showLabels, 1) === 0) { continue; } categoryCalculationInitiated = true; overriddenStyle = { // If labelfontsize is present at data/category level, use it. Else, use default font size. // Same applies for fontFamily and fontWeight fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }; (0, _lib.extend2)(overriddenStyle, singleCategory.style); overriddenStyle.lineHeight = (0, _lib.setLineHeight)(overriddenStyle); currStyleStr = overriddenStyle.fontSize + overriddenStyle.fontFamily + overriddenStyle.lineHeight + overriddenStyle.fontWeight; // Note setStyle is very expansive if (currStyleStr !== prevStyleStr) { smartLabel.setStyle(overriddenStyle); prevStyleStr = currStyleStr; } if (countValue % labelStep) { // If labelStep is provided, sets a flag so that other module knows about it singleCategory.stepSkipped = true; // Keep count of the skipped elements singleCategory.appliedSmartLabel = false; skipCount++; continue; } else { singleCategory.appliedSmartLabel = true; singleCategory.stepSkipped = false; } singleCategory._ovrStyle = overriddenStyle; if (allCategories[i].plotWidth) { labelHeightAllotment = Math.max(labelDisplay === 'rotate' ? allCategories[i].plotWidth - 2 * ROTATED_LABEL_PADDING : 0, getAllottedHeight(i)); } else { if (labelDisplay === 'rotate') { // if labelDisplay is rotate, find the Gap between the curresponding points. // Maintain a constant gap and allocate rest of the space to the label as its max allowed height if (i < categoryLength - 1) { labelGap = axis.getPixel(i + 1) - axis.getPixel(i) - ROTATED_LABEL_MIN_GAP; } } else { labelGap = 0; } // The following condition is true when only one label is present if (labelDisplay === 'rotate' && isNaN(+labelGap)) { labelGap = chartConfig.canvasWidth / axis.getVisibleLength() - ROTATED_LABEL_PADDING; } labelHeightAllotment = Math.max(labelGap, getAllottedHeight(i)); } smartLabelText = smartLabel.getSmartText(singleCategory.oriLabel || singleCategory.label, getAllottedWidth(singleCategory), labelHeightAllotment); cumulativeSum += smartLabelText.height + defTextPadding; // Store the width and height of the label text axis.components.labels[count++] = { config: { width: smartLabelText.width, height: smartLabelText.height, props: { label: {} } } }; singleCategory._cumulativeSum = cumulativeSum; singleCategory.oriLabel = singleCategory.oriLabel || singleCategory.label; singleCategory.label = smartLabelText.text; singleCategory.labelTooltext = smartLabelText.tooltext; singleCategory._sLabel = smartLabelText; if (maxLabelObj.width < smartLabelText.oriTextWidth) { (0, _lib.extend2)(maxLabelObj, smartLabelText); maxLabelObj.style = overriddenStyle; } if (maxLabelHeight < smartLabelText.height) { maxLabelHeight = smartLabelText.height; } } if (!categoryCalculationInitiated) { return { height: 0, width: 0 }; } reCalculateStaggerLines(allCategories, skipCount); updateCategoryMeta(allCategories, skipCount); finalRotationDecision(maxLabelObj.style, allCategories); maxText = maxLabelObj.text || ''; if (axisConfig.xAxisLabelMode === 'mixed') { if (axisConfig.isPercent) { numberFormatterFn = chart.getFromEnv('number-formatter').percentValue; } else { numberFormatterFn = chart.getFromEnv('number-formatter').xAxis; } // calculating the label max width and height maxTextSize = maxText.length; for (i = 0, ln = ticks && ticks.length; i < ln; ++i) { value = ticks[i]; text = '' + numberFormatterFn.call(chart.getFromEnv('number-formatter'), value, axisConfig.axisIndex); if (text.length > maxTextSize) { maxText = text; maxTextSize = text.length; } } } maxLabelObj.height = Math.max(maxLabelHeight, maxLabelObj.height || 0); catLength = allCategories.length; for (i = 0, categoryLength = allCategories.length; i < categoryLength; i++) { firstCategory = allCategories[i]; if (firstCategory._sLabel) { break; } } for (categoryLength = allCategories.length, i = categoryLength - 1; i >= 0; i--) { lastCategory = allCategories[i]; if (lastCategory._sLabel) { break; } } isZoomed = axis.getZoom() !== 1; if (!labels.rotation && !isZoomed && firstCategory._sLabel) { axisConfig.axisEndLabelDisplaySpace.left = Math.max(canvasLeft - (axis._getCustomPixel(firstCategory.x || 0) - firstCategory._sLabel.width / 2), 0); axisConfig.axisEndLabelDisplaySpace.right = Math.max(axis._getCustomPixel(lastCategory.x || catLength - 1) + lastCategory._sLabel.width / 2 - canvasRight, 0); } else { axisConfig.axisEndLabelDisplaySpace.left = 0; axisConfig.axisEndLabelDisplaySpace.right = 0; } retObj = maxLabelObj; } else { if (axisConfig.numberFormatterFn) { numberFormatterFn = chart.getFromEnv('number-formatter')[axisConfig.numberFormatterFn]; } else if (axisConfig.isPercent) { numberFormatterFn = chart.getFromEnv('number-formatter').percentValue; } else { numberFormatterFn = chart.getFromEnv('number-formatter').xAxis; } // calculating the label max width and height // TODO : smartly calculate the max width height for (i = 0, ln = ticks && ticks.length; i < ln; ++i) { tick = ticks[i]; value = (0, _lib.toPrecision)(tick, 10); text = '' + numberFormatterFn.call(chart.getFromEnv('number-formatter'), value, axisConfig.axisIndex); if (tick === min) { firstLabel = text; } if (tick === max) { lastLabel = text; } retObj = smartLabel.getOriSize(text); // Store the width and height of the label text axis.components.labels[i] = { config: { width: retObj.width, height: retObj.height, props: { label: {} } } }; if (text.length > maxTextSize) { maxText = text; maxTextSize = text.length; } } smartLabel.setStyle({ fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }); retObj = smartLabel.getOriSize(maxText || ''); // Decide the rotations of the labels if (labelDisplay === 'rotate') { labels.rotation = 270; } if (axisConfig.rotateLabels) { if (slantLabel) { labels.rotation = 300; } else { labels.rotation = 270; } } if (!labels.rotation) { firstLabel = smartLabel.getOriSize(firstLabel || ''); lastLabel = smartLabel.getOriSize(lastLabel || ''); axisConfig.axisEndLabelDisplaySpace.left = firstLabel.width / 2 + 2; axisConfig.axisEndLabelDisplaySpace.right = lastLabel.width / 2 + 2; } } if (axisConfig.tickValues && labelDisplay === 'stagger') { retObj.height = staggerLines * maxLabelObj.height; } // If the label height is forcefully curbed, this happens when the label is larger than the the max // allowed height, redefine the width (since it only happens when labeldisplay is none in rotate // mode). retObj.width = forceHeight ? Math.min(forceHeight, retObj.width) : retObj.width; retObj.width = (0, _lib.pluckNumber)(retObj.width); retObj.maxWidth = (0, _lib.pluckNumber)(retObj.maxWidth); return retObj; }; /** * Function will give the height of the maximum label present * @param {number} maxWidth The maximum height of the label * @return {Object} Object containing the width and height of the max length label */ CartesainLabelManager.prototype._getVMaxLabelDimention = function _getVMaxLabelDimention(maxWidth) { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, smartLabel = chart.getFromEnv('smartLabel'), labelStyle = axisConfig.labels.style, useEllipsesWhenOverflow = axisConfig.useEllipsesWhenOverflow, maxLabelWidthPercent = axisConfig.maxLabelWidthPercent, minLabelWidthPercent = axisConfig.minLabelWidthPercent, maxTextSize = 0, categories = chart.getFromEnv('dataSource').categories, maxTextDimention = { height: 0, width: 0 }, maxText, tempMaxWidth, tempMinWidth, i, ln, ticks = axisConfig.ticks, value, text, allCategories, categoryLength, singleCategory, smartLabelText, numberFormatterFn, categoriesStyle = {}, categoryStyle, singleCategoryStyle; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle({ fontSize: labelStyle.fontSize, fontFamily: labelStyle.fontFamily, lineHeight: labelStyle.lineHeight, fontWeight: labelStyle.fontWeight }); if (axisConfig.tickValues) { if (categories) { categoriesStyle = { fontFamily: categories[0].font, fontSize: categories[0].fontsize, color: categories[0].fontcolor }; } if (maxLabelWidthPercent) { tempMaxWidth = maxLabelWidthPercent / 100 * chartConfig.width; if (tempMaxWidth < maxWidth) { maxWidth = tempMaxWidth; } } /** * maxWidth is set to tempMinWidth if tempMinWidth is greater than maxWidth. * tempMinWidth is calculated when minLabelWidthPercent is provided. */ if (minLabelWidthPercent) { tempMinWidth = minLabelWidthPercent / 100 * chartConfig.width; if (tempMinWidth > maxWidth) { maxWidth = tempMinWidth; } } allCategories = axisConfig.tickValues.tickValue; for (i = 0, categoryLength = allCategories.length; i < categoryLength; i++) { singleCategory = allCategories[i]; if ((0, _lib.pluckNumber)(singleCategory.showlabel, axisConfig.showLabels) === 0) { continue; } categoryStyle = { fontFamily: (0, _lib.pluck)(singleCategory.font, singleCategory.labelfont, categoriesStyle.fontFamily, labelStyle.fontFamily), fontSize: (0, _lib.pluck)(singleCategory.fontsize, singleCategory.labelfontsize, categoriesStyle.fontSize, labelStyle.fontSize).replace(/px/i, '') + 'px', fontWeight: labelStyle.fontWeight == 'normal' ? (0, _lib.pluckNumber)(singleCategory.fontbold, singleCategory.labelfontbold, 0) ? 'bold' : 'normal' : labelStyle.fontWeight, fontStyle: labelStyle.fontStyle == 'normal' ? (0, _lib.pluckNumber)(singleCategory.fontitalic, singleCategory.labelfontitalic, 0) ? 'italic' : 'normal' : labelStyle.fontStyle }; singleCategoryStyle = { fontFamily: (0, _lib.pluck)(categoryStyle.fontFamily, categoriesStyle.fontFamily, labelStyle.fontFamily), fontSize: (0, _lib.pluck)(categoryStyle.fontSize, categoriesStyle.fontSize, labelStyle.fontSize), fontWeight: (0, _lib.pluck)(categoryStyle.fontWeight, labelStyle.fontWeight), fontStyle: (0, _lib.pluck)(categoryStyle.fontStyle, labelStyle.fontStyle) }; singleCategoryStyle.lineHeight = (0, _lib.setLineHeight)(singleCategoryStyle); smartLabel.setStyle(singleCategoryStyle); smartLabelText = smartLabel.getSmartText(singleCategory.oriLabel || singleCategory.label, maxWidth, labelStyle.lineHeight, useEllipsesWhenOverflow); // Set to axis config for annotation macros axis.components.labels[i] = { config: { width: smartLabelText.width, height: smartLabelText.height, props: { label: {} } } }; singleCategory.oriLabel = singleCategory.oriLabel || singleCategory.label; singleCategory.label = text = smartLabelText.text; singleCategory.labelTooltext = smartLabelText.tooltext; if (smartLabelText.width > maxTextSize) { maxTextDimention = smartLabelText; maxTextSize = smartLabelText.width; } } return maxTextDimention; } else { if (axisConfig.numberFormatterFn) { numberFormatterFn = chart.getFromEnv('number-formatter')[axisConfig.numberFormatterFn]; } else if (axisConfig.isPercent) { numberFormatterFn = chart.getFromEnv('number-formatter').percentValue; } else { numberFormatterFn = chart.getFromEnv('number-formatter').yAxis; } // calculating the label max width and height // TODO : smartly calculate the max width height for (i = 0, ln = ticks && ticks.length; i < ln; ++i) { value = (0, _lib.toPrecision)(ticks[i], 10); text = '' + numberFormatterFn.call(chart.getFromEnv('number-formatter'), value, axisConfig.axisIndex); smartLabelText = smartLabel.getSmartText(text); axis.components.labels[i] = { config: { width: smartLabelText.width, height: smartLabelText.height, props: { label: {} } } }; if (text.length > maxTextSize) { maxText = text; maxTextSize = text.length; } } } return smartLabel.getOriSize(maxText); }; /** * Returns a a number after formatting it through the number formatter * @param {number} num The number to be formatted * @param {Any} abs Absolute value * @return {string} The formatted value */ CartesainLabelManager.prototype.getCleanValue = function getCleanValue(num, abs) { var axis = this, numberFormatter = axis.getFromEnv('number-formatter'); return numberFormatter.getCleanValue(num, abs); }; CartesainLabelManager.prototype.generateMinorTicks = function generateMinorTicks() { if (this) return []; }; /** * Function define the canvas diameter if not axis will take it from the default chart canvas * @param {Object} data containing the axis dimentions */ CartesainLabelManager.prototype.setCanvas = function setCanvas(data) { var axis = this, axisConfig = axis.config; axisConfig.canvas = data; }; /** * Given an interval, this changes the number formatter in use at present * @param {number} interval The interval to adjust the number formatter against */ CartesainLabelManager.prototype._adjustNumberFormatter = function _adjustNumberFormatter(interval) { var axis = this, axisConfig = axis.config, axisIndex = axisConfig.axisIndex, isVertical = axisConfig.isVertical, chart = axis.getFromEnv('chart'), numberFormatter = chart.getFromEnv('number-formatter'), defaultDecimalPrecision = axisConfig._defaultDecimalPrecision, defaultForceDecimal = axisConfig._defaultForceDecimal, dec, beforeZero = 0, formatConfig; if (isVertical || axisConfig.numberFormatterFn === 'yAxis') { formatConfig = (numberFormatter.Y[axisIndex] || numberFormatter.Y[0]).yAxisLabelConf; } else { formatConfig = numberFormatter.paramX; } defaultDecimalPrecision !== _lib.UNDEF ? formatConfig.decimalprecision = defaultDecimalPrecision : axisConfig._defaultDecimalPrecision = formatConfig.decimalprecision; defaultForceDecimal !== _lib.UNDEF ? formatConfig.forcedecimals = defaultForceDecimal : axisConfig._defaultForceDecimal = formatConfig.forcedecimals; // If integer part is greater than zero no need of adjustment if (parseInt(interval, 10) > 0) { return; } // Get the fraction part as a string dec = interval.toString().split('.')[1]; if (dec) { // Extract the number of zero in the begining because if no of decimal in // numberFormatter is less or equal to the number zero then same number may repeat. beforeZero = dec.match(/^[0]*/)[0].length + 1; if (beforeZero > formatConfig.decimalprecision) { formatConfig.forcedecimals = 1; } formatConfig.decimalprecision = Math.max(beforeZero, formatConfig.decimalprecision); } }; /** * Function to set the axis data from (used for axis drawing) out side. * @param {Object} data Axis data object the values to be changed */ CartesainLabelManager.prototype.setLabelConfig = function setLabelConfig(data) { var axis = this, axisConfig = axis.config, labelConfig = axisConfig.labels, prop; for (prop in data) { if (data.hasOwnProperty(prop)) { labelConfig[prop] = data[prop]; } } }; return CartesainLabelManager; }(_cartesian2['default']); CartesainLabelManager.prototype._parseLabel = _commonApi._parseLabel; CartesainLabelManager.prototype._drawLabel = _commonApi._drawLabel; CartesainLabelManager.prototype.getTrendLineLimits = _commonApi.getTrendLineLimits; CartesainLabelManager.prototype.setAxisPadding = _commonApi.setAxisPadding; CartesainLabelManager.prototype.getLabel = _commonApi.getLabel; exports['default'] = CartesainLabelManager; /***/ }), /* 379 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.minimumEnquiry = exports.getCrispPath = undefined; var _axis = __webpack_require__(380); var _axis2 = _interopRequireDefault(_axis); var _lib = __webpack_require__(125); var _cartesianAxis = __webpack_require__(381); var _cartesianAxis2 = _interopRequireDefault(_cartesianAxis); var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); var _diff = __webpack_require__(383); var _diff2 = _interopRequireDefault(_diff); var _differenceWith = __webpack_require__(384); var _differenceWith2 = _interopRequireDefault(_differenceWith); var _dependencyManager = __webpack_require__(132); var _tools = __webpack_require__(229); var _commonApi = __webpack_require__(386); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var CRISP = 'crisp', BUTT = 'butt', EVENTARGS = 'eventArgs', TREND_ID = '_trend', TICK_ID = '_tick', LABEL_ID = '_label', getCrispPath = function getCrispPath(path, width) { var isCrisped = false, oddWidth = width % 2, value, roundValue; if (path[1] === path[4]) { value = path[1]; roundValue = Math.round(value); path[1] = path[4] = oddWidth ? roundValue > value ? roundValue - 0.5 : roundValue + 0.5 : roundValue; isCrisped = true; } if (path[2] === path[5]) { value = path[2]; roundValue = Math.round(value); path[2] = path[5] = oddWidth ? roundValue > value ? roundValue - 0.5 : roundValue + 0.5 : roundValue; isCrisped = true; } return { path: path, isCrisped: isCrisped }; }, isVisible = function isVisible(visibleRange) { return function (min, max) { return !!(visibleRange.minValue <= min && visibleRange.maxValue >= min || visibleRange.minValue <= max && visibleRange.maxValue >= max); }; }, isInBetween = function isInBetween(visibleRange) { return function (val) { return !!(visibleRange.minValue <= val && visibleRange.maxValue >= val); }; }, queryOptions = { wrtVisible: true }, minimumEnquiry = function minimumEnquiry(category) { var i = 0, len = category.length; for (; i < len; i++) { if (category[i].label || category[i].oriLabel) { return i; } } }; /** * If required, depending on the axis and chart configuration, returns the padding offset that needs * to be applied on the axis name * * @param {Object} axisConfig The configuration of the axis * @param {Object} chartConfig The configuration of the chart * @return {number} The axis padding offset */ function getAxisNamePaddingOffset(axisConfig, chartConfig) { var axisNamePaddingOffset = 0; // Only for candleStick chart as it has two axis whose yaxis name should be in one line. if (axisConfig.relativeAxis && axisConfig.relativeAxis.config && axisConfig.relativeAxis.config.axisNamePadding) { axisNamePaddingOffset = Math.max(axisConfig.relativeAxis.config.axisNamePadding, axisNamePaddingOffset); } if (axisConfig.isOpposit && chartConfig.canvasMarginRight) { axisNamePaddingOffset = Math.max(axisNamePaddingOffset, chartConfig.canvasMarginRight - chartConfig.marginLeft - axisConfig.nameMaxW); } if (!axisConfig.isOpposit && chartConfig.canvasMarginLeft) { axisNamePaddingOffset = Math.max(axisNamePaddingOffset, chartConfig.canvasMarginLeft - chartConfig.marginRight - axisConfig.nameMaxW); } return axisNamePaddingOffset; } (0, _dependencyManager.addDep)({ name: 'cartesianAxisAnimation', type: 'animationRule', extension: _cartesianAxis2['default'] }); var Cartesian = function (_Axis) { _inherits(Cartesian, _Axis); function Cartesian() { _classCallCheck(this, Cartesian); var _this = _possibleConstructorReturn(this, _Axis.call(this)); _this.config.referenceInfo = []; _this.config.prevTicks = []; _this.config.prevIntervalArr = []; _this.config.prevTrendLabels = []; _this.config.prevCategoryIntervalArr = []; return _this; } Cartesian.prototype.configureAttributes = function configureAttributes(rawAttr) { _Axis.prototype.configureAttributes.call(this, rawAttr); }; /** * Function called by the chart when there is requirement to calculate or recalculate the space * management this function must be called every time when chart dimension is changed * @param {number} maxLimit The maximum width/height that is available for space management * @return {Object} Left and right defining how much space is used in left and right */ Cartesian.prototype.placeAxis = function placeAxis(maxLimit) { var axis = this, scale = axis.getScale(), scrollDimensions, chart = axis.getFromEnv('chart'), scrollBar = axis.getChildren('scrollBar') && axis.getChildren('scrollBar')[0], isVertical = axis.config.isVertical, isOpposite = axis.config.isOpposit, isReverse = axis.config.isReverse, chartConfig = chart.config, allocatedSpace = {}; if (scrollBar && !scrollBar.getState('removed')) { scrollDimensions = scrollBar.getLogicalSpace(); if (scrollDimensions) { if (isVertical) { chart.config.shift = scrollDimensions.width + scrollBar.config.conf.padding; allocatedSpace[isOpposite ? 'right' : 'left'] = chart.config.shift; } else { chart.config.shift = scrollDimensions.height + scrollBar.config.conf.padding; allocatedSpace[isOpposite ? 'top' : 'bottom'] = chart.config.shift; } chart._allocateSpace(allocatedSpace); } } if (isVertical) { isReverse ? scale.setRange([chartConfig.canvasBottom, chartConfig.canvasTop]) : scale.setRange([chartConfig.canvasTop, chartConfig.canvasBottom]); return axis._placeVerticalAxis(maxLimit); } else { isReverse ? scale.setRange([chartConfig.canvasRight, chartConfig.canvasLeft]) : scale.setRange([chartConfig.canvasLeft, chartConfig.canvasRight]); return axis._placeHorizontalAxis(maxLimit); } }; /** * Function called by the placeAxis when there is requirement to calculate or recalculate the * space management * @param {number} maxWidth The maximum width that is available for space management * @return {Object} Left and right defining how much space is used in left and right */ Cartesian.prototype._placeVerticalAxis = function _placeVerticalAxis(maxWidth) { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, smartLabel = chart.getFromEnv('smartLabel'), axisRange = axisConfig.axisRange, // Store minLabelWidthPercent from axis.config in a variable minLabelWidthPercent = axisConfig.minLabelWidthPercent, axisNameData = axisConfig.name, isOpposit = axisConfig.isOpposit, numberFormatter = axis.getFromEnv('number-formatter'), canvasHeight = chartConfig.canvasHeight, axisValuePadding = axisConfig.labelPadding = (0, _lib.pluckNumber)(axisConfig.rawAttr.axisValuePadding, 4), axisNamePadding = (0, _lib.pluckNumber)(axisConfig.rawAttr.axisNamePadding, 5), useEllipsesWhenOverflow = axisConfig.useEllipsesWhenOverflow, nameStyle = axisConfig.name.style, trendStyle = axisConfig.trend.trendStyle, axisName = axisConfig.axisName, trendlines = axisConfig.trendLines, drawLabelsOpposit = axisConfig.drawLabelsOpposit, drawAxisNameOpposit = axisConfig.drawAxisNameOpposit, j, jLen, axisLabelWidth = 0, counter = 0, trendLabelConfig, labelWidth = 0, nameWidth = 0, trendLeftWidth = 0, trendRightWidth = 0, retObj = { left: 0, right: 0 }, maxLeftTrendValue = '', maxRightTrendValue = '', reserveNameHeight = 0, numberFormatterFn, axisSmartName, axisSmartTrendValue, trendTextFromValue, i, minLabelWidth = -1, max, min, text, dimention, iLim, trendObj, valueOnRight, axisLineThickness, startTValue, endTValue; // If minLabelWidthPercent is defined then calculate minLabelWidth accordingly. if (minLabelWidthPercent) { minLabelWidth = minLabelWidthPercent / 100 * chartConfig.width; } // If the value padding id negative make it 2 default value axisConfig.oriCanvasHeight = canvasHeight; if (axisValuePadding < 0) { axisConfig.labelPadding = 2; } if (axisConfig.drawTick && axisConfig.tickLength) { axisLineThickness = axisConfig.axisLineThickness + axisConfig.tickLength; } else { axisLineThickness = axisConfig.axisLineThickness; } // if axis line is shown adjust the space accordingly w.r.t width if (axisConfig.showAxisLine) { // recalculate the label padding axisConfig.labelPadding = (0, _lib.pluckNumber)(axisValuePadding, 2) + axisLineThickness; if (axisConfig.labelPadding < 0) { axisConfig.labelPadding = (axisConfig.axisLineThickness < 0 ? 0 : axisLineThickness) + 2; } // adjust the maxWidth accordingly maxWidth -= axisConfig.axisLineThickness; } else { // if the axis line is not shown adjust the label padding and maxWidth accordingly axisConfig.labelPadding = (0, _lib.pluckNumber)(axisValuePadding, 2); if (axisConfig.labelPadding < 0) { axisConfig.labelPadding = 2; } } max = axisRange.max; min = axisRange.min; // store the configuration of the axis axisConfig.name.rotation = 0; axisConfig.labels.step = axisConfig.labelStep; axisConfig.labels.isDraw = 1; // axisConfig.lines.isDraw = 1; // axisConfig.band.isDraw = 1; axisConfig.labels.drawNormalVal = axisConfig.showDivLineValues; axisConfig.labels.drawLimitVal = axisConfig.showLimits; reserveNameHeight = nameStyle.lineHeight; reserveNameHeight = Number(reserveNameHeight.replace(/px/i, '')); if (axisName && reserveNameHeight < maxWidth) { maxWidth -= reserveNameHeight; } // store the configuration if to draw the limit values if (axisConfig.showLimits !== 1 && axisConfig.showDivLineValues !== 1) { axisConfig.labels.isDraw = 0; } // using the smart label to get the max width among all the labels dimention = axisConfig.drawLabels ? axis._getVMaxLabelDimention(maxWidth - axisConfig.labelPadding) : { width: 0, height: 0 }; if (dimention.width + axisConfig.labelPadding > maxWidth && !axisConfig.tickValues || dimention.width === 0) { axisConfig.labels.isDraw = 0; } if (axisConfig.labels.isDraw) { // Set the labelMaxW to max of dimention.width and minLabelWidth axisConfig.labelMaxW = dimention.width > minLabelWidth ? dimention.width : minLabelWidth; axisConfig.labelMaxH = dimention.height; // axisLabelWidth is the total of labelMaxW and labelPadding axisLabelWidth = axisConfig.labelMaxW + axisConfig.labelPadding; labelWidth = axisLabelWidth; } // the width left after label is drawn // space management for trend lines // check if trend line is available and is active axis if (axisConfig.drawTrendLines && axisConfig.drawTrendLabels && trendlines && trendlines.length) { if (axisConfig.isPercent) { numberFormatterFn = numberFormatter.percentValue; } else if (axisConfig.isVertical) { numberFormatterFn = numberFormatter.yAxis; } else { numberFormatterFn = numberFormatter.xAxis; } smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); // for trend line smartLabel.setStyle({ fontSize: trendStyle.fontSize, fontFamily: trendStyle.fontFamily, lineHeight: trendStyle.lineHeight, fontWeight: trendStyle.fontWeight }); // iterate through every trend line to get the trend line max width for both left and right for (j = 0, jLen = trendlines.length; j < jLen; j += 1) { for (i = 0, iLim = trendlines[j].line && trendlines[j].line.length; i < iLim; i += 1) { trendObj = trendlines[j].line[i]; startTValue = numberFormatter.getCleanValue((0, _lib.pluck)(trendObj.startvalue, trendObj.value, 0)); endTValue = (0, _lib.pluckNumber)(trendObj.endvalue, startTValue); if (startTValue <= max && startTValue >= min && endTValue <= max && endTValue >= min) { if (axisConfig.isOpposit) { trendObj.valueonright = 1; } valueOnRight = (0, _lib.pluckNumber)(trendObj.valueonright, 0); trendTextFromValue = valueOnRight === 1 ? trendObj.endvalue || trendObj.startvalue : trendObj.startvalue || trendObj.endvalue; text = (0, _lib.parseUnsafeString)(trendObj.origText || trendObj.displayvalue || trendTextFromValue || ''); if (text === trendTextFromValue) { text = '' + numberFormatterFn.call(numberFormatter, text); } // if the value is displayed on right side if (valueOnRight) { if (text.length > maxRightTrendValue.length) { maxRightTrendValue = text; } } else { // if the value is on left side if (text.length > maxLeftTrendValue.length) { maxLeftTrendValue = text; } } } } } // get the width and store it accordingly dimention = smartLabel.getOriSize(maxRightTrendValue); trendRightWidth = dimention.width + axisConfig.labelPadding; dimention = smartLabel.getOriSize(maxLeftTrendValue); trendLeftWidth = dimention.width + axisConfig.labelPadding; if (isOpposit) { // managing space and truncating label value if required if (trendRightWidth > labelWidth && trendRightWidth > maxWidth) { trendRightWidth = maxWidth; } // update the label width if trend label width is added labelWidth = Math.max(labelWidth, trendRightWidth + axisConfig.labelPadding); if (trendLeftWidth > maxWidth - labelWidth) { trendLeftWidth = Math.min(trendLeftWidth, maxWidth - labelWidth); } } else { // managing space and truncating label value if required if (trendLeftWidth > labelWidth && trendLeftWidth > maxWidth) { trendLeftWidth = maxWidth; } // update the label width if trend label width is added labelWidth = Math.max(labelWidth, trendLeftWidth + axisConfig.labelPadding); if (trendRightWidth > maxWidth - labelWidth) { trendRightWidth = Math.min(trendRightWidth, maxWidth - labelWidth); } } // truncate the trend label if required for (j = 0, jLen = trendlines.length; j < jLen; j += 1) { for (i = 0, iLim = trendlines[j].line && trendlines[j].line.length; i < iLim; i += 1) { trendObj = trendlines[j].line[i]; startTValue = numberFormatter.getCleanValue((0, _lib.pluck)(trendObj.startvalue, trendObj.value, 0)); endTValue = (0, _lib.pluckNumber)(trendObj.endvalue, startTValue); if (Number(trendObj.valueonright) === 1) { text = trendObj.origText || trendObj.displayvalue || '' + endTValue || ''; } else { text = trendObj.origText || trendObj.displayvalue || '' + startTValue || ''; } text = (0, _lib.parseUnsafeString)('' + text); if (text === trendObj.endvalue || text === trendObj.startvalue) { text = '' + numberFormatterFn.call(numberFormatter, text); } trendObj.origText = text; valueOnRight = (0, _lib.pluckNumber)(trendObj.valueonright, 0); // get the smart label value for right side labels if (valueOnRight) { axisSmartTrendValue = smartLabel.getSmartText(text, trendRightWidth, chart.canvasHeight, useEllipsesWhenOverflow); } else { // get the smart label value for the left side label axisSmartTrendValue = smartLabel.getSmartText(text, labelWidth, chart.canvasHeight, useEllipsesWhenOverflow); } // Update the parsed trend label text (which was created in Cartesian#_parseTrendLine) // with the truncated/formatted text. The parsed trend labels will be used to actually // draw the labels in Cartesian#drawTrendLabel. trendLabelConfig = axisConfig.parsedTrendLabels[counter++]; if (trendLabelConfig) { trendLabelConfig.attr.text = trendObj.displayvalue = axisSmartTrendValue.text; // for opposite axis the valueOnRight property is defined internally 1 and the // decision of text-anchor has already been taken based on this property so that // needs to be chaged as well if (axisConfig.isOpposit) { trendLabelConfig.valueOnRight = 1; trendLabelConfig.attr['text-anchor'] = _lib.POSITION_START; } } // if tool text is to be shown or not if (axisSmartTrendValue.tooltext) { trendObj.valueToolText = axisSmartTrendValue.tooltext; trendLabelConfig && (trendLabelConfig.valueToolText = trendObj.valueToolText); } else { delete trendObj.valueToolText; trendLabelConfig && delete trendLabelConfig.valueToolText; } } } } maxWidth += reserveNameHeight; // For axis name // labelWidth include the left trend label width // checking if is possible to draw the axis name if (!axisConfig.drawAxisName || maxWidth - labelWidth - trendRightWidth <= 0 || axisName === '') { axisNameData.isDraw = false; axisNameData.value = ''; } else { // set the smart label style for axis name smartLabel.setStyle({ fontSize: nameStyle.fontSize, fontFamily: nameStyle.fontFamily, lineHeight: nameStyle.lineHeight, fontWeight: nameStyle.fontWeight }); // make isDraw true so that it is drawn axisNameData.isDraw = true; // if rotation is enabled get the axis name width by smart text height if (axisConfig.rotateAxisName) { // set the rotation axisConfig.name.rotation = isOpposit ? 90 : 270; axisSmartName = smartLabel.getSmartText(axisName, canvasHeight, maxWidth - labelWidth - trendRightWidth); axisNameData.value = axisName; // store the max width axisConfig.nameMaxW = Math.min(axisSmartName.height); // get the total name width with padding nameWidth = axisConfig.nameMaxW + axisNamePadding; } else { // if no rotation is there axisSmartName = smartLabel.getSmartText(axisName, maxWidth - labelWidth - trendRightWidth, canvasHeight); axisNameData.value = axisName; axisConfig.nameMaxW = Math.min(axisSmartName.width, maxWidth - labelWidth); axisConfig.nameMaxH = axisSmartName.height; if (axisConfig.axisNameWidth >= 0) { axisConfig.nameMaxW = Math.min(axisConfig.nameMaxW, axisConfig.axisNameWidth); } // get the total name width with padding nameWidth = axisConfig.nameMaxW + axisNamePadding; } } // returning the value of how much space has been taken if (isOpposit) { if (drawLabelsOpposit) { retObj.left += Math.max(axisLabelWidth, trendLeftWidth); retObj.right += trendRightWidth; } else { retObj.left += trendLeftWidth; retObj.right += Math.max(axisLabelWidth, trendRightWidth); } if (drawAxisNameOpposit) { axisConfig.axisNamePadding = retObj.left + axisNamePadding; retObj.left += nameWidth; } else { axisConfig.axisNamePadding = retObj.right + axisNamePadding; retObj.right += nameWidth; } } else { if (drawLabelsOpposit) { retObj.left += trendLeftWidth; retObj.right += Math.max(axisLabelWidth, trendRightWidth); } else { retObj.left += Math.max(axisLabelWidth, trendLeftWidth); retObj.right += trendRightWidth; } if (drawAxisNameOpposit) { axisConfig.axisNamePadding = retObj.right + axisNamePadding; retObj.right += nameWidth; } else { axisConfig.axisNamePadding = retObj.left + axisNamePadding; retObj.left += nameWidth; } } if (axisNameData.isDraw && axisConfig.axisNamePadding + axisConfig.nameMaxW > maxWidth) { axisConfig.axisNamePadding = maxWidth - axisConfig.nameMaxW; nameWidth = axisConfig.nameMaxW + axisConfig.axisNamePadding - labelWidth; } return retObj; }; /** * Function called by the placeAxis when there is requirement to calculate or recalculate * the space management * @param {number} maxHeight The maximum height that is available for space management * @return {Object} Bottom defining how much space is used in bottom */ Cartesian.prototype._placeHorizontalAxis = function _placeHorizontalAxis(maxHeight) { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, smartLabel = chart.getFromEnv('smartLabel'), axisRange = axisConfig.axisRange, axisNameData = axisConfig.name, isOpposit = axisConfig.isOpposit, numberFormatter = chart.getFromEnv('number-formatter'), drawLabelsOpposit = axisConfig.drawLabelsOpposit, drawAxisNameOpposit = axisConfig.drawAxisNameOpposit, axisLabelHeight = 0, canvasWidth = chartConfig.canvasWidth, axisValuePadding = axisConfig.labelPadding = (0, _lib.pluckNumber)(axisConfig.rawAttr.axisValuePadding, 4), axisNamePadding = (0, _lib.pluckNumber)(axisConfig.rawAttr.axisNamePadding, 5), useEllipsesWhenOverflow = axisConfig.useEllipsesWhenOverflow, nameStyle = axisConfig.name.style, trendStyle = axisConfig.trend.trendStyle, axisName = axisConfig.axisName, vtrendlines = axisConfig.vTrendLines, valueOnRight, trendTextFromValue, j, jLen, labelHeight = 0, counter = 0, trendLabelConfig, nameHeight = 0, retObj = { top: 0, bottom: 0 }, trendMaxHeight = 0, reserveNameHeight = 0, axisSmartName, i, max, min, text, iLim, heightLeft, trendObj, axisSmartTrendValue, trendHeight, dimention, numberFormatterFn, axisLineThickness, startTValue, endTValue; // If the value padding id negative make it 2 default value if (axisValuePadding < 0) { axisConfig.labelPadding = 2; } if (axisConfig.drawTick && axisConfig.tickLength) { axisLineThickness = axisConfig.axisLineThickness + axisConfig.tickLength; } else { axisLineThickness = axisConfig.axisLineThickness; } // if axis line is shown adjust the space accordingly w.r.t width if (axisConfig.showAxisLine) { // recalculate the label padding axisConfig.labelPadding = (0, _lib.pluckNumber)(axisValuePadding, 2) + axisLineThickness; if (axisConfig.labelPadding < 0) { axisConfig.labelPadding = (axisConfig.axisLineThickness < 0 ? 0 : axisLineThickness) + 2; } // adjust the maxHeight accordingly maxHeight -= axisConfig.axisLineThickness; } else { // if the axis line is not shown adjust the label padding and maxWidth accordingly axisConfig.labelPadding = (0, _lib.pluckNumber)(axisValuePadding, 2); if (axisConfig.labelPadding < 0) { axisConfig.labelPadding = 2; } } max = axisRange.max; min = axisRange.min; // For axis label // store the configuration of the axis axisConfig.labels.rotation = 0; axisConfig.labels.step = axisConfig.labelStep; axisConfig.labels.isDraw = 1; // axisConfig.lines.isDraw = 1; // axisConfig.band.isDraw = 1; axisConfig.labels.drawNormalVal = axisConfig.showDivLineValues; axisConfig.labels.drawLimitVal = axisConfig.showLimits; reserveNameHeight = nameStyle.lineHeight; reserveNameHeight = Number(reserveNameHeight.replace(/px/i, '')); if (axisName && reserveNameHeight < maxHeight) { maxHeight -= reserveNameHeight; } // checking is rotation is applied for labels by external attribute rotateLabels and // label display is not set to stagger or none then rotate if (axisConfig.rotateLabels && axisConfig.labelDisplay !== 'stagger' && axisConfig.labelDisplay !== 'none') { axisConfig.labelDisplay = 'rotate'; } // store the configuration if to draw the limit values if (axisConfig.showLimits !== 1 && axisConfig.showDivLineValues !== 1) { axisConfig.labels.isDraw = 0; } // using the smart label to get the max width or height among all the labels dimention = axisConfig.drawLabels ? axis._getHMaxLabelDimention(maxHeight - axisConfig.labelPadding) : { width: 0, height: 0 }; if (axisConfig.labels.rotation) { // if rotation is on the smart text width is applicable if (dimention.width + axisConfig.labelPadding > maxHeight && !axisConfig.tickValues) { axisConfig.labels.isDraw = 0; } } else { // the smart text height is applicable if (dimention.height + axisConfig.labelPadding > maxHeight && !axisConfig.tickValues) { axisConfig.labels.isDraw = 0; } } if (axisConfig.labels.isDraw) { // set the max width and height for rotation or non rotation if (axisConfig.labels.rotation) { axisConfig.labelMaxW = dimention.height; axisConfig.labelMaxH = dimention.width; axisLabelHeight = dimention.width + axisConfig.labelPadding; } else { axisConfig.labelMaxW = dimention.width; axisConfig.labelMaxH = dimention.height; axisLabelHeight = dimention.height + axisConfig.labelPadding; } labelHeight = axisLabelHeight; } labelHeight = Math.max(labelHeight, axisConfig.labelPadding); // the height left after label is drawn heightLeft = labelHeight <= maxHeight ? maxHeight - labelHeight : maxHeight; // space management for trend lines // check if vertical trend line is available and is active axis if (axisConfig.drawTrendLines && axisConfig.drawTrendLabels && vtrendlines && axisConfig.isActive) { if (axisConfig.isPercent) { numberFormatterFn = axis.getFromEnv('number-formatter').percentValue; } else if (axisConfig.isVertical) { numberFormatterFn = axis.getFromEnv('number-formatter').yAxis; } else { numberFormatterFn = axis.getFromEnv('number-formatter').xAxis; } smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); // for trend line smartLabel.setStyle({ fontSize: trendStyle.fontSize, fontFamily: trendStyle.fontFamily, lineHeight: trendStyle.lineHeight, fontWeight: trendStyle.fontWeight }); // iterate through every trend line to get the trend line max width for both left and right for (j = 0, jLen = vtrendlines.length; j < jLen; j += 1) { for (i = 0, iLim = vtrendlines[j].line && vtrendlines[j].line.length; i < iLim; i += 1) { trendObj = vtrendlines[j].line[i]; startTValue = numberFormatter.getCleanValue((0, _lib.pluck)(trendObj.startvalue, trendObj.value, 0)); endTValue = (0, _lib.pluckNumber)(trendObj.endvalue, startTValue); if (startTValue <= max && startTValue >= min && endTValue <= max && endTValue >= min) { valueOnRight = (0, _lib.pluckNumber)(trendObj.valueonright, 0); trendTextFromValue = valueOnRight === 1 ? trendObj.endvalue || trendObj.startvalue : trendObj.startvalue || trendObj.endvalue; text = (0, _lib.parseUnsafeString)(trendObj.origText || trendObj.displayvalue || trendTextFromValue || ''); if (text === trendTextFromValue) { text = '' + numberFormatterFn.call(chart.getFromEnv('number-formatter'), text); } trendObj.origText = text; axisSmartTrendValue = smartLabel.getSmartText(text, chart.canvasWidth, trendStyle.lineHeight, useEllipsesWhenOverflow); trendHeight = axisSmartTrendValue.height + 2; // checking if space available for trend label value to be drawn // if not make the display value empty if (heightLeft - trendHeight < 0) { trendObj.displayvalue = ''; } else { // Update the parsed trend label text (which was created in Cartesian#_parseTrendLine) // with the truncated/formatted text. The parsed trend labels will be used to actually // draw the labels in Cartesian#drawTrendLabel. trendLabelConfig = axisConfig.parsedTrendLabels[counter++]; if (trendLabelConfig) { trendLabelConfig.attr.text = trendObj.displayvalue = axisSmartTrendValue.text; } trendMaxHeight = trendMaxHeight < axisSmartTrendValue.height ? axisSmartTrendValue.height : trendMaxHeight; } // check tooltext is available which will help to draw tooltext on hover if (axisSmartTrendValue.tooltext) { trendObj.valueToolText = axisSmartTrendValue.tooltext; trendLabelConfig && (trendLabelConfig.valueToolText = trendObj.valueToolText); } else { delete trendObj.valueToolText; trendLabelConfig && delete trendLabelConfig.valueToolText; } } } } } // adjust the height left heightLeft -= trendMaxHeight; // recalculate the label height labelHeight += trendMaxHeight; heightLeft += reserveNameHeight; maxHeight += reserveNameHeight; // For axis name // checking if is possible to draw the axis name if (!axisConfig.drawAxisName || heightLeft <= 0 || axisName === '') { axisNameData.isDraw = false; axisNameData.value = ''; } else { // set the smart label style for axis name smartLabel.setStyle({ fontSize: nameStyle.fontSize, fontFamily: nameStyle.fontFamily, lineHeight: nameStyle.lineHeight, fontWeight: nameStyle.fontWeight }); // make isDraw true so that it is drawn axisNameData.isDraw = true; axisSmartName = smartLabel.getSmartText(axisName, canvasWidth, heightLeft); axisNameData.value = axisName; // store the max width axisConfig.nameMaxW = canvasWidth; // store the max height axisConfig.nameMaxH = axisSmartName.height; // get the total name height with padding nameHeight = axisSmartName.height + axisNamePadding; // total padding from after which the drawing of axis can be start so that this point of drawing // axis name need not to recalculate axisConfig.axisNamePadding = axisNamePadding + labelHeight; if (axisConfig.axisNamePadding + axisSmartName.height > maxHeight) { axisConfig.axisNamePadding = maxHeight - axisSmartName.height; nameHeight = axisSmartName.height + axisConfig.axisNamePadding - labelHeight; } } if (isOpposit) { if (drawLabelsOpposit) { retObj.bottom += axisLabelHeight + trendMaxHeight; } else { retObj.top += axisLabelHeight; retObj.bottom += trendMaxHeight; } axisConfig.trendBottomPadding = retObj.bottom - trendMaxHeight + 2; if (drawAxisNameOpposit) { // axisConfig.axisNamePadding = retObj.bottom + axisNamePadding; retObj.bottom += nameHeight; } else { // axisConfig.axisNamePadding = retObj.top + axisNamePadding; retObj.top += nameHeight; } } else { if (drawLabelsOpposit) { retObj.top += axisLabelHeight; retObj.bottom += trendMaxHeight; } else { retObj.bottom += axisLabelHeight + trendMaxHeight; } axisConfig.trendBottomPadding = retObj.bottom - trendMaxHeight + 2; if (drawAxisNameOpposit) { // axisConfig.axisNamePadding = retObj.top + axisNamePadding; retObj.top += nameHeight; } else { // axisConfig.axisNamePadding = retObj.bottom + axisNamePadding; retObj.bottom += nameHeight; } } // returning the value of how much space has been taken // if (isOpposit) { // retObj.top = labelHeight + nameHeight; // } else { // retObj.bottom = labelHeight + nameHeight; // } return retObj; }; /* * function is called internally by the axis class draw function to draw the category axis plot lines */ Cartesian.prototype._parseCategoryPlotLine = function _parseCategoryPlotLine() { var axis = this, axisConfig = axis.config, axisRange = axisConfig.axisRange, tickValue = axisConfig.tickValues.tickValue, plotLineColor = (0, _lib.convertColor)(axisConfig.divLineColor, axisConfig.divLineAlpha), plotLineWidth = axisConfig.divLineThickness, plotLineDashStyle = axisConfig.divLineIsDashed ? (0, _lib.getDashStyle)(axisConfig.divLineDashLen, axisConfig.divLineDashGap, plotLineWidth) : _lib.DASH_DEF, axisAttrObj, i, willDraw = isInBetween(axis.getVisibleConfig()), value, ticks = axisConfig._allTicks, len = ticks.length; axisAttrObj = { stroke: plotLineColor, 'stroke-width': plotLineWidth, 'stroke-dasharray': plotLineDashStyle }; // checking for pure tickValue axis exclude bubble scatter if (tickValue[0] && (tickValue[0].x !== _lib.UNDEF || tickValue[0].y !== _lib.UNDEF)) { return; } // checking if lines are to be drawn user can decide if (axisConfig.lines.isDraw && axisConfig.categoryNumDivLines) { for (i = 0; i < len; ++i) { value = ticks[i]; if (!willDraw(value)) { continue; } // category plot lines that is drawn at axis min or max will skipped if (value === axisRange.min || value === axisRange.max) { continue; } axis.setReferenceInfo({ from: value, type: 'line', layer: 1, attr: axisAttrObj }); } } }; /** * Calculates the parameters necessary to draw the components of the chart. * In addition, it also calculates and draws the axis labels and ticks */ Cartesian.prototype._drawComponents = function _drawComponents() { var axis = this, axisConfig = axis.config; axisConfig.drawAxisName && axis._drawAxisName(); axisConfig.drawAxisLine && axis._drawAxisLine(); if (!axisConfig.tickValues) { axisConfig.drawLabels && axis._drawLabel(); } else { axisConfig.drawLabels && axis._drawCategory(); } axisConfig.drawTrendLines && axis.drawTrendLabel(); }; Cartesian.prototype.drawTrendLabel = function drawTrendLabel() { var axis = this, axisConfig = axis.config, trendLabelConfigs = axisConfig.parsedTrendLabels, animationManager = axis.getFromEnv('animationManager'), toolTipController = this.getFromEnv('toolTipController'), container = axisConfig.axisTrendLabelContainer, isOpposite = axisConfig.isOpposit, axisPadding = axisConfig.labelPadding, vtrendlines = axisConfig.vTrendLines, trendlines = axisConfig.trendLines, axisDimension = axisConfig.axisDimention, visibleDomain = axis.getVisibleConfig(), visibleMin = visibleDomain.minValue, visibleMax = visibleDomain.maxValue, valueOnRight = void 0, trendLabelConfig = void 0, trendLabelElement = void 0, fixedTrendLabelPos = void 0, fixedTrendLabelPosRight = void 0, isTrendZone = void 0, startValue = void 0, midValue = void 0, endValue = void 0, isVisible = true, startValuePixel = void 0, endValuePixel = void 0, removingElement = void 0, diff = void 0, isEndValDefined = void 0, i = void 0, ii = void 0; for (i = 0, ii = trendLabelConfigs.length; i < ii; i++) { trendLabelConfigs[i].id = i + TREND_ID; } if (vtrendlines) { fixedTrendLabelPos = isOpposite ? axisDimension.opposite - (axisConfig.trendBottomPadding || 0) : axisDimension.y + (axisConfig.trendBottomPadding || 0); } else { fixedTrendLabelPos = isOpposite ? axisDimension.opposite + (axisPadding || 0) : axisDimension.x - (axisPadding || 0); fixedTrendLabelPosRight = isOpposite ? axisDimension.x + (axisPadding || 0) : axisDimension.opposite + (axisPadding || 0); } diff = (0, _differenceWith2['default'])(function (prev, now) { return prev.attr.text === now.attr.text; }, axisConfig.prevTrendLabels, trendLabelConfigs); for (i = 0, ii = diff.length; i < ii; i++) { removingElement = axis.getGraphicalElement(diff[i].id); if (removingElement) { axis.removeGraphicalElement(removingElement); } } axisConfig.prevTrendLabels = (0, _lib.extend2)([], trendLabelConfigs); if (!axisConfig.drawTrendLabels) { for (i = 0, ii = trendLabelConfigs.length; i < ii; i++) { removingElement = axis.getGraphicalElement(trendLabelConfigs[i].id); if (removingElement) { axis.removeGraphicalElement(removingElement); } } return; } for (i = 0, ii = trendLabelConfigs.length; i < ii; i++) { trendLabelConfig = trendLabelConfigs[i]; trendLabelElement = axis.getGraphicalElement(i + TREND_ID); startValue = +trendLabelConfig.from; endValue = +trendLabelConfig.to; isVisible = true; isEndValDefined = !isNaN(endValue); if (isEndValDefined) { midValue = startValue + (endValue - startValue) / 2; if (visibleMin > midValue || visibleMax < midValue) isVisible = false; } else { if (visibleMin > startValue || visibleMax < startValue) isVisible = false; } if (!isVisible) { trendLabelElement && axis.removeGraphicalElement(trendLabelElement); } else { if (vtrendlines) { startValuePixel = axis.getPixel(startValue, queryOptions); endValuePixel = endValue ? axis.getPixel(endValue, queryOptions) : 0; isTrendZone = (0, _lib.pluckNumber)(trendLabelConfig.isTrendZone, axisConfig.isTrendZone, 1); if (isEndValDefined && endValue !== startValue && isTrendZone) { trendLabelConfig.attr.x = startValuePixel + (endValuePixel - startValuePixel) / 2; trendLabelConfig.attr.y = fixedTrendLabelPos; } else { trendLabelConfig.attr.x = endValue ? endValuePixel : startValuePixel; trendLabelConfig.attr.y = fixedTrendLabelPos; } } else if (trendlines) { startValuePixel = axis.getPixel(startValue, queryOptions); endValuePixel = endValue ? axis.getPixel(endValue, queryOptions) : 0; valueOnRight = (0, _lib.pluckNumber)(trendLabelConfig.valueOnRight, 0); isTrendZone = (0, _lib.pluckNumber)(trendLabelConfig.isTrendZone, axisConfig.isTrendZone, 0); if (isEndValDefined && endValue !== startValue && isTrendZone) { trendLabelConfig.attr.x = valueOnRight ? fixedTrendLabelPosRight : fixedTrendLabelPos; trendLabelConfig.attr.y = startValuePixel + (endValuePixel - startValuePixel) / 2; } else { trendLabelConfig.attr.x = valueOnRight ? fixedTrendLabelPosRight : fixedTrendLabelPos; trendLabelConfig.attr.y = endValue ? valueOnRight ? endValuePixel : startValuePixel : startValuePixel; } } trendLabelElement = axis.addGraphicalElement(i + TREND_ID, animationManager.setAnimation({ container: container, el: trendLabelElement || 'text', attr: trendLabelConfig.attr, css: trendLabelConfig.css, data: { value: midValue || startValue }, component: axis, label: 'text' })); if (axisConfig.showTooltip && trendLabelConfig.valueToolText) { toolTipController.enableToolTip(trendLabelElement, trendLabelConfig.valueToolText); } else { toolTipController.disableToolTip(trendLabelElement); } } } }; /** * Function is called internally by the axis class draw function to draw the axis name */ Cartesian.prototype._drawAxisName = function _drawAxisName() { var axis = this, axisConfig = axis.config, toolTipController = this.getFromEnv('toolTipController'), canvasDimensions = axis.getLinkedItem('canvas').getEffectiveDimensions(), animationManager = axis.getFromEnv('animationManager'), canvasLeft = canvasDimensions.left, canvasTop = canvasDimensions.top, canvasWidth = canvasDimensions.width, canvasHeight = canvasDimensions.height, canvasBottom = canvasTop + canvasHeight, canvasRight = canvasLeft + canvasWidth, chartConfig = axis.getFromEnv('chart').config, style = axisConfig.name.style, axisName = axisConfig.name.value, isOpposite = axisConfig.isOpposit, isVertical = axisConfig.isVertical, smartLabel = axis.getFromEnv('smartLabel'), axisNameContainer = axisConfig.axisNameContainer, axisNamePadding = axisConfig.axisNamePadding, axisNameMaxH = axisConfig.nameMaxH, axisNameMaxW = axisConfig.nameMaxW, axisDimension = axisConfig.axisDimention, axisStart = isVertical ? axisDimension.x : axisDimension.y, axisOpposite = axisDimension.opposite, axisNameElement = axis.getGraphicalElement('axisName'), rotation = (0, _lib.pluckNumber)(axisConfig.name.rotation, isVertical ? 90 : 270), paper = axis.getFromEnv('paper'), css = { fontFamily: style.fontFamily, fontSize: style.fontSize, lineHeight: style.lineHeight, fontWeight: style.fontWeight, fontStyle: style.fontStyle }, axisAttrObj, axisSmartName, tooltext, nameHeightAvail, nameHeight, yPos; // checking if name is to be drawn user can decide or can be decided by axis placeAxis function // for radar chart axis name will not be drawn if (axisConfig.name.isDraw) { // common attribute style axisAttrObj = { fontFamily: style.fontFamily, fill: style.color, 'vertical-align': 'middle', 'font-size': style.fontSize, 'line-height': style.lineHeight }; // make the smart label ready to use for use of drawing the name smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle({ fontSize: style.fontSize, fontFamily: style.fontFamily, lineHeight: style.lineHeight, fontWeight: style.fontWeight }); // check with the drawAxisNameOpposit to finally decide the name should be draw on which side if (axisConfig.drawAxisNameOpposit) { isOpposite = !isOpposite; axisStart = axisOpposite; } // preparing the attributes if (isVertical) { axisNamePadding = Math.max(axisNamePadding, getAxisNamePaddingOffset(axisConfig, chartConfig)); // Set the available height based on caption and canvas alignment if (axisConfig.axisNameAlignCanvas || chartConfig.captionalignment && chartConfig.captionalignment === 'left') { nameHeightAvail = canvasHeight; } else { nameHeightAvail = Math.max(canvasHeight, axisConfig.oriCanvasHeight || 0); } // If rotation is there get the axis name from the smartText accordingly if (rotation) { axisSmartName = smartLabel.getSmartText(axisName, nameHeightAvail, axisNameMaxW); tooltext = axisSmartName.tooltext; nameHeight = axisSmartName.width; } else { axisSmartName = smartLabel.getSmartText(axisName, axisNameMaxW, nameHeightAvail); tooltext = axisSmartName.tooltext; nameHeight = axisSmartName.height; } if (axisConfig.drawAxisNameFromBottom) { yPos = canvasBottom - nameHeight / 2; } else { yPos = nameHeight > canvasHeight ? chartConfig.height / 2 : canvasTop + canvasHeight / 2; } axisAttrObj.text = axisSmartName.text; axisAttrObj.x = isOpposite ? (axisStart || canvasRight) + axisNamePadding + axisNameMaxW / 2 : (axisStart || canvasLeft) - axisNamePadding - axisNameMaxW / 2; axisAttrObj.y = yPos; } else { axisSmartName = smartLabel.getSmartText(axisName, canvasWidth, axisNameMaxH); tooltext = axisSmartName.tooltext; if (isOpposite && chartConfig.canvasMarginTop) { axisNamePadding = Math.max(axisNamePadding, chartConfig.canvasMarginTop - chartConfig.marginTop - axisNameMaxH); } if (!isOpposite && chartConfig.canvasMarginBottom) { axisNamePadding = Math.max(axisNamePadding, chartConfig.canvasMarginBottom - chartConfig.marginBottom - axisNameMaxH); } axisAttrObj.text = axisSmartName.text; axisAttrObj.x = canvasLeft + canvasWidth / 2; axisAttrObj.y = isOpposite ? (axisStart || canvasTop) - axisNamePadding - axisNameMaxH / 2 : (axisStart || canvasBottom) + axisNamePadding + axisNameMaxH / 2; } axisAttrObj['text-bound'] = axisSmartName.text === '' ? [] : [style.backgroundColor, style.borderColor, style.borderColor ? style.borderThickness : 0, style.borderPadding, style.borderRadius, style.borderDash]; axisAttrObj.transform = paper.getSuggestiveRotation(isVertical ? rotation : 0, axisAttrObj.x, axisAttrObj.y); axisNameElement = axis.addGraphicalElement('axisName', animationManager.setAnimation({ css: css, el: axisNameElement || 'text', attr: axisAttrObj, container: axisNameContainer, component: axis, label: 'text' })); if (axisConfig.showTooltip) { toolTipController.enableToolTip(axisNameElement, tooltext); } else { toolTipController.disableToolTip(axisNameElement); } } else { axisNameElement && axis.removeGraphicalElement(axisNameElement); } }; /** * Function is called internally by the axis class draw function to draw the axis line */ Cartesian.prototype._drawAxisLine = function _drawAxisLine() { var AXIS_LINE = 'axisLine'; var axis = this, axisConfig = axis.config, isVertical = axisConfig.isVertical, isOpposite = axisConfig.isOpposit, chart = axis.getFromEnv('chart'), canvasDimensions = axis.getLinkedItem('canvas').getEffectiveDimensions(), animationManager = axis.getFromEnv('animationManager'), canvasTop = canvasDimensions.top, canvasLeft = canvasDimensions.left, canvasBottom = canvasTop + canvasDimensions.height, canvasRight = canvasLeft + canvasDimensions.width, axisDimension = axisConfig.axisDimention, axisStartPosition = isVertical ? axisDimension.x : axisDimension.y, drawAxisLineWRTCanvas = axisConfig.drawAxisLineWRTCanvas, chartJSON = chart.getFromEnv('dataSource').chart, axisLineGroup = axisConfig.axisAxisLineContainerBottom, tickAttrObj, axisLineElementCheck = axis.getGraphicalElement(AXIS_LINE), axisLineElement, linePath, xAxisLineLeftExten, fixPoint, tickEndPoint, pixelValue, axisLineAttrObj, tickElement, tickElementCheck, removingElement, tick, tickId, drawElemIds = [], diff, i, crispPath, ticks, ln; xAxisLineLeftExten = (0, _lib.pluckNumber)(chartJSON.showyaxisline, chartJSON.showyaxisline) === 1 ? (0, _lib.pluckNumber)(chartJSON.yaxislinethickness, chartJSON.pyaxislinethickness, 1) : 0; // checking if axis lines are to be drawn user can decide or can be decided by axis placeAxis // function if (axisConfig.showAxisLine) { // initiate the line path element if (isVertical) { if (isOpposite) { axisStartPosition = drawAxisLineWRTCanvas ? canvasRight : axisStartPosition; fixPoint = axisStartPosition + axisConfig.axisLineThickness / 2; } else { axisStartPosition = drawAxisLineWRTCanvas ? canvasLeft : axisStartPosition; fixPoint = axisStartPosition - axisConfig.axisLineThickness / 2; } crispPath = getCrispPath(['M', fixPoint, canvasBottom, 'L', fixPoint, canvasTop], axisConfig.axisLineThickness); linePath = crispPath.path; } else { if (isOpposite) { axisStartPosition = drawAxisLineWRTCanvas ? canvasTop : axisStartPosition; fixPoint = axisStartPosition - axisConfig.axisLineThickness / 2; } else { axisStartPosition = drawAxisLineWRTCanvas ? canvasBottom : axisStartPosition; fixPoint = axisStartPosition + axisConfig.axisLineThickness / 2; } crispPath = getCrispPath(['M', canvasLeft - xAxisLineLeftExten, fixPoint, 'L', canvasRight, fixPoint], axisConfig.axisLineThickness); linePath = crispPath.path; } axisLineAttrObj = { path: linePath, stroke: axisConfig.axisLineColor, 'stroke-linecap': BUTT, 'stroke-width': axisConfig.axisLineThickness, 'shape-rendering': crispPath.isCrisped ? CRISP : _lib.UNDEF }; if (axisConfig.drawTick && axisConfig.tickLength) { tickAttrObj = { stroke: axisConfig.tickColor, 'stroke-width': axisConfig.tickWidth }; if (isVertical) { if (isOpposite) { tickEndPoint = fixPoint + axisConfig.tickLength; } else { tickEndPoint = fixPoint - axisConfig.tickLength; } } else { if (isOpposite) { tickEndPoint = fixPoint - axisConfig.tickLength; } else { tickEndPoint = fixPoint + axisConfig.tickLength; } } ticks = axisConfig.tickValues ? axisConfig.tickValues.tickValue.map(function (tickObj) { return isVertical ? tickObj.y : tickObj.x; }) : axisConfig.ticks; for (i = 0, ln = ticks.length; i < ln; i += 1) { tick = ticks[i]; tickId = '' + tick + TICK_ID; tickElementCheck = axis.getGraphicalElement(tickId); pixelValue = axis.getPixel(tick, queryOptions); tickAttrObj.path = getCrispPath(isVertical ? ['M', fixPoint, pixelValue, 'L', tickEndPoint, pixelValue] : ['M', pixelValue, fixPoint, 'L', pixelValue, tickEndPoint], axisConfig.tickWidth).path; tickElement = animationManager.setAnimation({ el: tickElementCheck || 'path', attr: tickAttrObj, data: { value: tick, path: tickAttrObj.path }, container: axisLineGroup, component: axis, label: 'path' }); if (!tickElementCheck) { axis.addGraphicalElement(tickId, tickElement); } drawElemIds.push(tickId); } } axisLineElement = animationManager.setAnimation({ el: axisLineElementCheck || 'path', attr: axisLineAttrObj, container: axisLineGroup, component: axis, label: 'path' }); if (!axisLineElementCheck) { axis.addGraphicalElement(AXIS_LINE, axisLineElement); } drawElemIds.push(AXIS_LINE); } diff = (0, _diff2['default'])(axisConfig.prevTicks, drawElemIds); for (i = 0, ln = diff.length; i < ln; i++) { removingElement = axis.getGraphicalElement(diff[i]); removingElement && axis.removeGraphicalElement(removingElement); } axisConfig.prevTicks = drawElemIds; }; /** * Parses category * * @memberof NumericAxis */ Cartesian.prototype._parseCategory = function _parseCategory() { var axis = this, axisConfig = axis.config, axisDimention = axisConfig.axisDimention || {}, chart = axis.getFromEnv('chart'), smartLabel = chart.getFromEnv('smartLabel'), axisComponents = axis.components, labelStore = axisComponents.labels, canvasDimensions = axis.getLinkedItem('canvas').getEffectiveDimensions(), chartConfig = chart.config, isOpposit = axisConfig.isOpposit, labels = axisConfig.labels, style = labels.style, isVertical = axisConfig.isVertical, canvasTop = canvasDimensions.top, canvasLeft = canvasDimensions.left, canvasBottom = canvasTop + canvasDimensions.height, canvasRight = canvasLeft + canvasDimensions.width, axisPadding = axisConfig.labelPadding, axisStartPosition = isVertical ? axisDimention.x : axisDimention.y, axisEndPosition = axisDimention.opposite, categories = chart.getFromEnv('dataSource').categories, categoriesStyle = {}, tickArr = axisConfig.tickValues.tickValue, i, curCategory, text, labelRotation, labelLineHeight, labelLineHeightpx, addCategoryPadding, css, categoryStyleFontFamily, categoryStyleFontSize, categoryStyleFontWeight, categoryStyleFontStyle, ParentCss, axisAttrObj, fontColor, pos, min = axisConfig.axisRange.min, curCategoryValue, labelBox, categoryArr, ln, tempStep, staggerLineAvailed, staggerLines = axisConfig.drawnStaggerLines, isUnevenLabels = (axisConfig.labelStep !== axisConfig.labels.step || axis.getZoom() !== 1) && axisConfig.labelDisplay === 'stagger', categoryPadding, staggerLabelWidth, intervalWidth, smartLabelText, labelMaxW, labelMaxH, axisXPadding = 1, curCategoryIndex; // checking if labels are to be drawn user can decide or can be decided by axis placeAxis function if (axisConfig.labels.isDraw) { if (isVertical) { intervalWidth = Math.abs(axis.getPixel(0, queryOptions) - axis.getPixel(0 + axisConfig.axisRange.tickInterval, queryOptions)); // check for overlap if there is any make the step such that no overlap happens if (axisConfig.labelMaxH > intervalWidth) { tempStep = Math.ceil(axisConfig.labelMaxH / intervalWidth); } if (tempStep > axisConfig.labels.step) { axisConfig.labels.step = tempStep; } } if (isUnevenLabels) { staggerLabelWidth = 2 * Math.abs(axis.getPixel(min, queryOptions) - axis.getPixel(min + axisConfig.labels.step, queryOptions)) * axisConfig.sWidthAdjstFactor - axisXPadding; } labelRotation = axisConfig.labels.rotation; labelMaxW = labelRotation ? axisConfig.labelMaxH : axisConfig.labelMaxW; labelMaxH = labelRotation ? axisConfig.labelMaxW : axisConfig.labelMaxH; // check with the drawAxisNameOpposit to finally decide the name should be draw on which // side if (axisConfig.drawLabelsOpposit) { isOpposit = !isOpposit; axisStartPosition = axisEndPosition; } if (categories && categories[0] && axisConfig.xAxisLabelMode !== 'auto') { categoriesStyle.fontFamily = categories[0].font; categoriesStyle.fontSize = categories[0].fontsize; categoriesStyle.color = categories[0].fontcolor; } axisConfig.ParentCss = ParentCss = { fontFamily: (0, _lib.pluck)(categoriesStyle.fontFamily, style.fontFamily), fontSize: (0, _lib.pluck)(categoriesStyle.fontSize, style.fontSize), fontWeight: (0, _lib.pluck)(style.fontWeight), fontStyle: (0, _lib.pluck)(style.fontStyle) }; ParentCss.lineHeight = (0, _lib.setLineHeight)(ParentCss); categoryArr = axis._getCategoryArr(); // for every parsing a new index array will be created axisComponents.labelIndexArr = []; // main loop where the drawing starts for (i = 0, ln = categoryArr.length; i < ln; i += 1) { curCategoryIndex = categoryArr[i].index; curCategory = tickArr[curCategoryIndex]; // TODO : need to curCategoryValue = categoryArr[i].value; axisComponents.labelIndexArr.push(curCategoryIndex); categoryStyleFontFamily = (0, _lib.pluck)(curCategory.font, curCategory.labelfont); categoryStyleFontSize = (0, _lib.pluck)(curCategory.fontsize, curCategory.labelfontsize); categoryStyleFontWeight = (0, _lib.pluck)(curCategory.fontbold, curCategory.labelfontbold) ? (0, _lib.pluckNumber)(curCategory.fontbold, curCategory.labelfontbold, 0) ? 'bold' : _lib.NORMAL : _lib.UNDEF; categoryStyleFontStyle = (0, _lib.pluck)(curCategory.fontitalic, curCategory.labelfontitalic) ? (0, _lib.pluckNumber)(curCategory.fontitalic, curCategory.labelfontitalic, 0) ? 'italic' : _lib.NORMAL : _lib.UNDEF; fontColor = (0, _lib.convertColor)((0, _lib.pluck)(curCategory.fontcolor, curCategory.labelfontcolor, categoriesStyle.color, style.color), (0, _lib.pluckNumber)(curCategory.labelalpha, axisConfig.rawAttr.labelFontAlpha, chart.config.singleseries ? _lib.UNDEF : curCategory.alpha, 100)); if (categoryStyleFontFamily || categoryStyleFontSize || categoryStyleFontWeight || categoryStyleFontStyle) { css = {}; categoryStyleFontFamily && (css.fontFamily = categoryStyleFontFamily); categoryStyleFontSize && (css.fontSize = categoryStyleFontSize); categoryStyleFontWeight && (css.fontWeight = categoryStyleFontWeight); categoryStyleFontStyle && (css.fontStyle = categoryStyleFontStyle); css.lineHeight = categoryStyleFontSize ? (0, _lib.setLineHeight)(css) : ParentCss.lineHeight; } else { css = _lib.UNDEF; } if (css || ParentCss) { labelLineHeightpx = (css || ParentCss).lineHeight; if (labelLineHeightpx.indexOf('px') !== -1) { labelLineHeight = labelLineHeightpx.replace(/px/i, ''); labelLineHeight = parseFloat(labelLineHeight); } } if (curCategory.appliedSmartLabel === false) { smartLabel.setStyle(curCategory._ovrStyle || ParentCss); smartLabelText = smartLabel.getSmartText(curCategory.oriLabel || curCategory.label, labelMaxW, labelMaxH); curCategory.oriLabel = curCategory.oriLabel || curCategory.label; curCategory.label = smartLabelText.text; curCategory.labelTooltext = smartLabelText.labelTooltext; curCategory.appliedSmartLabel = true; } // make the attribute ready to use pos = axis.getPixel(curCategoryValue, queryOptions); if (isVertical) { // y-axis text = curCategory.label || ''; // @temp addCategoryPadding = Number(curCategory.labelPadding) || 0; axisAttrObj = { fill: fontColor, 'line-height': labelLineHeight, opacity: 1, 'text-anchor': isOpposit ? _lib.POSITION_START : _lib.POSITION_END, 'text': text, cursor: !chartConfig.singleseries && curCategory.link || curCategory.labellink || style.labelLink ? _lib.POINTER : '', 'x': isOpposit ? (axisStartPosition || canvasRight) + axisPadding : (axisStartPosition || canvasLeft) - axisPadding, 'y': addCategoryPadding ? pos + addCategoryPadding : pos }; } else { // x-axis text = curCategory.label || ''; addCategoryPadding = Number(curCategory.labelPadding) || 0; axisAttrObj = { fill: fontColor, 'line-height': labelLineHeight, opacity: 1, 'text': text, cursor: !chartConfig.singleseries && curCategory.link || curCategory.labellink || style.labelLink ? _lib.POINTER : '', 'x': pos, 'y': isOpposit ? (canvasTop || axisStartPosition) - axisPadding : (axisStartPosition || canvasBottom) + axisPadding }; if (labelRotation) { axisAttrObj['text-anchor'] = isOpposit ? _lib.POSITION_START : _lib.POSITION_END; axisAttrObj['vertical-align'] = 'middle'; } else { axisAttrObj['text-anchor'] = _lib.POSITION_MIDDLE; axisAttrObj['vertical-align'] = isOpposit ? _lib.POSITION_BOTTOM : _lib.POSITION_TOP; } // this chnage is only for zoom charts in stagger mode if (isUnevenLabels) { staggerLineAvailed = curCategory.labelCount % staggerLines; if (staggerLineAvailed) { if (!(labelLineHeight = curCategory.style.lineHeight)) labelLineHeight = axisConfig.labels.style.lineHeight; categoryPadding = labelLineHeight.replace(/px/i, '') * staggerLineAvailed; axisAttrObj.y = isOpposit ? axisAttrObj.y - categoryPadding : axisAttrObj.y + categoryPadding; } smartLabel.setStyle(curCategory._ovrStyle || ParentCss); smartLabelText = smartLabel.getSmartText(curCategory.oriLabel || curCategory.label, staggerLabelWidth, labelMaxH); curCategory.oriLabel = curCategory.oriLabel || curCategory.label; axisAttrObj.text = curCategory.label = smartLabelText.text; curCategory.labelTooltext = smartLabelText.labelTooltext; curCategory.appliedSmartLabel = true; } else if (addCategoryPadding) { if (isOpposit) { axisAttrObj.y -= addCategoryPadding; } else { axisAttrObj.y += addCategoryPadding; } } } labelBox = { label: curCategory.label, lineHeight: labelLineHeightpx, border: (0, _lib.pluckNumber)(curCategory.borderthickness, curCategory.labelborderthickness) ? (0, _lib.pluckNumber)(curCategory.borderthickness, curCategory.labelborderthickness, 1) + 'px solid' : '', borderColor: curCategory.bordercolor || curCategory.labelbordercolor ? (0, _lib.convertColor)(curCategory.bordercolor || curCategory.labelbordercolor, (0, _lib.pluckNumber)(curCategory.borderalpha, curCategory.labelborderalpha, curCategory.alpha, curCategory.labelalpha, 100)) : _lib.BLANKSTRING, borderThickness: (0, _lib.pluckNumber)(curCategory.borderthickness, curCategory.labelborderthickness), borderPadding: (0, _lib.pluckNumber)(curCategory.borderpadding, curCategory.labelborderpadding), borderRadius: (0, _lib.pluckNumber)(curCategory.borderradius, curCategory.labelborderradius), backgroundColor: curCategory.bgcolor || curCategory.labelbgcolor ? (0, _lib.convertColor)(curCategory.bgcolor || curCategory.labelbgcolor, (0, _lib.pluckNumber)(curCategory.bgalpha, curCategory.labelbgalpha, curCategory.alpha, curCategory.labelalpha, axisConfig.rawAttr.labelFontAlpha, 100)) : _lib.BLANKSTRING, borderDash: (0, _lib.pluckNumber)(curCategory.borderdashed, curCategory.labelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(curCategory.borderdashlen, curCategory.labelborderdashlen, 4), (0, _lib.pluckNumber)(curCategory.borderdashgap, curCategory.labelborderdashgap, 2)) : (0, _lib.pluckNumber)(curCategory.borderdashed, curCategory.labelborderdashed) === 0 ? _lib.DASH_DEF : style.borderDash }; if (!curCategory.label) { axisAttrObj['text-bound'] = []; } else { axisAttrObj['text-bound'] = [(0, _lib.pluck)(labelBox.backgroundColor, style.backgroundColor), (0, _lib.pluck)(labelBox.borderColor, style.borderColor), (0, _lib.pluck)(labelBox.borderThickness, style.borderThickness), (0, _lib.pluck)(labelBox.borderPadding, style.borderPadding), (0, _lib.pluck)(labelBox.borderRadius, style.borderRadius), (0, _lib.pluck)(labelBox.borderDash, style.borderDash)]; } // If labels shift is applicable (Specially for 3D) then apply the changes if (labels.shiftX) { axisAttrObj.x += labels.shiftX; } if (labels.shiftY) { axisAttrObj.y += labels.shiftY; } axisAttrObj.transform = (0, _lib.getSuggestiveRotation)(labelRotation, axisAttrObj.x, axisAttrObj.y); labelStore[curCategoryIndex] = labelStore[curCategoryIndex] || { config: { props: { label: {} } } }; labelStore[curCategoryIndex].config.props.label.attr = axisAttrObj; labelStore[curCategoryIndex].config.props.label.css = css; } } }; /** * Parsing of position and attributes during post space management * * @memberof NumericAxis */ Cartesian.prototype.allocatePosition = function allocatePosition() { var axis = this, axisConfig = axis.config; if (!axisConfig.tickValues) { axisConfig.drawLabels && axis._parseLabel(); } else { axisConfig.drawLabels && axis._parseCategory(); } if (axis.getChildren('scrollBar') && axis.getChildren('scrollBar')[0]) { axis.getChildren('scrollBar')[0].setDimension(axis.getScrollerDimension()); } }; /** * Draws the category labels of the axis */ Cartesian.prototype._drawCategory = function _drawCategory() { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, labels = axisConfig.labels, animationManager = axis.getFromEnv('animationManager'), style = labels.style, toolTipController = this.getFromEnv('toolTipController'), axisContainer = axisConfig.axisContainer, categoryLabel = axis.config.categoryLabel || (axis.config.categoryLabel = []), raiseEvent = function raiseEvent(event) { return function (data) { var ele = this; chart.plotEventHandler(ele, data, event); }; }, tickArr = axisConfig.tickValues.tickValue, i, curCategory, textElement, axisAttrObj, diff, curCategoryValue, categoryArr, categoryArrStr = [], tempEle, ln, config, removingElement, curCategoryIndex; // checking if labels are to be drawn user can decide or can be decided by axis placeAxis function if (axisConfig.labels.isDraw) { axisContainer.css(axisConfig.ParentCss); categoryArr = axis._getCategoryArr(); diff = (0, _differenceWith2['default'])(function (prev, now) { return prev.value === now.value; }, axisConfig.prevCategoryIntervalArr, categoryArr); for (i = 0, ln = diff.length; i < ln; i++) { removingElement = axis.getGraphicalElement('' + diff[i].value + LABEL_ID); if (removingElement) { axis.removeGraphicalElement(removingElement); } } axisConfig.prevCategoryIntervalArr = (0, _lib.extend2)([], categoryArr); for (i = 0, ln = categoryArr.length; i < ln; i += 1) { categoryArrStr[i] = '' + categoryArr[i].value + LABEL_ID; } // main loop where the drawing starts for (i = 0, ln = categoryArr.length; i < ln; i += 1) { curCategoryIndex = categoryArr[i].index; curCategory = tickArr[curCategoryIndex]; config = axis.components.labels[curCategoryIndex].config; axisAttrObj = config.props.label.attr; tempEle = axis.getGraphicalElement(categoryArrStr[i]); textElement = animationManager.setAnimation({ el: tempEle || 'text', attr: axisAttrObj, container: axisContainer, data: { value: curCategoryValue }, component: axis, label: 'text', css: config.props.label.css }); if (!tempEle) { axis.addGraphicalElement(categoryArrStr[i], textElement); textElement.on('fc-click', raiseEvent('dataLabelClick')).hover(raiseEvent('dataLabelRollOver'), raiseEvent('dataLabelRollOut')); } textElement.data(EVENTARGS, { link: !chartConfig.singleseries && curCategory.link || curCategory.labellink || style.labelLink, text: axisAttrObj.text, index: curCategoryIndex }); if (curCategory.labelTooltext) { toolTipController.enableToolTip(textElement, curCategory.labelTooltext); } else { toolTipController.disableToolTip(textElement); } categoryLabel[curCategoryIndex] = textElement; } } else { for (i = 0, ln = axisConfig.prevCategoryIntervalArr.length; i < ln; i++) { removingElement = axis.getGraphicalElement('' + axisConfig.prevCategoryIntervalArr[i].value + LABEL_ID); if (removingElement) { axis.removeGraphicalElement(removingElement); } } } }; Cartesian.prototype._getCategoryArr = function _getCategoryArr() { var axis = this, axisConfig = axis.config, // realtimeEnabled = axis.getFromEnv('chart').config.realtimeEnabled, isVertical = axisConfig.isVertical, tempStep = 0, count = 0, category, i, max, min, curCategory, getLimit, curCategoryValue, increment, intervalWidth, checkForLimit, retArr = []; // NOTE: animateCategories seems to be legacy code. It was present at one point to force the // first incoming category to be drawn outside the canvas bounds. // if (axisConfig.isCategoryAnimate && axisConfig.animateCategories) { // category = axisConfig.animateCategories; // } else { category = axisConfig.tickValues.tickValue; // } min = minimumEnquiry(category); max = category ? category.length - 1 : 0; if (isVertical) { intervalWidth = Math.abs(axis.getPixel(0, queryOptions) - axis.getPixel(1, queryOptions)); // check for overlap if there is any make the step such that no overlap happens if (axisConfig.labelMaxH > intervalWidth) { tempStep = Math.ceil(axisConfig.labelMaxH / intervalWidth); } if (tempStep > axisConfig.labels.step) { axisConfig.labels.step = tempStep; } } increment = axisConfig.labels.step > 0 ? axisConfig.labels.step : 1; // a redundant check was there in 3.12.2, need to verify if it is really required // and the check of step skipped is required // if (realtimeEnabled) { // increment = 1; // } // if not zoomed dont check for limit checkForLimit = axis.getZoom() !== 1; getLimit = this.getVisibleConfig(); // main loop where the drawing starts for (i = min; i <= max; i += increment) { curCategory = category[i]; if (!curCategory /* || (realtimeEnabled && curCategory.stepSkipped) */) { continue; } // TODO : need to curCategoryValue = (0, _lib.pluckNumber)(curCategory.x, curCategory.y, i); if ((0, _lib.pluckNumber)(curCategory.showlabel, axisConfig.showLabels, 1) === 0) { continue; } // if value is not between the visual limit increment it and continue if (checkForLimit && (curCategoryValue < getLimit.minValue || curCategoryValue > getLimit.maxValue)) { curCategory.labelCount = count++; continue; } if ((axisConfig.xAxisLabelMode === 'auto' || axisConfig.xAxisLabelMode === 'mixed') && (axisConfig.showZeroPlane === 0 || axisConfig.showZeroPlaneValue === 0) && curCategoryValue === 0) { continue; } // if values are not limit value and label drawing is off other // than limit increment it and continue if (!axisConfig.labels.drawNormalVal && !(axisConfig.labels.drawLimitVal && (i === min || i === max))) { continue; } if (!axisConfig.labels.drawNormalVal && !(i === min || i === max)) { continue; } // if value are limit value but limit value are not mean to be drawn if (!axisConfig.labels.drawLimitVal && (i === min || i === max)) { continue; } curCategory.labelCount = count++; retArr.push({ index: i, value: curCategoryValue }); } return retArr; }; /** * Function returning values for respective pixel passed * @param {number} pixel the pixel value for which the (X or Y) value is required * @param {Object} options An object which indicates whether values should be w.r.t. the visible range * @return {number} Value for which the pixel is passed */ Cartesian.prototype.getValue = function getValue(pixel) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { wrtVisible: false }; var scale = this.getScale(), translateValue = this.getTranslation(), domainValue = scale.getDomainValue(options.wrtVisible ? pixel : pixel - translateValue); return domainValue; }; /** * Function returning the pixel for respective value passed * @param {number} value The value for which the pixel value is required * @param {Object} options The object containing information about whether the axis should * return values w.r.t. the old axis OR w.r.t. the visible range * @return {number} The pixel corresponding to the given value */ Cartesian.prototype.getPixel = function getPixel(value) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { wrtVisible: false }; var scale = this.getScale(), translateValue = this.getTranslation(), rangeValue = scale.getRangeValue(value); return options.wrtVisible ? rangeValue : rangeValue + translateValue; }; /** * Function returning the pixel for respective value and length passed to it * @param {number} value The value for which the pixel value is required * @param {number} length The length with respect to which the pixel is required * @param {Object} options The object containing information about whether the axis should * return values w.r.t. the old axis OR w.r.t. the visible range * @return {number} The pixel corresponding to the given value and length */ Cartesian.prototype._getCustomPixel = function _getCustomPixel(value, length) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { wrtVisible: false }; if (!length) { return this.getPixel(value, options); } var newScale = this.getScale().copy(), _newScale$getRange = newScale.getRange(), val1 = _newScale$getRange[0], val2 = _newScale$getRange[1], min = Math.min(val1, val2), rangeValue = newScale.getRangeValue(value), translateValue = this.getTranslation(); newScale.setRange([min, min + length]); return options.wrtVisible ? rangeValue : rangeValue + translateValue; }; /** * Returns the amount by which the visible window is translated with respect to the axis' * reference point * @return {number} The translation amount */ Cartesian.prototype.getTranslation = function getTranslation() { return this.config.translation || 0; }; /** * Sets the scrolling behavior of the axis. * **'none'** indicates that the scroll bar wil never be shown * **'smart'** indicates that the scroll bar will be shown only when the axis limits are beyond * the visible limits of the chart * **'always'** indicates that the scroll bar will always be visible * @param {string} type The type of scroll behavior. */ Cartesian.prototype.setScrollType = function setScrollType(type) { if (type === 'none' || type === 'smart' || type === 'always') { this.config.scrollType = type; if (type === 'none') { this.disableScroll(); } else { this.enableScroll(); } } }; /** * Returns the currently active scrolling behavior of the axis. * @return {string} The axis' scrolling behavior */ Cartesian.prototype.getScrollType = function getScrollType() { return this.config.scrollType; }; /** * Sets up the scroll bar associated with the axis and attaches it as a component of the axis. * Also sets the handler function to be executed when the scroll bar is dragged. */ Cartesian.prototype._createScrollBar = function _createScrollBar() { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), animationManager = axis.getFromEnv('animationManager'), scrollerInstance = axis.getChildren('scrollBar') && axis.getChildren('scrollBar')[0], prevPos; if (!scrollerInstance) { // adding the scrollbar. scrollerInstance = axis.attachChild(new _tools.Scroller(), 'scrollBar'); } scrollerInstance.configure({ isHorizontal: !axisConfig.isVertical }); scrollerInstance.attachEventHandlers({ scrollStart: function scrollStart(scrollPosition) { prevPos = scrollPosition; chart.fireChartInstanceEvent('scrollstart', { scrollPosition: scrollPosition }); }, scroll: function scroll(scrollPosition) { var axisMax = axisConfig.axisRange.max, axisMin = axisConfig.axisRange.min, visibleConfig = axis.getVisibleConfig(), visibleMin = visibleConfig.minValue, visibleMax = visibleConfig.maxValue, visibleRange = visibleMax - visibleMin, interpolateMax = axisMax - visibleRange, interpolate = (0, _number2['default'])(axisMin, interpolateMax), visibleStart = axisConfig.isReverse ? interpolate(1 - scrollPosition) : interpolate(scrollPosition); axis.setState('scrolling', true); animationManager.setAnimationState('scroll'); chart.fireChartInstanceEvent('onScroll', { scrollPosition: scrollPosition }); axis.setVisibleConfig(visibleStart, visibleStart + visibleRange); }, scrollEnd: function scrollEnd(scrollPosition) { chart.fireChartInstanceEvent('scrollend', { scrollPosition: scrollPosition, prevScrollPosition: prevPos }); } }); }; Cartesian.prototype._disposeScrollBar = function _disposeScrollBar() { var axis = this, scrollBar = axis.getChildren('scrollBar') && axis.getChildren('scrollBar')[0]; if (scrollBar) { scrollBar.remove(); } }; /** * Returns the scrollbar dimensions */ Cartesian.prototype.getScrollerDimension = function getScrollerDimension() { var axis = this, chart = axis.getFromEnv('chart'), axisConfig = axis.config, axisRange = axisConfig.axisRange, scrollOptions = axisConfig.scrollOptions || (axisConfig.scrollOptions = {}), max = axisRange.max, min = axisRange.min, vxLength = scrollOptions.vxLength, scrollBar = axis.getChildren('scrollBar')[0], scrollConf, canvasLeft, canvasTop, canvasHeight, canvasWidth, canvasConfig = chart.getChildren('canvas')[0].config, canvasBorderWidth, axisLineWidth, axisLineStartExtension, axisLineEndExtension, scrollRatio, windowedCanvasWidth, fullCanvasWidth, scrollBarParentGroup = axisConfig.scrollerContainer, visibleConfig, visibleMax, visibleMin, visibleRange, totalRange, scrollPosition; if (!scrollBar) { return; } scrollConf = scrollBar.config; canvasLeft = canvasConfig.canvasLeft; canvasTop = canvasConfig.canvasTop; canvasHeight = canvasConfig.canvasHeight; canvasWidth = canvasConfig.canvasWidth; canvasBorderWidth = canvasConfig.canvasBorderWidth; axisLineWidth = axisConfig.showAxisLine ? axisConfig.axisLineThickness || 0 : 0; axisLineStartExtension = (0, _lib.pluckNumber)(canvasBorderWidth, axisConfig.lineStartExtension); axisLineEndExtension = (0, _lib.pluckNumber)(canvasBorderWidth, axisConfig.lineEndExtension); scrollOptions.viewPortMin = min; scrollOptions.viewPortMax = max; visibleConfig = axis.getVisibleConfig(); visibleMax = visibleConfig.maxValue; visibleMin = visibleConfig.minValue; visibleRange = visibleMax - visibleMin; totalRange = axisRange.max - axisRange.min; scrollRatio = visibleRange / totalRange; scrollPosition = (visibleMin - axisRange.min) / (totalRange - visibleRange); windowedCanvasWidth = scrollOptions.windowedCanvasWidth = axis.getPixel(vxLength, queryOptions); fullCanvasWidth = scrollOptions.fullCanvasWidth = axis.getPixel(max - min, queryOptions) - windowedCanvasWidth; scrollConf.scrollRatio = scrollRatio; scrollConf.roundEdges = canvasConfig.isRoundEdges; scrollConf.fullCanvasWidth = fullCanvasWidth; scrollConf.windowedCanvasWidth = windowedCanvasWidth; scrollConf.parentLayer = scrollBarParentGroup; scrollConf.scrollPosition = scrollPosition; // todo padding needs to be included. if (axisConfig.isVertical) { scrollConf.scrollPosition = axisConfig.isReverse ? 1 - scrollPosition : scrollPosition; return { x: canvasLeft, y: canvasTop, height: canvasHeight }; } else { scrollConf.scrollPosition = scrollPosition; return { x: canvasLeft - axisLineStartExtension, y: canvasTop + canvasHeight + canvasBorderWidth + axisLineWidth - 2, width: canvasWidth + axisLineStartExtension + axisLineEndExtension }; } }; Cartesian.prototype.enableScroll = function enableScroll() { // if (this.isScrollEnabled()) return; this._createScrollBar(); }; Cartesian.prototype.disableScroll = function disableScroll() { // if (!this.isScrollEnabled()) return; this._disposeScrollBar(); }; Cartesian.prototype.isScrollEnabled = function isScrollEnabled() { return !!this.getChildren('scrollBar'); }; /** * Sets the visible range of the axis. Also sets axis's reference values and re-calculates PVR. * @param {number} minValue The minimum value of the area to be visible * @param {number} maxValue The maximum value of the area to be visible * @return {boolean} Whether the visible range of the axis was successfully set or not */ Cartesian.prototype.setVisibleConfig = function setVisibleConfig(minValue, maxValue) { var axis = this, axisConfig = axis.config, prevZoom = axis.getZoom(), scale = axis.getScale(), domain = void 0; if (minValue >= maxValue || minValue < axisConfig.axisRange.min || maxValue > axisConfig.axisRange.max) { return false; } domain = scale.setDomain([minValue, maxValue]).getDomain(); axisConfig.visibleMin = domain[0]; axisConfig.visibleMax = domain[1]; axisConfig.zoom = axis._computeZoom(); axisConfig.translation = axis._computeTranslation(); if (prevZoom !== 1 || axis.getZoom() !== 1) { axisConfig.ticks = axis.generateTicks(); axisConfig.minorTicks = axis.generateMinorTicks(); axisConfig.tickValues && axis.calculateTicksOnLabelMode && axis.calculateTicksOnLabelMode(); } // axis.decideScroll(); axis.clearReferenceInfo(); axis._parseReferenceVisuals(); axis.fireEvent('visiblerangeset', { minValue: minValue, maxValue: maxValue }); axis.asyncDraw(); // Indicate that the value was successfully set return true; }; /** * Hides the axis components */ Cartesian.prototype.hide = function hide() { var axis = this, axisConfig = axis.config; if (!axisConfig.axisContainer) { return; } axisConfig.axisLabelContainerTop.hide(); // axisConfig.scrollerContainer.hide(); axisConfig.axisContainer.hide(); axisConfig.axisNameContainer.hide(); axisConfig.axisTrendLabelContainer.hide(); axisConfig.axisAxisLineContainer.hide(); axisConfig.axisAxisLineContainerBottom.hide(); }; /** * Hides the axis components */ Cartesian.prototype.show = function show() { var axis = this, axisConfig = axis.config; if (!axisConfig.axisContainer) { return; } axisConfig.axisLabelContainerTop.show(); // axisConfig.scrollerContainer.show(); axisConfig.axisContainer.show(); axisConfig.axisNameContainer.show(); axisConfig.axisTrendLabelContainer.show(); axisConfig.axisAxisLineContainer.show(); axisConfig.axisAxisLineContainerBottom.show(); }; Cartesian.prototype.getZoom = function getZoom() { return this.config.zoom || 1; }; Cartesian.prototype._computeTranslation = function _computeTranslation() { var axisConfig = this.config, visibleDomain = this.getVisibleConfig(), visibleMin = (0, _lib.pluckNumber)(visibleDomain.minValue, axisConfig.axisRange.min, 0), rangeMin = (0, _lib.pluckNumber)(axisConfig.axisRange.min, visibleDomain.minValue, 0); return this.getPixel(visibleMin) - this.getPixel(rangeMin); }; Cartesian.prototype._computeZoom = function _computeZoom() { var axisConfig = this.config, visibleDomain = this.getVisibleConfig(), visibleMin = (0, _lib.pluckNumber)(visibleDomain.minValue, axisConfig.axisRange.min, 0), visibleMax = (0, _lib.pluckNumber)(visibleDomain.maxValue, axisConfig.axisRange.max, 1), rangeMin = (0, _lib.pluckNumber)(axisConfig.axisRange.min, visibleDomain.minValue, 0), rangeMax = (0, _lib.pluckNumber)(axisConfig.axisRange.max, visibleDomain.maxValue, 1), zoomLimit = axisConfig.maxZoomLimit, zoom = (rangeMax - rangeMin) / (visibleMax - visibleMin); return zoom > zoomLimit ? zoomLimit : zoom; }; Cartesian.prototype.getTickValues = function getTickValues() { var tickInfo = this.config.tickValues; return tickInfo && tickInfo.tickValue || []; }; Cartesian.prototype.dataLabels = function dataLabels(value) { var axis = this, axisIndex = axis.config.axisIndex, numberFormatter = axis.getFromEnv('number-formatter'); return numberFormatter.dataLabels(value, axisIndex); }; /** * Function to get the base position of the axis. Base required for plots like column, area etc. * @return {number} the base value */ Cartesian.prototype.getAxisBase = function getAxisBase() { var _getVisibleConfig = this.getVisibleConfig(), minValue = _getVisibleConfig.minValue, maxValue = _getVisibleConfig.maxValue; // For inverse axis charts, columns should not be hanging from top when all data is positive return minValue < 0 && maxValue > 0 ? 0 : maxValue <= 0 ? maxValue : minValue; }; Cartesian.prototype._parseReferenceVisuals = function _parseReferenceVisuals() { var axis = this, axisConfig = axis.config, tickValues = axis.getTickValues(), min = 0, max = tickValues.length, is3d = axis.getFromEnv('chartConfig').is3D, preLineDrawState, preBandDrawState; if (!axisConfig.isActive) { preLineDrawState = axisConfig.lines.isDraw; preBandDrawState = axisConfig.band.isDraw; axisConfig.lines.isDraw = 0; axisConfig.band.isDraw = 0; } if (!axisConfig.tickValues) { axisConfig.drawPlotlines && axis._parsePlotLine(); } else { // axisConfig.drawLabels && axis._drawCategory(); axisConfig.drawLabels && axis._parseCategoryLine(tickValues, min, max); } if (!axisConfig.tickValues || axisConfig.xAxisLabelMode === 'auto') { axisConfig.drawPlotBands && !is3d && axis._parsePlotBand(); } else { // axisConfig.drawPlotlines && axis._drawCategoryVline(); axisConfig.drawPlotlines && !is3d && axis._parseCategoryPlotLine(); axisConfig.drawPlotBands && !is3d && axis._parseCategoryPlotBand(); if (axisConfig.xAxisLabelMode === 'mixed') { axisConfig.drawPlotBands && !is3d && axis._parsePlotBand(); } } if (!axisConfig.isActive) { axisConfig.lines.isDraw = preLineDrawState; axisConfig.band.isDraw = preBandDrawState; } axisConfig.drawTrendLines && axis._parseTrendLine(); }; /* * function is called internally by the axis class draw function to draw the axis plot bands */ Cartesian.prototype._parseCategoryPlotBand = function _parseCategoryPlotBand() { var axis = this, axisConfig = axis.config, tickValue = axisConfig.tickValues.tickValue, showAlternateGridColor = axisConfig.showAlternateGridColor, alternateGridColor = axisConfig.alternateGridColor, alternateGridAlpha = axisConfig.alternateGridAlpha, ticks = axisConfig._allTicks, limit = axis.getLimit(), min = limit.min, max = limit.max, axisAttrObj, colorDetector, from, to, willDraw = isVisible(axis.getVisibleConfig()), i; // checking for pure category axis exclude bubble scatter if (tickValue[0] && (tickValue[0].x !== _lib.UNDEF || tickValue[0].y !== _lib.UNDEF)) { return; } // checking if lines are to be drawn user can decide if (showAlternateGridColor && axisConfig.band.isDraw && axisConfig.categoryNumDivLines) { // common attributes axisAttrObj = { fill: (0, _lib.toRaphaelColor)((0, _lib.convertColor)(alternateGridColor, alternateGridAlpha)), 'stroke-width': 0 }; colorDetector = 0; for (i = 0; i < ticks.length; ++colorDetector, ++i) { if (!willDraw(ticks[i], ticks[i + 1])) { continue; } // if this should be colored band or not from = ticks[i]; if (colorDetector % 2 !== 0) { continue; } to = ticks[i + 1]; if (to === _lib.UNDEF) { continue; } // starting band will start from canvas left and last band will end at // canvas right if it was about to end at axis max if (from === min) from = 'canvasStart'; if (to === max) to = 'canvasEnd'; axis.setReferenceInfo({ from: from, to: to, layer: 0, type: 'band', attr: axisAttrObj }); } } }; Cartesian.prototype._parseTrendLine = function _parseTrendLine() { var axis = this, axisConfig = axis.config, isVertical = axisConfig.isVertical, axisIndex = axisConfig.axisIndex, chartAttr = axis.getFromEnv('chart-attrib'), numberFormatter = axis.getFromEnv('number-formatter'), axisRange = axisConfig.axisRange, max = axisRange.max, min = axisRange.min, style = axisConfig.trend.trendStyle, css = { fontFamily: style.fontFamily, fontSize: style.fontSize, lineHeight: style.lineHeight, fontWeight: style.fontWeight, fontStyle: style.fontStyle }, vtrendlines = axisConfig.vTrendLines, trendlines = axisConfig.trendLines, i, iLim, j, jLen, toolText, showOnTop, counter = 0, comTrendLines, isTrendZone, axisDrawingAttrObj, axisTextAttrObj, trendObj, text, valueOnRight, startValue, endValue, strokeWidth, NFMethodName, from, type, to; // get the trend line object comTrendLines = trendlines || vtrendlines; if (comTrendLines) { for (j = 0, jLen = comTrendLines.length; j < jLen; j += 1) { for (i = 0, iLim = comTrendLines[j].line && comTrendLines[j].line.length; i < iLim; i += 1) { trendObj = comTrendLines[j].line[i]; NFMethodName = isVertical ? 'yAxis' : 'xAxis'; startValue = trendObj.startvalue || trendObj.value || 0; startValue = numberFormatter.getCleanValue((0, _lib.pluck)(trendObj.startvalue, trendObj.value, 0)); endValue = Number(trendObj.endvalue) || _lib.UNDEF; toolText = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(comTrendLines[j].line[i].tooltext, comTrendLines[0].tooltext, axisConfig.trendlineToolText))); toolText = (0, _lib.parseTooltext)(toolText, [7, 15, 16, 17, 18, 19], { startValue: startValue, startDataValue: numberFormatter[NFMethodName](startValue, axisIndex), endValue: endValue || startValue, endDataValue: numberFormatter[NFMethodName](endValue || startValue, axisIndex), axisName: axisConfig.axisName }, trendObj); if (startValue > max || startValue < min || endValue > max || endValue < min) { continue; } // prepare the trend line or zone path and attributes if (vtrendlines) { // y-axis text = (0, _lib.parseUnsafeString)(trendObj.displayvalue || ''); isTrendZone = (0, _lib.pluckNumber)(trendObj.istrendzone, axisConfig.isTrendZone, 1); // trend zone if (endValue !== _lib.UNDEF && endValue !== '' && endValue !== startValue && isTrendZone) { axisDrawingAttrObj = { fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, axisConfig.trendlineColor), (0, _lib.pluck)(trendObj.alpha, axisConfig.trendlineAlpha, 40)), 'stroke-width': 0 }; axisTextAttrObj = { fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, style.color), (0, _lib.pluck)(style.valueAlpha, trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'vertical-align': _lib.POSITION_TOP, 'text': text }; } else { // trend line strokeWidth = (0, _lib.pluckNumber)(trendObj.thickness, axisConfig.trendlineThickness, 1); axisDrawingAttrObj = { stroke: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, axisConfig.trendlineColor), (0, _lib.pluck)(trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'stroke-width': strokeWidth, 'stroke-dasharray': (0, _lib.pluck)(trendObj.dashed, axisConfig.trendlinesAreDashed) === _lib.ONESTRING ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(trendObj.dashlen, axisConfig.trendlinesDashLen), (0, _lib.pluckNumber)(trendObj.dashgap, axisConfig.trendlinesDashGap)) : _lib.DASH_DEF }; axisTextAttrObj = { fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, style.color), (0, _lib.pluck)(style.valueAlpha, trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'vertical-align': _lib.POSITION_TOP, 'text': text }; } } else if (trendlines) { // x-axis text = (0, _lib.pluck)((0, _lib.parseUnsafeString)(trendObj.displayvalue), trendObj.startvalue, ''); valueOnRight = (0, _lib.pluckNumber)(trendObj.valueonright, 0); isTrendZone = (0, _lib.pluckNumber)(trendObj.istrendzone, axisConfig.isTrendZone, 0); if (endValue !== _lib.UNDEF && endValue !== '' && endValue !== startValue && isTrendZone) { // trend zone axisDrawingAttrObj = { fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, axisConfig.trendlineColor), (0, _lib.pluck)(trendObj.alpha, axisConfig.trendlineAlpha, 40)), 'stroke-width': 0 }; axisTextAttrObj = { 'text-anchor': valueOnRight ? _lib.POSITION_START : _lib.POSITION_END, fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, style.color), (0, _lib.pluck)(style.valueAlpha, trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'text': text }; } else { // trend line strokeWidth = (0, _lib.pluckNumber)(trendObj.thickness, axisConfig.trendlineThickness, 1); axisDrawingAttrObj = { stroke: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, axisConfig.trendlineColor), (0, _lib.pluck)(trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'stroke-width': strokeWidth, 'stroke-dasharray': (0, _lib.pluck)(trendObj.dashed, axisConfig.trendlinesAreDashed) === _lib.ONESTRING ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(trendObj.dashlen, axisConfig.trendlinesDashLen), (0, _lib.pluckNumber)(trendObj.dashgap, axisConfig.trendlinesDashGap)) : _lib.DASH_DEF }; axisTextAttrObj = { 'text-anchor': valueOnRight ? _lib.POSITION_START : _lib.POSITION_END, fill: (0, _lib.convertColor)((0, _lib.pluck)(trendObj.color, style.color), (0, _lib.pluck)(style.valueAlpha, trendObj.alpha, axisConfig.trendlineAlpha, 99)), 'text': text }; } } axisTextAttrObj['text-bound'] = axisTextAttrObj.text ? [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash] : []; if (!(axisConfig.showTooltip && toolText)) { toolText = ''; } showOnTop = axisConfig.forceTrendBelow ? 0 : (0, _lib.pluckNumber)(trendObj.showontop, chartAttr.showtrendlinesontop, 0); if (isVertical) { from = startValue; to = endValue !== _lib.UNDEF ? endValue : startValue; } else { from = endValue !== _lib.UNDEF ? endValue : startValue; to = startValue; } type = isTrendZone && from !== to ? 'band' : 'line'; from !== _lib.UNDEF && axis.setReferenceInfo({ from: from, to: to, toolText: toolText, attr: axisDrawingAttrObj, layer: showOnTop ? 3 : 2, type: type, id: 'trend' + counter + type }); axisConfig.parsedTrendLabels.push({ css: css, valueOnRight: valueOnRight, isTrendZone: isTrendZone, from: startValue, to: endValue, attr: axisTextAttrObj }); counter += 1; } } } }; /* * function is called internally by the axis class draw function to draw the axis plot lines */ Cartesian.prototype._parsePlotLine = function _parsePlotLine() { var axis = this, axisConfig = axis.config, axisRange = axisConfig.axisRange, max = axisRange.max, min = axisRange.min, willDraw = isInBetween(axis.getVisibleConfig()), showCanvasBorder = axisConfig.showCanvasBorder, plotLineColor = (0, _lib.convertColor)(axisConfig.divLineColor, axisConfig.divLineAlpha), plotLineWidth = axisConfig.divLineThickness, plotLineDashStyle = axisConfig.divLineIsDashed ? (0, _lib.getDashStyle)(axisConfig.divLineDashLen, axisConfig.divLineDashGap) : _lib.DASH_DEF, zeroPlaneColor = (0, _lib.convertColor)(axisConfig.zeroPlaneColor, axisConfig.zeroPlaneAlpha), zeroPlaneThickness = axisConfig.zeroPlaneThickness, ticks = axisConfig._allTicks, len = ticks.length, i, j, showZeroPlaneOnTop = axisConfig.showZeroPlaneOnTop, minorTicksArr = axisConfig.minorTicks, minorTicksLen = minorTicksArr && minorTicksArr.length, minorTicks, axisAttrObj, minorAttrObj; // checking if lines are to be drawn user can decide if (axisConfig.lines.isDraw) { for (j = 0; j < len; ++j) { i = ticks[j]; if (!willDraw(i)) { continue; } axisAttrObj = { 'stroke-dasharray': plotLineDashStyle }; // condition check for zero plane if (axisConfig.showZeroPlane === 0 && i === 0 || showCanvasBorder && (i === max || i === min)) { continue; } // attach the required attributes for zeroplane if applicable if (i === 0 && i !== min && i !== max) { axisAttrObj.stroke = zeroPlaneColor; axisAttrObj['stroke-width'] = zeroPlaneThickness; showZeroPlaneOnTop = axisConfig.showZeroPlaneOnTop; } else { showZeroPlaneOnTop = 0; axisAttrObj.stroke = plotLineColor; axisAttrObj['stroke-width'] = plotLineWidth; } axis.setReferenceInfo({ type: 'line', from: i, layer: i === 0 && showZeroPlaneOnTop ? 3 : 1, attr: axisAttrObj }); } } minorAttrObj = { stroke: axisConfig.minorDivlinecolor, 'stroke-width': axisConfig.minorDivLineThickness, 'stroke-dasharray': plotLineDashStyle }; for (j = 0; j < minorTicksLen; ++j) { minorTicks = minorTicksArr[j]; axis.setReferenceInfo({ type: 'line', from: minorTicks, layer: 1, attr: minorAttrObj }); } }; Cartesian.prototype._parseCategoryLine = function _parseCategoryLine(category, min, max) { var axis = this, axisConfig = axis.config, colorM = axis.getFromEnv('color-manager'), chartInstance = axis.getFromEnv('chartInstance'), categories = chartInstance.getJSONData().categories, categoriesStyle = {}, i, curCategory, getLimit, categoryLineAttr, curCategoryValue, checkForLimit; min = min || 0; max = max || category ? category.length - 1 : 0; if (axisConfig.drawPlotlines) { // if not zoomed dont check for limit checkForLimit = axis.getZoom() !== 1; getLimit = this.getVisibleConfig(); if (categories && categories[0]) { categoriesStyle.verticalLineColor = categories[0].verticallinecolor; categoriesStyle.verticalLineAlpha = categories[0].verticallinealpha; categoriesStyle.verticalLineThickness = categories[0].verticallinethickness; categoriesStyle.verticalLineDashed = categories[0].verticallinedashed; categoriesStyle.verticalLineDashLen = categories[0].verticallinedashlen; categoriesStyle.verticalLineDashGap = categories[0].verticallinedashgap; } // main loop where the drawing starts for (i = min; i <= max; i += 1) { curCategory = category[i]; if (!curCategory) { continue; } curCategoryValue = (0, _lib.pluckNumber)(curCategory.x, curCategory.y, i); if (Number(curCategory.showverticalline) !== 1) { continue; } // if value is not between the visual limit increment it and continue if (checkForLimit && (curCategoryValue < getLimit.minValue || curCategoryValue > getLimit.maxValue)) { continue; } categoryLineAttr = { stroke: (0, _lib.convertColor)((0, _lib.pluck)(curCategory.linecolor, categoriesStyle.verticalLineColor, axisConfig.divLineColor, colorM.getColor('divLineColor')), (0, _lib.pluck)(curCategory.linealpha, categoriesStyle.verticalLineAlpha, colorM.getColor('divLineAlpha'))), 'stroke-width': (0, _lib.pluckNumber)(curCategory.linethickness, categoriesStyle.verticalLineThickness, 1) }; categoryLineAttr['stroke-dasharray'] = (0, _lib.pluckNumber)(curCategory.linedashed, categoriesStyle.verticalLineDashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(curCategory.linedashLen, categoriesStyle.verticalLineDashLen, 4), (0, _lib.pluckNumber)(curCategory.linedashgap, categoriesStyle.verticalLineDashGap, 2), categoryLineAttr['stroke-width']) : _lib.DASH_DEF; axis.setReferenceInfo({ type: 'line', from: curCategoryValue, layer: 1, attr: categoryLineAttr }); } } }; /* * function is called internally by the axis class draw function to draw the axis plot bands */ Cartesian.prototype._parsePlotBand = function _parsePlotBand() { var axis = this, axisConfig = axis.config, showAlternateGridColor = axisConfig.showAlternateGridColor, alternateGridColor = axisConfig.alternateGridColor, alternateGridAlpha = axisConfig.alternateGridAlpha, axisAttrObj, colorDetector, ticks = axisConfig._allTicks, len, willDraw = isVisible(axis.getVisibleConfig()), i, to, isReverse = axisConfig.isReverse, from; // checking if lines are to be drawn user can decide if (showAlternateGridColor && axisConfig.band.isDraw) { colorDetector = 1; // common attributes axisAttrObj = { fill: (0, _lib.toRaphaelColor)((0, _lib.convertColor)(alternateGridColor, alternateGridAlpha)), 'stroke-width': 0 }; for (i = 0, len = ticks.length; i < len; ++i, ++colorDetector) { if (!willDraw(ticks[i], ticks[i + 1])) { continue; } // if this should be colored band or not if (colorDetector % 2 !== 0) { // intelegientIncrement(); continue; } if (ticks[i + 1] === _lib.UNDEF) { continue; } from = isReverse ? Math.max(ticks[i], ticks[i + 1]) : Math.min(ticks[i], ticks[i + 1]); to = isReverse ? Math.min(ticks[i], ticks[i + 1]) : Math.max(ticks[i], ticks[i + 1]); axis.setReferenceInfo({ from: from, to: to, type: 'band', layer: 0, attr: axisAttrObj }); } } }; Cartesian.prototype.getReferenceInfo = function getReferenceInfo() { return this.config.referenceInfo; }; Cartesian.prototype.setReferenceInfo = function setReferenceInfo(info) { this.config.referenceInfo.push(info); }; Cartesian.prototype.clearReferenceInfo = function clearReferenceInfo() { var axisConfig = this.config; axisConfig.referenceInfo = []; axisConfig.parsedTrendLabels = []; axisConfig.parsedVlineInfo = []; }; Cartesian.prototype.resetStoredLimits = function resetStoredLimits() { this.config.dataLimit = {}; }; Cartesian.prototype.decideScroll = function decideScroll() { var axis = this, scrollType = axis.getScrollType(); if (scrollType === 'always' || scrollType === 'smart' && axis.getZoom() !== 1) { axis.enableScroll(); } else { axis.disableScroll(); } }; Cartesian.prototype.getAxisDimension = function getAxisDimension() { var _config$axisDimention = this.config.axisDimention, x = _config$axisDimention.x, y = _config$axisDimention.y, opposite = _config$axisDimention.opposite, axisLength = _config$axisDimention.axisLength; return { x: x, y: y, opposite: opposite, axisLength: axisLength }; }; return Cartesian; }(_axis2['default']); Cartesian.prototype.setAxisDimention = _commonApi.setAxisDimention; Cartesian.prototype.shiftLabels = _commonApi.shiftLabels; Cartesian.prototype._createContainer = _commonApi._createContainer; exports['default'] = Cartesian; exports.getCrispPath = getCrispPath; exports.minimumEnquiry = minimumEnquiry; /***/ }), /* 380 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var /** * Forces a given value to a given limit * @param {number} value The value to be limited * @param {number} limit The number to which the given value must be limited * @return {number} The limited value */ _forceValidLowerLimit = function _forceValidLowerLimit(value, limit) { return value < limit ? limit : value; }; var Axis = function (_ComponentInterface) { _inherits(Axis, _ComponentInterface); function Axis() { _classCallCheck(this, Axis); return _possibleConstructorReturn(this, _ComponentInterface.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ Axis.prototype.getType = function getType() { return 'axis'; }; /** * Sets the default configuration of the axis */ Axis.prototype.__setDefaultConfig = function __setDefaultConfig() { _ComponentInterface.prototype.__setDefaultConfig.call(this); this.components = { labels: [] }; var config = this.config; config.setAdaptiveMin = 0; config.adjustDiv = 1; config.axisNameWidth = _lib.UNDEF; config.rotateAxisName = 0; config.useEllipsesWhenOverflow = 1; config.divLineColor = _lib.UNDEF; config.divLineAlpha = _lib.UNDEF; config.divLineThickness = _lib.UNDEF; config.divLineIsDashed = _lib.UNDEF; config.divLineDashLen = _lib.UNDEF; config.divLineDashGap = _lib.UNDEF; config.showAlternateGridColor = _lib.UNDEF; config.alternateGridColor = _lib.UNDEF; config.alternateGridAlpha = _lib.UNDEF; config.showZeroPlane = 1; config.zeroPlaneAlpha = 80; config.showZeroPlaneValue = 1; config.showZeroPlaneOnTop = 1; config.showAxisLine = _lib.UNDEF; config.axisLineThickness = _lib.UNDEF; config.axisLineAlpha = _lib.UNDEF; config.tickLength = 0; config.trendlineToolText = _lib.UNDEF; config.trendlineColor = '333333'; config.trendlineThickness = 1; config.trendlineAlpha = _lib.UNDEF; config.showTrendlinesOnTop = 0; config.trendlinesAreDashed = 0; config.trendlinesDashLen = 5; config.trendlinesDashGap = 2; config.isTrendZone = _lib.UNDEF; config.showTrendlines = 1; config.showTrendlineLabels = 1; config.showLabels = 1; config.maxLabelHeight = _lib.UNDEF; config.rotateLabels = _lib.UNDEF; config.slantLabel = 0; config.showAxisValues = 1; config.showTooltip = 1; config.isActive = true; // this attribute control the drawing of divline and trendline config.drawLabels = true; config.drawOnlyCategoryLine = false; // true only for candlestick volume canvas config.drawLabelsOpposit = false; config.drawPlotlines = true; config.drawAxisLine = true; config.drawPlotBands = true; config.drawAxisName = true; config.drawAxisNameOpposit = false; config.axisNameAlignCanvas = false; config.drawAxisNameFromBottom = false; config.drawTrendLines = true; config.drawTrendLabels = true; config.drawTick = true; config.drawTickMinor = true; config.animateAxis = true; config.drawAxisLineWRTCanvas = true; config.isRelativeAxisInverse = false; config.axisIndex = 0; config.uniqueClassName = 0; config.viewPortRatio = {}; config.canvas = {}; config.axisRange = {}; config.drawnStaggerLines = _lib.UNDEF; config.axisDimention = {}; config.forceZeroTick = true; // decides weather to add zero tick forcefully or not, can be given by charts config.isZeroTickForced = false; // keeps track weather zero tick has been added forcefully or not // configuration required for drag chart to edit the extreme labels config.extremeLabels = { firstLabel: {}, lastLabel: {} }; // these are configuration for internal use don't use it from outside config._setRangeAgain = false; config._defaultForceDecimal = _lib.UNDEF; config._defaultDecimalPrecision = _lib.UNDEF; config.rangeChanged = false; config.dimensionChanged = false; config.apparentScrollPos = 0; config.visibleMin = _lib.UNDEF; config.visibleMax = _lib.UNDEF; config.setPadding = false; config.trendLimits = _lib.UNDEF; }; /** * Prepare the axis attributes for use by the chart drawing. It applies default values to the * options that are undefined. * @param {Object} rawAttr The raw attributes to be set */ Axis.prototype.configureAttributes = function configureAttributes(rawAttr) { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), jsonData = axis.getFromEnv('dataSource'), is3D = chart.config.is3D, FCChartObj = jsonData.chart, numberFormatter = axis.getFromEnv('number-formatter'), axisAttr, fontBdrColor, trendFontBdrColor, labelFontBdrColor; axisAttr = axisConfig.rawAttr = rawAttr; axisConfig.referenceInfo = []; axisConfig.parsedTrendLabels = []; axisConfig.parsedVlineInfo = []; axisConfig.trendLines = axisAttr.trendlines; axisConfig.vTrendLines = axisAttr.vtrendlines; (0, _lib.parseConfiguration)(axisAttr, axisConfig); // TODO : validation of the attributes is required axisConfig.axisName = (0, _lib.parseUnsafeString)(axisAttr.axisName); // Store the attribute value in the axisConfig object axisConfig.axisValuePadding = axisConfig.axisNamePadding || (0, _lib.pluckNumber)(axisAttr.axisValuePadding, 4); // if change also in placeAxis axisConfig.axisNamePadding = axisConfig.axisNamePadding || (0, _lib.pluckNumber)(axisAttr.axisNamePadding, 5); // if change also in placeAxis axisConfig.maxLabelWidthPercent = (0, _lib.pluckNumber)(axisAttr.maxLabelWidthPercent); axisConfig.maxLabelWidthPercent = Math.abs(axisConfig.maxLabelWidthPercent); // Take minLabelWidthPercent from axis attribute and set it to config of axis axisConfig.minLabelWidthPercent = Math.abs((0, _lib.pluckNumber)(axisAttr.minLabelWidthPercent)); axisConfig.numDivLines = (0, _lib.pluckNumber)(axisAttr.numDivLines, 4); axisConfig.numDivLines = _forceValidLowerLimit(axisConfig.numDivLines, 0); axisConfig.categoryNumDivLines = (0, _lib.pluckNumber)(axisAttr.numDivLines, 0); axisConfig.axisValuePadding = _forceValidLowerLimit(axisConfig.axisValuePadding, 0); axisConfig.isReverse = (0, _lib.pluckNumber)(axisAttr.isReverse, 0); axisConfig.isOpposit = (0, _lib.pluckNumber)(axisAttr.isOpposit, 0); axisConfig.isVertical = (0, _lib.pluckNumber)(axisAttr.isVertical, 0); axisConfig.categoryDivLinesFromZero = 1; // can be overwritten programetically axisConfig.axisMinValue = numberFormatter.getCleanValue(axisAttr.axisMinValue); axisConfig.axisMaxValue = numberFormatter.getCleanValue(axisAttr.axisMaxValue); axisConfig.zeroPlaneColor = (0, _lib.pluck)(axisAttr.zeroPlaneColor, axisAttr.divLineColor); axisConfig.zeroPlaneThickness = (0, _lib.pluck)(axisAttr.zeroPlaneThickness, axisAttr.divLineThickness); axisConfig.axisLineColor = (0, _lib.convertColor)(axisAttr.axisLineColor, axisAttr.axisLineAlpha); axisConfig.tickAlpha = (0, _lib.pluckNumber)(axisAttr.tickAlpha, axisConfig.axisLineAlpha); axisConfig.tickColor = (0, _lib.convertColor)((0, _lib.pluck)(axisAttr.tickColor, axisAttr.axisLineColor), axisConfig.tickAlpha); axisConfig.tickWidth = (0, _lib.pluckNumber)(axisAttr.tickWidth, axisConfig.axisLineThickness); axisConfig.maxZoomLimit = (0, _lib.pluckNumber)(FCChartObj.maxzoomlimit, chart.maxzoomlimit, 1000); axisConfig.showVLines = (0, _lib.pluckNumber)(FCChartObj.showvlines, 1); axisConfig.showVLinesOnTop = (0, _lib.pluckNumber)(FCChartObj.showvlinesontop, 0); axisConfig.showVLineLabels = (0, _lib.pluckNumber)(FCChartObj.showvlinelabels, this.showVLineLabels, 1); axisConfig.showVLineLabelBorder = (0, _lib.pluckNumber)(FCChartObj.showvlinelabelborder, 1); axisConfig.rotateVLineLabels = (0, _lib.pluckNumber)(FCChartObj.rotatevlinelabels, 0); axisConfig.vLineColor = (0, _lib.pluck)(FCChartObj.vlinecolor, '333333'); axisConfig.vLineLabelColor = (0, _lib.pluck)(FCChartObj.vlinelabelcolor); axisConfig.vLineThickness = (0, _lib.pluck)(FCChartObj.vlinethickness, 1); axisConfig.vLineAlpha = (0, _lib.pluckNumber)(FCChartObj.vlinealpha, 80); axisConfig.vLineLabelBgColor = (0, _lib.pluck)(FCChartObj.vlinelabelbgcolor, 'ffffff'); axisConfig.vLineLabelBgAlpha = (0, _lib.pluckNumber)(FCChartObj.vlinelabelbgalpha, is3D ? 50 : 100); axisConfig.staggerLines = Math.max((0, _lib.pluckNumber)(FCChartObj.staggerlines, 2), 2); axisConfig.staggerLines = _forceValidLowerLimit(axisConfig.staggerLines, 1); axisConfig.trendlineValuesOnOpp = (0, _lib.pluck)(axisAttr.trendlineValuesOnOpp, axisAttr.trendlineValuesOnOpp, 0); axisConfig.labelDisplay = (0, _lib.pluck)(axisAttr.labelDisplay, 'auto').toLowerCase(); axisConfig.labelStep = (0, _lib.pluckNumber)(axisAttr.labelStep, 1); axisConfig.labelStep = Math.round(axisConfig.labelStep); axisConfig.labelStep = _forceValidLowerLimit(axisConfig.labelStep, 1); axisConfig.startPad = 0; axisConfig.endPad = 0; axisConfig._oriLabelStep = axisConfig.labelStep; axisConfig.showLimits = (0, _lib.pluckNumber)(axisAttr.showLimits, axisConfig.showAxisValues); axisConfig.showUpperLimit = axisAttr.showLimits; axisConfig.showDivLineValues = (0, _lib.pluckNumber)(axisAttr.showDivLineValues, axisConfig.showAxisValues); axisConfig.showCanvasBorder = chart.getChildren('canvas')[0].config.showCanvasBorder ? 1 : 0; axisConfig.axisBreak = axisAttr.axisBreaks; axisConfig.isBreak = !!axisConfig.axisBreak; if (axisConfig.isBreak) { axis._processAxisBreak(); } // Store the axis name style attributesa fontBdrColor = (0, _lib.getFirstValue)(axisAttr.axisNameBorderColor, _lib.BLANKSTRING); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(axisAttr.axisNameBorderAlpha, axisAttr.axisNameAlpha, 100)) : _lib.BLANKSTRING; axisConfig.name = axisConfig.name || {}; axisConfig.name.style = { fontFamily: (0, _lib.pluck)(axisAttr.axisNameFont, axisAttr.outCanfontFamily), fontSize: (0, _lib.pluck)(axisAttr.axisNameFontSize, (0, _lib.pInt)(axisAttr.outCanfontSize)) + _lib.PXSTRING, color: (0, _lib.convertColor)((0, _lib.pluck)(axisAttr.axisNameFontColor, axisAttr.outCancolor), (0, _lib.pluckNumber)(axisAttr.axisNameFontAlpha, axisAttr.axisNameAlpha, 100)), fontWeight: (0, _lib.pluckNumber)(axisAttr.axisNameFontBold, 1) ? 'bold' : _lib.NORMAL, fontStyle: (0, _lib.pluckNumber)(axisAttr.axisNameFontItalic) ? 'italic' : _lib.NORMAL, border: fontBdrColor || axisAttr.axisNameBgColor ? (0, _lib.pluckNumber)(axisAttr.axisNameBorderThickness, 1) + 'px solid' : _lib.UNDEF, borderColor: fontBdrColor, borderThickness: (0, _lib.pluckNumber)(axisAttr.axisNameBorderThickness, 1), borderPadding: (0, _lib.pluckNumber)(axisAttr.axisNameBorderPadding, 2), borderRadius: (0, _lib.pluckNumber)(axisAttr.axisNameBorderRadius, 0), backgroundColor: axisAttr.axisNameBgColor ? (0, _lib.convertColor)(axisAttr.axisNameBgColor, (0, _lib.pluckNumber)(axisAttr.axisNameBgAlpha, axisAttr.axisNameAlpha, 100)) : _lib.BLANKSTRING, borderDash: (0, _lib.pluckNumber)(axisAttr.axisNameBorderDashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(axisAttr.axisNameBorderDashLen, 4), (0, _lib.pluckNumber)(axisAttr.axisNameBorderDashGap, 2)) : _lib.DASH_DEF }; // Calculate the line height of the axis name axisConfig.name.style.lineHeight = (0, _lib.setLineHeight)(axisConfig.name.style); // Trend line label font style trendFontBdrColor = (0, _lib.getFirstValue)(FCChartObj.trendvaluebordercolor, _lib.BLANKSTRING); trendFontBdrColor = trendFontBdrColor ? (0, _lib.convertColor)(trendFontBdrColor, (0, _lib.pluckNumber)(FCChartObj.trendvalueborderalpha, FCChartObj.trendvaluealpha, 100)) : _lib.BLANKSTRING; axisConfig.trend = axisConfig.trend || {}; axisConfig.trend.trendStyle = { fontFamily: (0, _lib.pluck)(FCChartObj.trendvaluefont, axisAttr.outCanfontFamily), color: (0, _lib.pluck)(FCChartObj.trendvaluefontcolor, axisAttr.trendlineColor, axisAttr.outCancolor, '333333'), valueAlpha: FCChartObj.trendvaluealpha, fontSize: (0, _lib.pluckFontSize)(FCChartObj.trendvaluefontsize, (0, _lib.pInt)(axisAttr.outCanfontSize)) + _lib.PXSTRING, fontWeight: (0, _lib.pluckNumber)(FCChartObj.trendvaluefontbold) ? 'bold' : _lib.NORMAL, fontStyle: (0, _lib.pluckNumber)(FCChartObj.trendvaluefontitalic) ? 'italic' : _lib.NORMAL, // Set border as empty string when not required, // since IE will stop js execution if it is undefined or null. border: trendFontBdrColor || FCChartObj.trendvaluebgcolor ? (0, _lib.pluckNumber)(FCChartObj.trendvalueborderthickness, 1) + 'px solid' : '', borderColor: trendFontBdrColor, borderThickness: (0, _lib.pluckNumber)(FCChartObj.trendvalueborderthickness, 1), borderPadding: (0, _lib.pluckNumber)(FCChartObj.trendvalueborderpadding, 2), borderRadius: (0, _lib.pluckNumber)(FCChartObj.trendvalueborderradius, 0), backgroundColor: FCChartObj.trendvaluebgcolor ? (0, _lib.convertColor)(FCChartObj.trendvaluebgcolor, (0, _lib.pluckNumber)(FCChartObj.trendvaluebgalpha, FCChartObj.trendvaluealpha, 100)) : _lib.BLANKSTRING, borderDash: (0, _lib.pluckNumber)(FCChartObj.trendvalueborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(FCChartObj.trendvalueborderdashlen, 4), (0, _lib.pluckNumber)(FCChartObj.trendvalueborderdashgap, 2)) : _lib.DASH_DEF }; // Trend line label line height axisConfig.trend.trendStyle.lineHeight = (0, _lib.setLineHeight)(axisConfig.trend.trendStyle); axisConfig.labels = axisConfig.labels || {}; axisConfig.lines = axisConfig.lines || {}; axisConfig.band = axisConfig.band || {}; // Axis label style labelFontBdrColor = (0, _lib.getFirstValue)(FCChartObj.labelbordercolor, _lib.BLANKSTRING); labelFontBdrColor = labelFontBdrColor ? (0, _lib.convertColor)(labelFontBdrColor, (0, _lib.pluckNumber)(FCChartObj.labelborderalpha, FCChartObj.labelalpha, 100)) : _lib.BLANKSTRING; axisConfig.labels.style = { fontFamily: (0, _lib.pluck)(axisAttr.labelFont, axisAttr.outCanfontFamily), fontSize: (0, _lib.pluckNumber)(axisAttr.labelFontSize, (0, _lib.pInt)(axisAttr.outCanfontSize)) + _lib.PXSTRING, fontWeight: (0, _lib.pluckNumber)(axisAttr.labelFontBold) ? 'bold' : _lib.NORMAL, fontStyle: (0, _lib.pluckNumber)(axisAttr.labelFontItalic) ? 'italic' : _lib.NORMAL, color: (0, _lib.convertColor)((0, _lib.pluck)(axisAttr.labelFontColor, axisAttr.outCancolor), (0, _lib.pluckNumber)(axisAttr.labelFontAlpha, 100)), labelLink: FCChartObj.labellink, border: labelFontBdrColor || FCChartObj.labelbgcolor ? (0, _lib.pluckNumber)(FCChartObj.labelborderthickness, 1) + 'px solid' : '', borderColor: labelFontBdrColor, borderThickness: (0, _lib.pluckNumber)(FCChartObj.labelborderthickness, 1), borderPadding: (0, _lib.pluckNumber)(FCChartObj.labelborderpadding, 2), borderRadius: (0, _lib.pluckNumber)(FCChartObj.labelborderradius, 0), backgroundColor: FCChartObj.labelbgcolor ? (0, _lib.convertColor)(FCChartObj.labelbgcolor, (0, _lib.pluckNumber)(FCChartObj.labelbgalpha, FCChartObj.labelalpha, 100)) : _lib.BLANKSTRING, borderDash: (0, _lib.pluckNumber)(FCChartObj.labelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(FCChartObj.labelborderdashlen, 4), (0, _lib.pluckNumber)(FCChartObj.labelborderdashgap, 2)) : _lib.DASH_DEF }; // Axis label line height axisConfig.labels.style.lineHeight = (0, _lib.setLineHeight)(axisConfig.labels.style); axisConfig.numberFormatterFn = (0, _lib.pluck)(axisAttr.numberFormatterFn); // Setting zoom and scroll if present axisConfig.apparentScrollPos = axisAttr.apparentScrollPos || axisConfig.apparentScrollPos; // axis.setZoomScale(axisAttr.zoomScale || axisConfig.zoomScale); // flushing the axis range data for each configuartion axisConfig.axisRange = {}; axisConfig.dataLimit = {}; axisConfig.axisEndLabelDisplaySpace = { left: 0, right: 0, top: 0, bottom: 0 }; axisConfig.isConfigured = true; axisConfig._defaultForceDecimal = _lib.UNDEF; axisConfig._defaultDecimalPrecision = _lib.UNDEF; // axis.setScrollType('smart'); axisConfig.lines.isDraw = (0, _lib.pluckNumber)(axisAttr.lines && axisAttr.lines.isDraw, 1); axisConfig.band.isDraw = (0, _lib.pluckNumber)(axisAttr.band && axisAttr.band.isDraw, 1); }; Axis.prototype.createContainer = function createContainer(containerName, attr, container) { var animationManager = this.getFromEnv('animationManager'); return this.addContainer(containerName, animationManager.setAnimation({ container: container, attr: attr, el: this.getContainer(containerName) || 'group', component: this, label: 'group' })); }; Axis.prototype.createGroup = function createGroup(containerName, attr, container) { var label = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'group'; var animationManager = this.getFromEnv('animationManager'); return animationManager.setAnimation({ container: container, attr: attr, el: this.config[containerName] || 'group', component: this, label: label }); }; /** * returns the value padding of axis * * @returns {any} * @memberof Axis */ Axis.prototype.getValuePadding = function getValuePadding() { var axisConfig = this.config; return { left: axisConfig.startPad, right: axisConfig.endPad }; }; /** * The function is called whenever there is need to draw the axis or update the axis * NOTE : before calling the function placeAxis must be called to manage the space */ Axis.prototype.draw = function draw() { var axis = this, axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, isVertical = axisConfig.isVertical, viewPortConfig = chartConfig.viewPortConfig, limitUpdaters = axis.getChildren().limitUpdater, viewPortRatio = axisConfig.viewPortRatio || {}, dx, dy, originY, originX; axis._createContainer(); originY = viewPortConfig.y * viewPortConfig.scaleY; originX = viewPortConfig.x * viewPortConfig.scaleX; // On zoom condition if (viewPortRatio.scaleX && viewPortRatio.scaleY && (viewPortRatio.scaleX !== viewPortConfig.scaleX || viewPortRatio.scaleY !== viewPortConfig.scaleY)) { viewPortRatio.scaleX = viewPortConfig.scaleX; viewPortRatio.scaleY = viewPortConfig.scaleY; axis._drawComponents(); } else { // On pan condition // while panning no need to clip only transform accordingly if (isVertical) { // dy is the amount of the dataset transform vertically dy = originY - viewPortConfig.y * viewPortConfig.scaleY; // axisConfig.vlineLabelContainer.transform('t0,' + dy); axisConfig.axisContainer.transform('t0,' + dy); axisConfig.axisLabelContainerTop.transform('t0,' + dy); } else { // dx is the amount of the dataset transform horizontally dx = originX - viewPortConfig.x * viewPortConfig.scaleX; // axisConfig.vlineLabelContainer.transform('t' + dx + ',0'); axisConfig.axisContainer.transform('t' + dx + ',0'); axisConfig.axisLabelContainerTop.transform('t' + dx + ',0'); } // draw the axis elements axis._drawComponents(); // axis.translateRTGroups(); } axis.addExtEventListener('animationcomplete', function () { limitUpdaters && limitUpdaters.forEach(function (limitUpdater) { limitUpdater.draw(); }); }, axis.getFromEnv('animationmanager')); axis.addToEnv('prevScale', axis.getScale().copy()); }; Axis.prototype.setScale = function setScale(scale) { this.config.scale = scale; }; Axis.prototype.getScale = function getScale() { return this.config.scale; }; /** * Function returning limit of the axis * @return {Object} ({min:number,max: number}) return an object with axis limits as property */ Axis.prototype.getLimit = function getLimit() { var axisRange = this.config.axisRange; return { min: axisRange.min, max: axisRange.max, tickInterval: axisRange.tickInterval }; }; /** * Gets the visible min and max values from the axis * @return {Object} Contains minValue and maxValue, the min and max values of the visible area */ Axis.prototype.getVisibleConfig = function getVisibleConfig() { var axisConfig = this.config; return { minValue: axisConfig.visibleMin, maxValue: axisConfig.visibleMax }; }; /** * Function to set the axis config from (used for axis configuration) out side. * @param {Object} data Axis config object the values to be changed */ Axis.prototype.setAxisConfig = function setAxisConfig(data) { var axis = this, axisConfig = axis.config, prop; for (prop in data) { if (data.hasOwnProperty(prop)) { axisConfig[prop] = data[prop]; } } }; /** * Function to get the axis config. * @param {string} name Name of the configuration * @return {any} Value of the configuration */ Axis.prototype.getAxisConfig = function getAxisConfig(name) { var axis = this, axisConfig = axis.config; if (name) { return axisConfig[name]; } else { return axisConfig; } }; /** * Returns the difference between the visible max value and the visible min value * @return {number} The visible range */ Axis.prototype.getVisibleLength = function getVisibleLength() { var axis = this, limit = axis.getVisibleConfig(); return Math.abs(limit.maxValue - limit.minValue); }; Axis.prototype.getAxisEndLabelDisplaySpace = function getAxisEndLabelDisplaySpace() { return this.config.axisEndLabelDisplaySpace || {}; }; Axis.prototype.getTicksLen = function getTicksLen() { var tickInfo = this.config.tickValues; return tickInfo && tickInfo.tickValue.length || 0; }; return Axis; }(_componentInterface.ComponentInterface); exports['default'] = Axis; /***/ }), /* 381 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var appearingAxis = [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'axis' }], appearingFinal = [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], axisAnimationFinal = { 'text.appearing': appearingFinal, 'path.appearing': appearingFinal, 'rect.appearing': appearingFinal }, axisAnimationAxis = { 'text.appearing': appearingAxis, 'path.appearing': appearingAxis, 'rect.appearing': appearingAxis, 'scroller.appearing': appearingAxis }; exports['default'] = { 'initial.axis.numeric': axisAnimationAxis, 'initial.axis.category': axisAnimationAxis, 'initial.axis.log': axisAnimationAxis, 'update.axis.numeric': axisAnimationFinal, 'update.axis.category': axisAnimationFinal, 'update.axis.log': axisAnimationFinal }; exports.appearingAxis = appearingAxis; exports.appearingFinal = appearingFinal; exports.axisAnimationAxis = axisAnimationAxis; exports.axisAnimationFinal = axisAnimationFinal; /***/ }), /* 382 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; function interpolateNumber(min, max) { min = Number(min); max = Number(max); var diff = max - min; return function (ratio) { return diff * ratio + min; }; } exports["default"] = interpolateNumber; /***/ }), /* 383 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /* eslint require-jsdoc: 'error', valid-jsdoc: 'error' */ /** * Will give the difference in elements that is present in 1st array and not in 2nd array * @param {Array} arr1 array in which the diff will be checked * @param {Array} arr2 array by which the diff will be checked * @return {Array} array containing the diff elements */ var diff = function diff(arr1, arr2) { return arr1.filter(function (ele) { return arr2.indexOf(ele) < 0; }); }; exports["default"] = diff; /***/ }), /* 384 */ /***/ (function(module, exports, __webpack_require__) { var _containsWith = /*#__PURE__*/__webpack_require__(385); var _curry3 = /*#__PURE__*/__webpack_require__(203); /** * Finds the set (i.e. no duplicates) of all elements in the first list not * contained in the second list. Duplication is determined according to the * value returned by applying the supplied predicate to two list elements. * * @func * @memberOf R * @since v0.1.0 * @category Relation * @sig ((a, a) -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred A predicate used to test whether two items are equal. * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The elements in `list1` that are not in `list2`. * @see R.difference, R.symmetricDifference, R.symmetricDifferenceWith * @example * * var cmp = (x, y) => x.a === y.a; * var l1 = [{a: 1}, {a: 2}, {a: 3}]; * var l2 = [{a: 3}, {a: 4}]; * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] */ var differenceWith = /*#__PURE__*/_curry3(function differenceWith(pred, first, second) { var out = []; var idx = 0; var firstLen = first.length; while (idx < firstLen) { if (!_containsWith(pred, first[idx], second) && !_containsWith(pred, first[idx], out)) { out.push(first[idx]); } idx += 1; } return out; }); module.exports = differenceWith; /***/ }), /* 385 */ /***/ (function(module, exports) { function _containsWith(pred, x, list) { var idx = 0; var len = list.length; while (idx < len) { if (pred(x, list[idx])) { return true; } idx += 1; } return false; } module.exports = _containsWith; /***/ }), /* 386 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports._parseLabel = exports.extractStyleInfo = exports.getLabel = exports.setAxisPadding = exports._createContainer = exports.shiftLabels = exports.setTickValues = exports._drawLabel = exports.getPixel = exports.getTrendLineLimits = exports.setDataLimit = exports.setAxisDimention = undefined; var _lib = __webpack_require__(125); var _difference = __webpack_require__(387); var _difference2 = _interopRequireDefault(_difference); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var queryOptions = { wrtVisible: true }, LABEL_ID = '_label', NORMALSTRING = 'normal', /** * Extracts the style information of a category * @param {Object} cat The category whose style information is required */ extractStyleInfo = function extractStyleInfo(cat, chart) { var sAttrMap = { 'labelfont': ['fontFamily'], 'labelfontcolor': ['fontColor'], 'labelfontsize': ['fontSize', function (val) { return val ? (0, _lib.pluckNumber)(val) + 'px' : _lib.UNDEF; }], 'labelfontbold': ['fontWeight', function (val) { return val ? 'bold' : NORMALSTRING; }], 'labelfontitalic': ['fontStyle', function (val) { return val ? 'italic' : NORMALSTRING; }], 'labelfontalpha': ['fontAlpha'] }, cats = chart.getFromEnv('dataSource').categories, catData = cats && cats[0] || {}, defFn = function defFn(val) { return val; }, styleExists = false, attrKey, attrVal, secAttrVal, style = {}, attrRule, mappedAttr, mapFn, mappedVal; for (attrKey in catData) { if (attrKey === 'category' || attrKey in cat) { continue; } attrVal = catData[attrKey]; cat[attrKey] = attrVal; } for (attrKey in sAttrMap) { attrRule = sAttrMap[attrKey]; mappedAttr = attrRule[0]; mapFn = attrRule[1] || defFn; attrVal = cat[attrKey]; secAttrVal = cat[mappedAttr.toLowerCase()]; if (attrVal !== _lib.UNDEF || secAttrVal !== _lib.UNDEF) { if ((mappedVal = mapFn(attrVal)) !== _lib.UNDEF || (mappedVal = mapFn(secAttrVal)) !== _lib.UNDEF) { style[mappedAttr] = mappedVal; styleExists = true; } } if (styleExists) { cat.style = style; } } }, /** * Function set the starting point for drawing the axis and the axis drawing width/height * @param {Object} data Contains the x, y, length and whether the axis is drawn on the opposite side */ setAxisDimention = function setAxisDimention(data) { var axis = this, scale = axis.getScale(), axisConfig = axis.config, chart = axis.getFromEnv('chart'), chartConfig = chart.config, axisDimention = axisConfig.axisDimention || (axisConfig.axisDimention = {}), isReverse = axisConfig.isReverse; axisDimention.opposite = (0, _lib.pluckNumber)(data.opposite, axisDimention.opposite); axisDimention.x = (0, _lib.pluckNumber)(data.x, axisDimention.x, chartConfig.canvasLeft); axisDimention.y = (0, _lib.pluckNumber)(data.y, axisDimention.y, chartConfig.canvasTop); axisDimention.axisLength = (0, _lib.pluckNumber)(data.axisLength, axisDimention.axisLength); if (axisConfig.isVertical) { isReverse ? scale.setRange([axisDimention.y + axisDimention.axisLength, axisDimention.y]) : scale.setRange([axisDimention.y, axisDimention.y + axisDimention.axisLength]); } else { isReverse ? scale.setRange([axisDimention.x + axisDimention.axisLength, axisDimention.x]) : scale.setRange([axisDimention.x, axisDimention.x + axisDimention.axisLength]); } axisConfig.translation = axis._computeTranslation(); }, /** * Function set the div interval and set the max and min value used by axis * This function is called externally by the chart to adjust or define the axis limits * @param {number} max maximum limit of axis from the data * @param {number} min minimum limit of axis from the data */ setDataLimit = function setDataLimit(max, min) { var axis = this, axisConfig = axis.config, categories = axis.getFromEnv('dataSource').categories, categoryArr = categories && categories[0] && categories[0].category, startPad = axisConfig.startPad || 0, endPad = axisConfig.endPad || 0, catMin, catMax, trendMin, trendMax, xAxisLabelMode = axisConfig.xAxisLabelMode, numberAccessor = function numberAccessor(a) { return Number(a); }; if (xAxisLabelMode === 'categories' || xAxisLabelMode === 'mixed') { var _extent = (0, _lib.extent)(categoryArr, function (obj) { return Number(obj.x); }); // Include categories into the axis limit if the label mode is categories or mixed catMin = _extent[0]; catMax = _extent[1]; } var _axis$getTrendLineLim = axis.getTrendLineLimits(); trendMin = _axis$getTrendLineLim[0]; trendMax = _axis$getTrendLineLim[1]; var _extent2 = (0, _lib.extent)([trendMin, trendMax, catMin, catMax, min, max], numberAccessor); min = _extent2[0]; max = _extent2[1]; axisConfig.originalMax = max; axisConfig.originalMin = min; max = axisConfig.isPercent ? 100 : max + endPad; min = axisConfig.isPercent ? 0 : min - startPad; axis._setAxisRange({ min: min, max: max }); if (axisConfig.axisRange.tickInterval !== _lib.UNDEF) { axis._adjustNumberFormatter(axisConfig.axisRange.tickInterval); } }, getTrendLineLimits = function getTrendLineLimits() { var axisConfig = this.config, lines = axisConfig.trendLines || axisConfig.vTrendLines || axisConfig.trendPoints, lineArr = lines && lines[0] && lines[0].line || lines && lines.point, startMin = void 0, startMax = void 0, endMin = void 0, endMax = void 0; if (axisConfig.trendLimits) return axisConfig.trendLimits; var _extent3 = (0, _lib.extent)(lineArr, function (obj) { return obj.startvalue === '' ? _lib.UNDEF : Number(obj.startvalue); }); startMin = _extent3[0]; startMax = _extent3[1]; var _extent4 = (0, _lib.extent)(lineArr, function (obj) { return obj.endvalue === '' ? _lib.UNDEF : Number(obj.endvalue); }); endMin = _extent4[0]; endMax = _extent4[1]; axisConfig.trendLimits = (0, _lib.extent)([startMin, startMax, endMin, endMax], function (a) { return Number(a); }); return axisConfig.trendLimits; }, /** * Function returning the pixel for respective value passed * @param {number} value The value for which the pixel value is required * @param {Object} options The object containing information about whether the axis should * return values w.r.t. the old axis OR w.r.t. the visible range * @return {number} The pixel corresponding to the given value */ getPixel = function getPixel(value) { return this.getScale().getRangeValue(value); }, /** * Function is called internally by the axis class draw function to draw the axis labels */ _drawLabel = function _drawLabel() { var axis = this, axisConfig = axis.config, animationManager = axis.getFromEnv('animationManager'), toolTipController = this.getFromEnv('toolTipController'), axisRange = axisConfig.axisRange, labels = axisConfig.labels, style = labels.style, axisComponents = axis.components, i, j, ln, max = axisRange.max, min = axisRange.min, axisContainer = axisConfig.axisContainer, extremeLabels = axisConfig.extremeLabels, textElement, ticks = axisConfig.ticks, mapId, map = [], css = { fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight, fontStyle: style.fontStyle, lineHeight: style.lineHeight }, removingElement, axisAttrObj, value, diff, labelIndexArr, labelConfArr; // checking if labels are to be drawn user can decide or can be decided by axis placeAxis function if (axisConfig.labels.isDraw) { labelConfArr = axisComponents.labels; labelIndexArr = axisComponents.labelIndexArr; axisContainer.css(css); // main loop where the drawing starts for (j = 0, ln = labelIndexArr && labelIndexArr.length; j < ln; j += 1) { i = labelIndexArr[j]; value = ticks[i]; mapId = '' + value + LABEL_ID; textElement = axis.getGraphicalElement(mapId); axisAttrObj = labelConfArr[i].config.props.label.attr; textElement = axis.addGraphicalElement(mapId, animationManager.setAnimation({ el: textElement || 'text', attr: axisAttrObj, container: axisContainer, data: { value: value }, component: axis, label: 'text' })); if (axisAttrObj.tooltext) { toolTipController.enableToolTip(textElement, axisAttrObj.tooltext); } else { toolTipController.disableToolTip(textElement); } // Setting the extreme labels helps the limit updater to draw its UI at those labels in // dragable charts if (value === max) { extremeLabels.lastLabel.graphic = textElement; } else if (value === min) { extremeLabels.firstLabel.graphic = textElement; } map.push(mapId); } } diff = (0, _difference2['default'])(axisConfig.prevIntervalArr, map); for (i = 0, ln = diff.length; i < ln; i++) { removingElement = axis.getGraphicalElement(diff[i]); removingElement && axis.removeGraphicalElement(removingElement); } axisConfig.prevIntervalArr = map; }, _parseLabel = function _parseLabel() { var axis = this, axisConfig = axis.config, canvasDimensions = axis.getLinkedItem('canvas').getEffectiveDimensions(), axisDimension = axisConfig.axisDimention, chart = axis.getFromEnv('chart'), chartConfig = chart.config, axisRange = axisConfig.axisRange, isOpposit = axisConfig.isOpposit, labels = axisConfig.labels, axisComponents = axis.components, labelStore = axisComponents.labels, style = labels.style, smartLabel = chart.getFromEnv('smartLabel'), i, ln, isVertical = axisConfig.isVertical, max = axisRange.max, min = axisRange.min, numberFormatter = axis.getFromEnv('number-formatter'), canvasTop = canvasDimensions.top, canvasLeft = canvasDimensions.left, canvasBottom = canvasTop + canvasDimensions.height, canvasRight = canvasLeft + canvasDimensions.width, axisPadding = axisConfig.labelPadding, extremeLabels = axisConfig.extremeLabels, axisStartPosition = isVertical ? axisDimension.x : axisDimension.y, axisEndPosition = axisDimension.opposite, labelRotation, labelLineHeight, avalW, avalH, axisValueMaxH = axisConfig.labelMaxH, axisValueMaxW = axisConfig.labelMaxW, tempStep, tickInterval = axisRange.tickInterval, intervalWidth = Math.abs(axis.getPixel(min, queryOptions) - axis.getPixel(min + tickInterval, queryOptions)), numberFormatterFn, axisAttrObjCommon, axisAttrObj, // this keeps a mapping between the array to be drawn and the ticks array tickMap = [], ticks = axisConfig.ticks, counter = 0, isReverse = axisConfig.isReverse, leftSpace, rightSpace, value, smartLabelConf, showZeroPlaneValue = (0, _lib.pluckNumber)(axis.getFromEnv('chart-attrib').showzeroplanevalue), checkLimit = true, zeroInPx, limit = axis.getLimit(), intervalArr; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle({ fontSize: style.fontSize, fontFamily: style.fontFamily, lineHeight: style.lineHeight, fontWeight: style.fontWeight }); labelLineHeight = style.lineHeight; if (labelLineHeight) { if (labelLineHeight.indexOf('px') !== -1) { labelLineHeight = parseFloat(labelLineHeight.replace('px', '')); } } if (showZeroPlaneValue === 0) { checkLimit = false; } // checking if labels are to be drawn user can decide or can be decided by axis placeAxis function if (axisConfig.labels.isDraw) { // check with the drawAxisNameOpposit to finally decide the name should be draw on which side if (axisConfig.drawLabelsOpposit) { isOpposit = !isOpposit; axisStartPosition = axisEndPosition; } // Common style attributes axisAttrObjCommon = { fill: style.color, 'line-height': labelLineHeight, 'font-size': style.fontSize, 'opacity': 1 }; labelRotation = axisConfig.labels.rotation; // check if label overlap if (isVertical) { // check for overlap if there is any make the step such that no overlap happens if (axisConfig.labelMaxH > intervalWidth && !axisConfig.tickValues) { tempStep = Math.ceil(axisConfig.labelMaxH / intervalWidth); } // Fix the alignment axisAttrObjCommon['text-anchor'] = isOpposit ? _lib.POSITION_START : _lib.POSITION_END; } else { // check for overlap if there is any make the step such that no overlap happens if (axisConfig.labelMaxW > intervalWidth && !axisConfig.tickValues) { tempStep = Math.ceil(axisConfig.labelMaxW / intervalWidth); } // Fix the alignment if (labelRotation) { axisAttrObjCommon['text-anchor'] = isOpposit ? _lib.POSITION_START : _lib.POSITION_END; axisAttrObjCommon['vertical-align'] = 'middle'; } else { axisAttrObjCommon['vertical-align'] = isOpposit ? _lib.POSITION_BOTTOM : _lib.POSITION_TOP; } leftSpace = canvasLeft; rightSpace = chartConfig.width - canvasRight; } if (tempStep > axisConfig.labels.step) { axisConfig.labels.step = tempStep; } if (axisConfig.numberFormatterFn) { numberFormatterFn = numberFormatter[axisConfig.numberFormatterFn]; } else if (axisConfig.isPercent) { numberFormatterFn = numberFormatter.percentValue; } else if (isVertical) { numberFormatterFn = numberFormatter.yAxis; } else { numberFormatterFn = numberFormatter.xAxis; } extremeLabels.firstLabel = {}; extremeLabels.lastLabel = {}; intervalArr = ticks.filter(function (tick, idx, arr) { if (tick === 0 && !axisConfig.showZeroPlaneValue) { // if zero plane value is not to be shown if (!checkLimit || checkLimit && !(limit.max === tick || limit.min === tick)) { return false; } else { tickMap[counter++] = idx; return true; } } else if (!isVertical && idx !== arr.length - 1 && axis.getPixel(tick, queryOptions) + axisConfig.labelMaxW > canvasRight) { // checking if the label overlap with the last label return false; } else if (idx % axisConfig.labels.step === 0) { // Include only every step-th tick... tickMap[counter++] = idx; return true; } else if (axisConfig.labels.drawLimitVal && (idx === 0 || idx === arr.length - 1)) { // ...unless limits must be shown, in which case include the limits,... tickMap[counter++] = idx; return true; } else { // ... otherwise exclude the ticks return false; } }); if (axisConfig.isZeroTickForced && intervalArr.indexOf(0) !== -1) { var valueInPx = void 0; counter = 0; tickMap = []; zeroInPx = axis.getPixel(0); intervalArr = intervalArr.filter(function (tick, index, arr) { valueInPx = axis.getPixel(tick); if (arr[index + 1] === 0 || arr[index - 1] === 0) { if (isVertical) { if (valueInPx + axisValueMaxH >= zeroInPx && zeroInPx >= valueInPx - axisValueMaxH) return false;else { tickMap[counter++] = index; return true; } } else if (valueInPx + axisValueMaxW >= zeroInPx && zeroInPx >= valueInPx - axisValueMaxW) return false;else { tickMap[counter++] = index; return true; } } else { tickMap[counter++] = index; return true; } }); } avalW = (isVertical ? axisValueMaxW : intervalWidth / 2) * axisConfig.labels.step; avalH = isVertical ? intervalWidth / 2 : axisValueMaxH; axisComponents.labelIndexArr = tickMap.slice(); // main loop where the drawing starts for (i = 0, ln = intervalArr.length; i < ln; i += 1) { value = intervalArr[i]; labelStore[tickMap[i]] = labelStore[tickMap[i]] || { config: { props: { label: {} } } }; axisAttrObj = Object.assign({}, axisAttrObjCommon); smartLabelConf = _lib.UNDEF; if (!axisConfig.labels.drawNormalVal && !(value === min || value === max)) { // if values are not limit value and label drawing is off other // than limit axisAttrObj.text = ''; } else if (!axisConfig.labels.drawLimitVal && (value === min || value === max)) { // if value are limit value but limit value are not mean to be drawn axisAttrObj.text = ''; } else if (value === min && axisConfig.lowerLimitDisplay && axisConfig.labels.drawLimitVal) { smartLabelConf = smartLabel.getSmartText(axisConfig.lowerLimitDisplay, avalW, avalH + labelLineHeight / 2); axisAttrObj.text = smartLabelConf.text; axisAttrObj.tooltext = smartLabelConf.tooltext; } else if (value === max && axisConfig.upperLimitDisplay && axisConfig.labels.drawLimitVal) { smartLabelConf = smartLabel.getSmartText(axisConfig.upperLimitDisplay, avalW, avalH + labelLineHeight / 2); axisAttrObj.text = smartLabelConf.text; axisAttrObj.tooltext = smartLabelConf.tooltext; } else { axisAttrObj.text = '' + numberFormatterFn.call(numberFormatter, value, axisConfig.axisIndex); smartLabelConf = smartLabel.getOriSize(axisAttrObj.text); } // make the attribute ready to use if (isVertical) { axisAttrObj.x = isOpposit ? (axisStartPosition || canvasRight) + axisPadding : (axisStartPosition || canvasLeft) - axisPadding; axisAttrObj.y = axis.getPixel(value, queryOptions); if ((isReverse && value === min && axisConfig.lowerLimitDisplay || !isReverse && value === max && axisConfig.upperLimitDisplay) && smartLabelConf && smartLabelConf.height > labelLineHeight) { axisAttrObj['vertical-align'] = _lib.POSITION_BOTTOM; } if ((isReverse && value === max && axisConfig.upperLimitDisplay || !isReverse && value === min && axisConfig.lowerLimitDisplay) && smartLabelConf && smartLabelConf.height > labelLineHeight) { axisAttrObj['vertical-align'] = _lib.POSITION_TOP; } if (axisConfig.placeValuesInside) { axisAttrObj['text-anchor'] = isOpposit ? _lib.POSITION_END : _lib.POSITION_START; } } else { axisAttrObj.x = axis.getPixel(value, queryOptions); axisAttrObj.y = isOpposit ? (axisStartPosition || canvasTop) - axisPadding : (axisStartPosition || canvasBottom) + axisPadding; if ((!isReverse && value === min || isReverse && value === max) && smartLabelConf && smartLabelConf.width > leftSpace * 2) { axisAttrObj['text-anchor'] = _lib.POSITION_START; } if ((!isReverse && value === max || isReverse && value === min) && smartLabelConf && smartLabelConf.width > rightSpace * 2) { axisAttrObj['text-anchor'] = _lib.POSITION_END; } if (axisConfig.placeValuesInside) { axisAttrObj['vertical-align'] = isOpposit ? _lib.POSITION_TOP : _lib.POSITION_BOTTOM; } else { axisAttrObj['vertical-align'] = isOpposit ? _lib.POSITION_BOTTOM : _lib.POSITION_TOP; } } // If labels shift is applicable (Specially for 3D) then apply the changes if (labels.shiftX) { axisAttrObj.x += labels.shiftX; } if (labels.shiftY) { axisAttrObj.y += labels.shiftY; } axisAttrObj.transform = (0, _lib.getSuggestiveRotation)(labelRotation, axisAttrObj.x, axisAttrObj.y); labelStore[tickMap[i]].config.props.label.attr = axisAttrObj; } } }, setTickValues = function setTickValues(categories) { var len = categories && categories.length, axisConfig = this.config, startPad = axisConfig.startPad || 0, index, chart = this.getFromEnv('chart'), tickObj, countCat = 0, tickValues = axisConfig.tickValues = {}, tickValue = tickValues.tickValue = [], vline = tickValues.vline = [], tickIdMap = tickValues.tickIdMap = {}, endPad = axisConfig.endPad || 0; axisConfig.hasCategory = 1; for (index = 0; index < len; index += 1) { tickObj = (0, _lib.extend2)({}, categories[index]); if (!tickObj.vline) { // parse and store the category ID if (tickObj.id) { tickIdMap[tickObj.id.toLowerCase()] = { tickObj: tickObj, index: countCat }; } // parse and store style if (axisConfig.mapTickValuesById && tickObj.id || !axisConfig.mapTickValuesById) { extractStyleInfo(tickObj, chart); tickValue.push(tickObj); tickValue[countCat].label = (0, _lib.parseUnsafeString)(tickValue[countCat].label); countCat += 1; } } else { tickObj.startIndex = tickValue.length - 1; vline.push(tickObj); } } // oriCatLen is the number of categories in the user given category array excluding the vlines axisConfig.oriCatLen = countCat; this._setAxisRange({ // max is the total number of categories added with the axis padding max: Number((0, _lib.toPrecision)(countCat - 1 + endPad, 10)), // min is the axis padding subtracted the minimum possible number of // categories, i.e. 0 min: Number((0, _lib.toPrecision)(0 - startPad, 10)), tickInterval: Number((0, _lib.toPrecision)(1, 10)) }); }, /** * Shift the labels by the x and y amounts given * @param {number} x The amount of x shift * @param {number} y The amount of y shift */ shiftLabels = function shiftLabels(x, y) { var axis = this, axisConfig = axis.config, labels = axisConfig.labels; // This will help to shift the labels accordingly labels.shiftX = x; labels.shiftY = y; }, // for cartesian and polar category axis _createContainer = function _createContainer() { var axis = this, axisConfig = axis.config, isVertical = axisConfig.isVertical, chart = axis.getLinkedParent(), childContainers = chart.getChildContainer(), axisBottom = childContainers.axisBottomGroup, axisTop = childContainers.axisTopGroup, translation = -axis.getTranslation(), translateString = isVertical ? 'T0,' + translation : 'T' + translation + ',0', axisLineGroup = void 0, axisNameGroup = void 0, axisTrendGroupTop = void 0, axisLabelGroup = void 0, axisLabelGroupTop = void 0; // creating the axis elements group unique throughout the charts // axisNameGroup hold the name container axisNameGroup = axis.createContainer('axisNameGroup', { name: 'dataset-Name-group' }, axisBottom); // axisLineGroup hold the axis line element axisLineGroup = axis.createContainer('axisLineGroup', { name: 'axis-Line-group' }, axisTop); // axisTrendGroupTop hold trendContainer top of the dataset axisTrendGroupTop = axis.createContainer('axisTrendGroupTop', { name: 'dataset-Trend-group-top' }, axisTop); // axisLabelGroup hold the label container axisLabelGroup = axis.createContainer('axisLabelGroup', { name: 'dataset-Label-group' }, axisBottom); // axisLabelGroup hold the label container axisLabelGroupTop = axis.createContainer('axisLabelGroupTop', { name: 'dataset-Label-group' }, axisTop); // creating the container group for every axis there will be // note : if new container added add it to hide and show // contains all the axis labels // axisConfig.scrollerContainer = axis.createGroup('scrollerContainer', { // name: 'scroller-container' // }, axisLineGroup, 'scroller'); if (!axis.getGraphicalElement('scrollerContainer')) { axis.addGraphicalElement('scrollerContainer', axis.createGroup('scrollerContainer', { name: 'scroller-container' }, axisLineGroup, 'scroller')); } axisConfig.axisContainer = axis.createGroup('axisContainer', { name: 'dataset-axis', transform: translateString }, axisLabelGroup); axisConfig.axisLabelContainerTop = axis.createGroup('axisLabelContainerTop', { name: 'dataset-top-label', transform: translateString }, axisLabelGroupTop); axisConfig.axisAxisLineContainer = axis.createGroup('axisAxisLineContainer', { name: 'axis-line-tick' }, axisLineGroup); // axisConfig.vlineLabelContainer = axis.createGroup('vlineLabelContainer', { // name: 'axis-vline-label' // }, axisLineGroup); // contain trend label elements axisConfig.axisTrendLabelContainer = axis.createGroup('axisTrendLabelContainer', { name: 'dataset-axis-trend-label' }, axisTrendGroupTop); axisConfig.axisNameContainer = axis.createGroup('axisNameContainer', { name: 'dataset-axis-name' }, axisNameGroup); axisConfig.axisAxisLineContainerBottom = axis.createGroup('axisAxisLineContainerBottom', { name: 'axis-line-tick-bottom' }, axisBottom); }, // for category and polar category /** * Function to shift the axis drawing * @param {number} startPad start padding in values * @param {number} endPad end Padding in values */ setAxisPadding = function setAxisPadding() { var startPad = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var endPad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var axis = this, axisConfig = axis.config, scale = axis.getScale(), _scale$getDomain = scale.getDomain(), min = _scale$getDomain[0], max = _scale$getDomain[1], diff; // If only a single category is to be represented on the axis, and the start/end padding value // is given as zero, align it centrally by forcing a value padding of 0.5 to the start/end of // the axis. if (axisConfig.oriCatLen === 1) { if (startPad === 0) { startPad = 0.5; } if (endPad === 0) { endPad = 0.5; } } diff = startPad - axisConfig.startPad; axisConfig.startPad = Math.max(axisConfig.startPad, startPad); axisConfig.endPad = Math.max(axisConfig.endPad, endPad); if (diff > 0) { axisConfig.setPadding = true; axis._setAxisRange({ min: min - diff, max: max + diff }); } if (!axisConfig.tickValues) { if (axisConfig.originalMax && axisConfig.originalMin) { axis.setDataLimit(axisConfig.originalMax, axisConfig.originalMin); } } }, getLabel = function getLabel(tickId) { var axis = this, axisConfig = axis.config, tickObj = axisConfig.tickValues && axisConfig.tickValues.tickValue[tickId], macroIndices = [3], parserConfig = {}; if (tickObj && tickObj.tooltext) { parserConfig.label = tickObj.label; tickObj.tooltext = (0, _lib.parseTooltext)(tickObj.tooltext, macroIndices, parserConfig); } return { label: tickObj && (tickObj.oriLabel || tickObj.label), tooltext: tickObj && tickObj.tooltext }; }; exports.setAxisDimention = setAxisDimention; exports.setDataLimit = setDataLimit; exports.getTrendLineLimits = getTrendLineLimits; exports.getPixel = getPixel; exports._drawLabel = _drawLabel; exports.setTickValues = setTickValues; exports.shiftLabels = shiftLabels; exports._createContainer = _createContainer; exports.setAxisPadding = setAxisPadding; exports.getLabel = getLabel; exports.extractStyleInfo = extractStyleInfo; exports._parseLabel = _parseLabel; // setAxisDimention: numeric, category, log, gauge // setDataLimit: numeric, gauge, polar-numeric // getTrendLineLimits: numeric, category, log, gauge, polar-numeric // getPixel: gauge, polar // _drawLabel: numeric, category, gauge // setTickValues: category, polar // shiftLabels: numeric, category, log, polar // _createContainer: numeric, category, log, polar // setAxisPadding: category, numeric, polar // getLabel: category, numeric, polar // extractStyleInfo: numeric /***/ }), /* 387 */ /***/ (function(module, exports, __webpack_require__) { var _contains = /*#__PURE__*/__webpack_require__(388); var _curry2 = /*#__PURE__*/__webpack_require__(199); /** * Finds the set (i.e. no duplicates) of all elements in the first list not * contained in the second list. Objects and Arrays are compared in terms of * value equality, not reference equality. * * @func * @memberOf R * @since v0.1.0 * @category Relation * @sig [*] -> [*] -> [*] * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The elements in `list1` that are not in `list2`. * @see R.differenceWith, R.symmetricDifference, R.symmetricDifferenceWith, R.without * @example * * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] * R.difference([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}] */ var difference = /*#__PURE__*/_curry2(function difference(first, second) { var out = []; var idx = 0; var firstLen = first.length; while (idx < firstLen) { if (!_contains(first[idx], second) && !_contains(first[idx], out)) { out[out.length] = first[idx]; } idx += 1; } return out; }); module.exports = difference; /***/ }), /* 388 */ /***/ (function(module, exports, __webpack_require__) { var _indexOf = /*#__PURE__*/__webpack_require__(389); function _contains(a, list) { return _indexOf(list, a, 0) >= 0; } module.exports = _contains; /***/ }), /* 389 */ /***/ (function(module, exports, __webpack_require__) { var equals = /*#__PURE__*/__webpack_require__(390); function _indexOf(list, a, idx) { var inf, item; // Array.prototype.indexOf doesn't exist below IE9 if (typeof list.indexOf === 'function') { switch (typeof a) { case 'number': if (a === 0) { // manually crawl the list to distinguish between +0 and -0 inf = 1 / a; while (idx < list.length) { item = list[idx]; if (item === 0 && 1 / item === inf) { return idx; } idx += 1; } return -1; } else if (a !== a) { // NaN while (idx < list.length) { item = list[idx]; if (typeof item === 'number' && item !== item) { return idx; } idx += 1; } return -1; } // non-zero numbers can utilise Set return list.indexOf(a, idx); // all these types can utilise Set case 'string': case 'boolean': case 'function': case 'undefined': return list.indexOf(a, idx); case 'object': if (a === null) { // null can utilise Set return list.indexOf(a, idx); } } } // anything else not covered above, defer to R.equals while (idx < list.length) { if (equals(list[idx], a)) { return idx; } idx += 1; } return -1; } module.exports = _indexOf; /***/ }), /* 390 */ /***/ (function(module, exports, __webpack_require__) { var _curry2 = /*#__PURE__*/__webpack_require__(199); var _equals = /*#__PURE__*/__webpack_require__(391); /** * Returns `true` if its arguments are equivalent, `false` otherwise. Handles * cyclical data structures. * * Dispatches symmetrically to the `equals` methods of both arguments, if * present. * * @func * @memberOf R * @since v0.15.0 * @category Relation * @sig a -> b -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * R.equals(1, 1); //=> true * R.equals(1, '1'); //=> false * R.equals([1, 2, 3], [1, 2, 3]); //=> true * * var a = {}; a.v = a; * var b = {}; b.v = b; * R.equals(a, b); //=> true */ var equals = /*#__PURE__*/_curry2(function equals(a, b) { return _equals(a, b, [], []); }); module.exports = equals; /***/ }), /* 391 */ /***/ (function(module, exports, __webpack_require__) { var _arrayFromIterator = /*#__PURE__*/__webpack_require__(392); var _containsWith = /*#__PURE__*/__webpack_require__(385); var _functionName = /*#__PURE__*/__webpack_require__(393); var _has = /*#__PURE__*/__webpack_require__(206); var identical = /*#__PURE__*/__webpack_require__(394); var keys = /*#__PURE__*/__webpack_require__(395); var type = /*#__PURE__*/__webpack_require__(397); /** * private _uniqContentEquals function. * That function is checking equality of 2 iterator contents with 2 assumptions * - iterators lengths are the same * - iterators values are unique * * false-positive result will be returned for comparision of, e.g. * - [1,2,3] and [1,2,3,4] * - [1,1,1] and [1,2,3] * */ function _uniqContentEquals(aIterator, bIterator, stackA, stackB) { var a = _arrayFromIterator(aIterator); var b = _arrayFromIterator(bIterator); function eq(_a, _b) { return _equals(_a, _b, stackA.slice(), stackB.slice()); } // if *a* array contains any element that is not included in *b* return !_containsWith(function (b, aItem) { return !_containsWith(eq, aItem, b); }, b, a); } function _equals(a, b, stackA, stackB) { if (identical(a, b)) { return true; } var typeA = type(a); if (typeA !== type(b)) { return false; } if (a == null || b == null) { return false; } if (typeof a['fantasy-land/equals'] === 'function' || typeof b['fantasy-land/equals'] === 'function') { return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) && typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a); } if (typeof a.equals === 'function' || typeof b.equals === 'function') { return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a); } switch (typeA) { case 'Arguments': case 'Array': case 'Object': if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') { return a === b; } break; case 'Boolean': case 'Number': case 'String': if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) { return false; } break; case 'Date': if (!identical(a.valueOf(), b.valueOf())) { return false; } break; case 'Error': return a.name === b.name && a.message === b.message; case 'RegExp': if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) { return false; } break; } var idx = stackA.length - 1; while (idx >= 0) { if (stackA[idx] === a) { return stackB[idx] === b; } idx -= 1; } switch (typeA) { case 'Map': if (a.size !== b.size) { return false; } return _uniqContentEquals(a.entries(), b.entries(), stackA.concat([a]), stackB.concat([b])); case 'Set': if (a.size !== b.size) { return false; } return _uniqContentEquals(a.values(), b.values(), stackA.concat([a]), stackB.concat([b])); case 'Arguments': case 'Array': case 'Object': case 'Boolean': case 'Number': case 'String': case 'Date': case 'Error': case 'RegExp': case 'Int8Array': case 'Uint8Array': case 'Uint8ClampedArray': case 'Int16Array': case 'Uint16Array': case 'Int32Array': case 'Uint32Array': case 'Float32Array': case 'Float64Array': case 'ArrayBuffer': break; default: // Values of other types are only equal if identical. return false; } var keysA = keys(a); if (keysA.length !== keys(b).length) { return false; } var extendedStackA = stackA.concat([a]); var extendedStackB = stackB.concat([b]); idx = keysA.length - 1; while (idx >= 0) { var key = keysA[idx]; if (!(_has(key, b) && _equals(b[key], a[key], extendedStackA, extendedStackB))) { return false; } idx -= 1; } return true; } module.exports = _equals; /***/ }), /* 392 */ /***/ (function(module, exports) { function _arrayFromIterator(iter) { var list = []; var next; while (!(next = iter.next()).done) { list.push(next.value); } return list; } module.exports = _arrayFromIterator; /***/ }), /* 393 */ /***/ (function(module, exports) { function _functionName(f) { // String(x => x) evaluates to "x => x", so the pattern may not match. var match = String(f).match(/^function (\w*)/); return match == null ? '' : match[1]; } module.exports = _functionName; /***/ }), /* 394 */ /***/ (function(module, exports, __webpack_require__) { var _curry2 = /*#__PURE__*/__webpack_require__(199); /** * Returns true if its arguments are identical, false otherwise. Values are * identical if they reference the same memory. `NaN` is identical to `NaN`; * `0` and `-0` are not identical. * * @func * @memberOf R * @since v0.15.0 * @category Relation * @sig a -> a -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * var o = {}; * R.identical(o, o); //=> true * R.identical(1, 1); //=> true * R.identical(1, '1'); //=> false * R.identical([], []); //=> false * R.identical(0, -0); //=> false * R.identical(NaN, NaN); //=> true */ var identical = /*#__PURE__*/_curry2(function identical(a, b) { // SameValue algorithm if (a === b) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return a !== 0 || 1 / a === 1 / b; } else { // Step 6.a: NaN == NaN return a !== a && b !== b; } }); module.exports = identical; /***/ }), /* 395 */ /***/ (function(module, exports, __webpack_require__) { var _curry1 = /*#__PURE__*/__webpack_require__(200); var _has = /*#__PURE__*/__webpack_require__(206); var _isArguments = /*#__PURE__*/__webpack_require__(396); // cover IE < 9 keys issues var hasEnumBug = ! /*#__PURE__*/{ toString: null }.propertyIsEnumerable('toString'); var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // Safari bug var hasArgsEnumBug = /*#__PURE__*/function () { 'use strict'; return arguments.propertyIsEnumerable('length'); }(); var contains = function contains(list, item) { var idx = 0; while (idx < list.length) { if (list[idx] === item) { return true; } idx += 1; } return false; }; /** * Returns a list containing the names of all the enumerable own properties of * the supplied object. * Note that the order of the output array is not guaranteed to be consistent * across different JS platforms. * * @func * @memberOf R * @since v0.1.0 * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties. * @see R.keysIn, R.values * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ var _keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? function keys(obj) { return Object(obj) !== obj ? [] : Object.keys(obj); } : function keys(obj) { if (Object(obj) !== obj) { return []; } var prop, nIdx; var ks = []; var checkArgsLength = hasArgsEnumBug && _isArguments(obj); for (prop in obj) { if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { ks[ks.length] = prop; } } if (hasEnumBug) { nIdx = nonEnumerableProps.length - 1; while (nIdx >= 0) { prop = nonEnumerableProps[nIdx]; if (_has(prop, obj) && !contains(ks, prop)) { ks[ks.length] = prop; } nIdx -= 1; } } return ks; }; var keys = /*#__PURE__*/_curry1(_keys); module.exports = keys; /***/ }), /* 396 */ /***/ (function(module, exports, __webpack_require__) { var _has = /*#__PURE__*/__webpack_require__(206); var toString = Object.prototype.toString; var _isArguments = function () { return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } : function _isArguments(x) { return _has('callee', x); }; }; module.exports = _isArguments; /***/ }), /* 397 */ /***/ (function(module, exports, __webpack_require__) { var _curry1 = /*#__PURE__*/__webpack_require__(200); /** * Gives a single-word string description of the (native) type of a value, * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not * attempt to distinguish user Object types any further, reporting them all as * 'Object'. * * @func * @memberOf R * @since v0.8.0 * @category Type * @sig (* -> {*}) -> String * @param {*} val The value to test * @return {String} * @example * * R.type({}); //=> "Object" * R.type(1); //=> "Number" * R.type(false); //=> "Boolean" * R.type('s'); //=> "String" * R.type(null); //=> "Null" * R.type([]); //=> "Array" * R.type(/[A-z]/); //=> "RegExp" * R.type(() => {}); //=> "Function" * R.type(undefined); //=> "Undefined" */ var type = /*#__PURE__*/_curry1(function type(val) { return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); }); module.exports = type; /***/ }), /* 398 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /* eslint require-jsdoc: 'error', valid-jsdoc: 'error' */ var START = 0, STEP = 1; /** * The function creates a AP series with given start, stop and step values, * if start and step is not given it takes start as 0 and step as 1 by default * @param {number} params numbers * @return {Array} array containig AP series starting from start but not ending at stop */ var range = function range() { var start = void 0, stop = void 0, step = void 0, len = void 0, i = void 0, output = []; if (arguments.length > 2) { start = arguments.length <= 0 ? undefined : arguments[0]; stop = arguments.length <= 1 ? undefined : arguments[1]; step = arguments.length <= 2 ? undefined : arguments[2]; } else if (arguments.length === 1) { start = START; stop = arguments.length <= 0 ? undefined : arguments[0]; step = STEP; } else { start = arguments.length <= 0 ? undefined : arguments[0]; stop = arguments.length <= 1 ? undefined : arguments[1]; step = STEP; } len = Math.floor(Math.max(0, Math.ceil((stop - start) / step))); if (isFinite(len)) { for (i = 0; i < len; ++i) { output.push(step * i + start); } } return output; }; exports["default"] = range; /***/ }), /* 399 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _continuous = __webpack_require__(400); var _continuous2 = _interopRequireDefault(_continuous); var _ticks2 = __webpack_require__(416); var _ticks3 = _interopRequireDefault(_ticks2); var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); var _ticks4 = __webpack_require__(417); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: 'error' */ /** * Scale linear class */ var ScaleLinear = function (_ScaleContinuous) { _inherits(ScaleLinear, _ScaleContinuous); /** * this constructs a linear scale with linear deinterpolator and a numeric interpolator */ function ScaleLinear() { _classCallCheck(this, ScaleLinear); return _possibleConstructorReturn(this, _ScaleContinuous.call(this, _continuous.deInterpolateLinear, _number2['default'])); } /** * Returns approximately count uniformly spaced values from the scale's domain. Note * that the specified count is only a hint, the scale may return more or fewer values * than count depending on the domain. * * @param {number} [count=7] The approoximate number of ticks to generate. Defaults to 7. * @return {Array} An array of generated tick values */ ScaleLinear.prototype.ticks = function ticks() { var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 7; var domain = this.getDomain(); return this.majorTicks = (0, _ticks3['default'])(domain[0], domain[domain.length - 1], count); }; ScaleLinear.prototype.tickFormat = function tickFormat(count, specifier) { return (0, _ticks4.tickFormat)(this.getDomain(), count, specifier, this._localeConverter); }; /** * Extends the domain so that it starts and ends on nice, round values. The optional count * parameter allows greater control over the step size. * Note: Nicing the domain ony affects the current domain. The scale must be re-niced after * setting a new domain, if required. * * @param {number} [count=7] Optional argument which allows control over the step size used to * extend the bound, guaranteeing that the returned ticks will exactly * cover the domain. * @return {Object} An instance of the scale. */ ScaleLinear.prototype.nice = function nice() { var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 7; var domain = this.getDomain(), startIndex = 0, endIndex = domain.length - 1, start = domain[startIndex], stop = domain[endIndex], step = void 0; if (stop < start) { step = start; start = stop; stop = step; step = startIndex; startIndex = endIndex; endIndex = step; } step = (0, _ticks2.tickIncrement)(start, stop, count); if (step > 0) { start = Math.floor(start / step) * step; stop = Math.ceil(stop / step) * step; step = (0, _ticks2.tickIncrement)(start, stop, count); } else if (step < 0) { start = Math.ceil(start * step) / step; stop = Math.floor(stop * step) / step; step = (0, _ticks2.tickIncrement)(start, stop, count); } if (step > 0) { domain[startIndex] = Math.floor(start / step) * step; domain[endIndex] = Math.ceil(stop / step) * step; this.setDomain(domain); } else if (step < 0) { domain[startIndex] = Math.ceil(start * step) / step; domain[endIndex] = Math.floor(stop * step) / step; this.setDomain(domain); } return this; }; /** * creates a new copy of the scale with configiration of the current scale * @return {Object} instance of new scale */ ScaleLinear.prototype.copy = function copy() { return (0, _continuous.copyScale)(this, new ScaleLinear()); }; /** * Api to create minor ticks * @param {Number} numMinor is the no of minor ticks will be craeted between two major ticks * @param {Array} majorTicks a set of major ticks if ticks has not been created from scale * @returns {Array} of minor ticks */ ScaleLinear.prototype.minorTicks = function minorTicks() { var numMinor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 4; var majorTicks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.majorTicks || this.ticks(); var ticksLen = majorTicks.length, tickInterval = majorTicks[1] - majorTicks[0], minorTickValues = [], j = void 0, minorTickInterval = void 0, start = void 0, i = void 0; for (i = 0; i < ticksLen - 1; ++i) { start = majorTicks[i]; minorTickInterval = tickInterval / (Number(numMinor) + 1); for (j = 1; j <= numMinor; j += 1) { minorTickValues.push(start + minorTickInterval * j); } } return minorTickValues; }; ScaleLinear.prototype.contextTicks = function contextTicks() { return this.contextTicksArr || []; }; ScaleLinear.prototype.getType = function getType() { return 'linear'; }; return ScaleLinear; }(_continuous2['default']); exports['default'] = ScaleLinear; /***/ }), /* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.bimap = exports.deInterpolateLinear = exports.copyScale = undefined; var _value = __webpack_require__(401); var _value2 = _interopRequireDefault(_value); var _round = __webpack_require__(403); var _round2 = _interopRequireDefault(_round); var _constant = __webpack_require__(402); var _constant2 = _interopRequireDefault(_constant); var _enUS = __webpack_require__(404); var _enUS2 = _interopRequireDefault(_enUS); var _numberConverter = __webpack_require__(405); 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"); } } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var count = 0; var UNIT = [0, 1]; /** *returns a function which when given a value in domain returns the corresponding range * @param {Array} domain array containing the start and end value * @param {Array} range array containing the start and end value * @param {Function} deInterpolate function * @param {Function} reInterpolate function * @return {Function} takes in value and returns the mapped value */ function bimap(domain, range, deInterpolate, reInterpolate) { var deInterpolator, reInterpolator; if (domain[0] > domain[1]) { deInterpolator = deInterpolate(domain[1], domain[0]); reInterpolator = reInterpolate(range[1], range[0]); } else { deInterpolator = deInterpolate(domain[0], domain[1]); reInterpolator = reInterpolate(range[0], range[1]); } return function (value) { return reInterpolator(deInterpolator(value)); }; } /** * copy the domain, range and interpolator of source to targe * @param {Object} sourceScale instance of scale * @param {Object} targetScale instance of scale * @return {Object} the target scale */ function copyScale(sourceScale, targetScale) { return targetScale.setInterpolate(sourceScale.getInterpolate()).setClamp(sourceScale.getClamp()).setDomain(sourceScale.getDomain()).setRange(sourceScale.getRange()); } /** * function to return a ratio with respect to the liinterpolatemit * @param {number} min of domain * @param {number} max of domain * @return {Function} that takes in value and return the ratio */ function deInterpolateLinear(min, max) { min = Number(min); max = Number(max); var diff = max - min; if (!diff) { return (0, _constant2['default'])(diff); } return function (value) { return (value - min) / diff; }; } /** * function to return a ratio with respect to the limit and will clamp it to 0 and 1 * if it goes out of range * @param {Function} deInterpolate function * @return {Function} takes a value and return clamped value */ function deInterpolateClamp(deInterpolate) { return function (min, max) { min = Number(min); max = Number(max); var interpolator = deInterpolate(min, max); return function (value) { if (value <= min) { return 0; } else if (value >= max) { return 1; } else { return interpolator(value); } }; }; } /** * function to return a value with respect to the limit and will clamp it to max and min * if it goes out of range * @param {Function} reInterpolate function * @return {Function} takes in ratio and returns clamped value */ function reInterpolateClamp(reInterpolate) { return function (min, max) { min = Number(min); max = Number(max); var interpolator = reInterpolate(min, max); return function (ratio) { if (ratio <= 0) { return min; } else if (ratio >= 1) { return max; } else { return interpolator(ratio); } }; }; } /** * continous scale class */ var ScaleContinuous = function () { /** * constructs the class with * @param {Function} deInterpolate deinterpolate(a,b)(x) takes a domain value x in [a,b] and returns * corresponding value t in [0,1] * @param {Function} reInterpolate reinterpolate(a,b)(t) takes a value t in [0,1] and returns * corresponding domain value x in [a,b] */ function ScaleContinuous(deInterpolate, reInterpolate) { _classCallCheck(this, ScaleContinuous); this.domain = UNIT; this.range = UNIT; this.deInterpolate = deInterpolate; this.reInterpolate = reInterpolate; this.interpolate = _value2['default']; this.clamp = false; this.input = null; this.output = null; this.locale = _enUS2['default']; this._localeConverter = new _numberConverter.NumberConverter(_enUS2['default']); this._rescale(); this._id = 'scale_' + count++; } /** * when called it informs the scale that it needs to update its mappiing function * @return {Object} instnace of */ ScaleContinuous.prototype._rescale = function _rescale() { this.input = null; this.output = null; return this; }; /** * sets the domain * @param {Array} inputArr is the input array contianig the domian * @return {Object} instance of scale */ ScaleContinuous.prototype.setDomain = function setDomain() { var inputArr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UNIT; this.domain = inputArr.map(Number); return this._rescale(); }; /** * returns the currnet domain * @return {Array} domain array */ ScaleContinuous.prototype.getDomain = function getDomain() { return this.domain.slice(); }; /** * sets the range * @param {Array} inputArr is the input array contianig the range * @return {Object} instance of scale */ ScaleContinuous.prototype.setRange = function setRange() { var inputArr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UNIT; this.range = inputArr.slice(); return this._rescale(); }; /** * returns the currnet range * @return {Array} range array */ ScaleContinuous.prototype.getRange = function getRange() { return this.range.slice(); }; /** * sets the inpterpolate function * @param {Function} interpolate function * @return {Object} instance of scale */ ScaleContinuous.prototype.setInterpolate = function setInterpolate() { var interpolate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _value2['default']; this.interpolate = interpolate; return this._rescale(); }; /** * get the interpolate function * @return {Function} interpolate function */ ScaleContinuous.prototype.getInterpolate = function getInterpolate() { return this.interpolate; }; /** * Function to set if the value returned will be clamped to the domain or range * @param {boolean} clamp is the flag to check wether to clamp the value to the given range * @return {Object} instance of scale */ ScaleContinuous.prototype.setClamp = function setClamp() { var clamp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; this.clamp = !!clamp; return this._rescale(); }; /** * returns the clamping value * @return {boolean} clamp flag value */ ScaleContinuous.prototype.getClamp = function getClamp() { return this.clamp; }; /** * sets the new range and sets the interpolate function as round interpolate * @param {Array} inputArr of range * @return {Object} instance of scale */ ScaleContinuous.prototype.rangeRound = function rangeRound() { var inputArr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UNIT; this.range = inputArr.slice(); this.interpolate = _round2['default']; return this._rescale(); }; /** * Function to return the range value with respect to domain value * @param {number} domainValue is a domain value * @return {number} range value */ ScaleContinuous.prototype.getRangeValue = function getRangeValue(domainValue) { domainValue = domainValue !== null ? domainValue : undefined; var clamp = this.getClamp(), deInterpolate = clamp ? deInterpolateClamp(this.deInterpolate) : this.deInterpolate; if (!this.output) { this.output = bimap(this.getDomain(), this.getRange(), deInterpolate, this.interpolate); } return this.output(Number(domainValue)); }; /** * Function to return the domain value with respect to range value * @param {number} rangeValue is the pixel value * @return {number} domain value */ ScaleContinuous.prototype.getDomainValue = function getDomainValue(rangeValue) { var clamp = this.getClamp(), reInterpolate = clamp ? reInterpolateClamp(this.reInterpolate) : this.reInterpolate; if (!this.input) { this.input = bimap(this.getRange(), this.getDomain(), deInterpolateLinear, reInterpolate); } return this.input(Number(rangeValue)); }; ScaleContinuous.prototype.setLocale = function setLocale() { var locale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _enUS2['default']; this.locale = locale; this._localeConverter = new _numberConverter.NumberConverter(locale); return this; }; ScaleContinuous.prototype.getLocale = function getLocale() { return this.locale; }; ScaleContinuous.prototype.getId = function getId() { return this._id; }; return ScaleContinuous; }(); exports.copyScale = copyScale; exports.deInterpolateLinear = deInterpolateLinear; exports.bimap = bimap; exports['default'] = ScaleContinuous; /***/ }), /* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); var _constant = __webpack_require__(402); var _constant2 = _interopRequireDefault(_constant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function isValid(num) { if (num === null || typeof num === 'undefined') { return false; } return true; } function interpolateValue(from, to) { var interpolator = _number2['default']; if (!isValid(to) || !isValid(from) || typeof to === 'boolean') { return (0, _constant2['default'])(to); } return interpolator(from, to); } exports['default'] = interpolateValue; /***/ }), /* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var constant = function constant(x) { return function () { return x; }; }; exports["default"] = constant; /***/ }), /* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; function interpolateRound(min, max) { min = Number(min); max = Number(max); var diff = max - min; return function (ratio) { return Math.round(diff * ratio + min); }; } exports["default"] = interpolateRound; /***/ }), /* 404 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var enUS = { decimal: '.', thousands: ',', grouping: [3], prefix: '$', suffix: '' }; exports['default'] = enUS; /***/ }), /* 405 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.NumberConverter = undefined; var _enUS = __webpack_require__(404); var _enUS2 = _interopRequireDefault(_enUS); var _exponent = __webpack_require__(406); var _exponent2 = _interopRequireDefault(_exponent); var _formatter = __webpack_require__(408); var _formatter2 = _interopRequireDefault(_formatter); var _formatGroup = __webpack_require__(414); var _formatGroup2 = _interopRequireDefault(_formatGroup); var _formatNumerals = __webpack_require__(415); var _formatNumerals2 = _interopRequireDefault(_formatNumerals); var _formatSpecifier = __webpack_require__(409); var _formatSpecifier2 = _interopRequireDefault(_formatSpecifier); var _lib = __webpack_require__(125); 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 identity = function identity(x) { return x; }; var NumberConverter = function () { function NumberConverter(locale) { _classCallCheck(this, NumberConverter); this.localeInfo = { group: locale.grouping && locale.thousands ? (0, _formatGroup2['default'])(locale.grouping, locale.thousands) : identity, prefix: locale.prefix, suffix: locale.suffix, decimal: locale.decimal, numerals: locale.numerals ? (0, _formatNumerals2['default'])(locale.numerals) : identity, percent: locale.percent || '%', prefixes: locale.prefixes || ['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] }; } NumberConverter.prototype.formatter = function formatter(specifier) { return new _formatter2['default'](specifier, this.localeInfo); }; NumberConverter.prototype.formatPrefix = function formatPrefix(specifier, value) { specifier = new _formatSpecifier2['default'](specifier); specifier.type = 'f'; var prefix = this.localeInfo.prefix, suffix = this.localeInfo.suffix, localLocaleInfo = (0, _lib.extend2)((0, _lib.extend2)({}, this.localeInfo), { prefix: '', suffix: '' }), f = new _formatter2['default'](specifier, localLocaleInfo), e = Math.max(-8, Math.min(8, Math.floor((0, _exponent2['default'])(value) / 3))) * 3, k = Math.pow(10, -e), siPrefix = this.localeInfo.prefixes[8 + e / 3]; return { format: function format(x) { return prefix + f.format(k * x) + siPrefix + suffix; }, setCustomPrefix: function setCustomPrefix(s) { f.setCustomPrefix(s);return this; }, getCustomPrefix: function getCustomPrefix(s) { return f.getCustomPrefix(s); }, setCustomSuffix: function setCustomSuffix(s) { f.setCustomSuffix(s);return this; }, getCustomSuffix: function getCustomSuffix(s) { return f.getCustomSuffix(s); } }; }; return NumberConverter; }(); exports.NumberConverter = NumberConverter; exports['default'] = new NumberConverter(_enUS2['default']); /***/ }), /* 406 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _formatDecimal = __webpack_require__(407); var _formatDecimal2 = _interopRequireDefault(_formatDecimal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var exponent = function exponent(x) { x = (0, _formatDecimal2['default'])(Math.abs(x)); return x ? x[1] : NaN; }; exports['default'] = exponent; /***/ }), /* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * Computes the decimal coefficient and exponent of a number considering the given, * optional, significant digits. * * @example * formatDecimal(8.74) // ['874', 0] * * @param {number} num A positive integer * @param {number} significantDigits The number of significant digits (between 1 and 21) * @returns {Array} The computed coefficient and exponent */ var formatDecimal = function formatDecimal(num, significantDigits) { var i = void 0, coefficient = void 0; num = significantDigits ? num.toExponential(significantDigits - 1) : num.toExponential(); i = num.indexOf('e'); if (i < 0) return null; // NaN, +/-Infinity coefficient = num.slice(0, i); // The string returned by toExponential either has the form \d\.\d+e[-+]\d+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3). return [coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, +num.slice(i + 1)]; }; exports['default'] = formatDecimal; /***/ }), /* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _formatSpecifier = __webpack_require__(409); var _formatSpecifier2 = _interopRequireDefault(_formatSpecifier); var _formatTypes = __webpack_require__(410); var _formatTypes2 = _interopRequireDefault(_formatTypes); var _formatTrim = __webpack_require__(413); var _formatTrim2 = _interopRequireDefault(_formatTrim); var _formatPrefixAuto = __webpack_require__(411); 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 CHAR_CODE_0 = 48, CHAR_CODE_9 = 57, CHAR_CODE_DOT = 46, isNil = function isNil(x) { return typeof x === 'undefined' || x === null; }; var Formatter = function () { function Formatter(specifier, localeInfo) { _classCallCheck(this, Formatter); this.specifier = new _formatSpecifier2['default'](specifier); this.localeInfo = localeInfo; var symbol = this.specifier.symbol; this.fill = this.specifier.fill; this.align = this.specifier.align; this.sign = this.specifier.sign; this.zero = this.specifier.zero; this.width = this.specifier.width; this.comma = this.specifier.comma; this.precision = this.specifier.precision; this.trim = this.specifier.trim; this.type = this.specifier.type; if (this.type === 'n') { // 'n' type is equivalent to ',g' type this.comma = true; this.type = 'g'; } else if (!_formatTypes2['default'][this.type]) { // '' type or any invalid type is equivalent to '.12~g' if (isNil(this.precision)) this.precision = 12; this.trim = true; this.type = 'g'; } // For zero fill, padding goes is between sign and digits if (this.zero || this.fill === '0' && this.align === '=') { this.zero = true; this.fill = '0'; this.align = '='; } // Compute the prefix and suffix (except for SI prefix) if (symbol === '$') { this.prefix = this.localeInfo.prefix; } else if (symbol === '#' && /[boxX]/.test(this.type)) { this.prefix = '0' + this.type.toLowerCase(); } else { this.prefix = ''; } if (symbol === '$') { this.suffix = this.localeInfo.suffix; } else if (/[%p]/.test(this.type)) { this.suffix = this.localeInfo.percent; } else { this.suffix = ''; } // Set the format function for the type this.formatType = _formatTypes2['default'][this.type]; this.mayHaveSuffix = /[defgprs%]/.test(this.type); // Set the default precision if no precision is specified. // If a precision is specified, clamp it to the supported range. // [1, 21] for significant precision. // [0, 20] for fixed precision. if (isNil(this.precision)) { this.precision = 6; } else if (/[gprs]/.test(this.type)) { this.precision = Math.max(1, Math.min(21, this.precision)); } else { this.precision = Math.max(0, Math.min(20, this.precision)); } this.setCustomPrefix(''); this.setCustomSuffix(''); } Formatter.prototype.format = function format(value) { var valuePrefix = this.prefix, valueSuffix = this.suffix, formatType = this.formatType, isValueNegative = void 0, totalLength = void 0, padding = void 0, i = void 0, n = void 0, c = void 0; if (this.type === 'c') { valueSuffix = formatType(value) + valueSuffix; value = ''; } else { value = +value; // Initial formatting isValueNegative = value < 0; value = formatType(Math.abs(value), this.precision); // Trim insignificant zeros if (this.trim) value = (0, _formatTrim2['default'])(value); // If a negative value rounds to zero during formatting, treat it as positive if (isValueNegative && +value === 0) isValueNegative = false; // Decide the prefix and suffix. if (isValueNegative) { valuePrefix = (this.sign === '(' ? this.sign : '-') + valuePrefix; } else if (this.sign === '-' || this.sign === '(') { valuePrefix = '' + valuePrefix; } else { valuePrefix = this.sign + valuePrefix; } if (this.type === 's') { valueSuffix = this.localeInfo.prefixes[8 + _formatPrefixAuto.prefixExponent / 3] + valueSuffix; } else { valueSuffix = '' + valueSuffix; } valueSuffix = valueSuffix + (isValueNegative && this.sign === '(' ? ')' : ''); // Break the formatted value into the integer “value” part that can be // grouped, and fractional or exponential “suffix” part that is not. if (this.mayHaveSuffix) { i = -1; n = value.length; while (++i < n) { c = value.charCodeAt(i); if (c < CHAR_CODE_0 || c > CHAR_CODE_9) { valueSuffix = (c === CHAR_CODE_DOT ? this.localeInfo.decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; value = value.slice(0, i); break; } } } } // If fill is not '0', group first. Then pad. if (this.comma && !this.zero) value = this.localeInfo.group(value, Infinity); // Compute the padding. totalLength = valuePrefix.length + value.length + valueSuffix.length; padding = totalLength < this.width ? new Array(this.width - totalLength + 1).join(this.fill) : ''; // If the fill is '0', pad first. Then group. if (this.comma && this.zero) { value = this.localeInfo.group(padding + value, padding.length ? this.width - valueSuffix.length : Infinity); padding = ''; } // Reconstruct the final output based on the desired alignment. switch (this.align) { case '<': value = valuePrefix + value + valueSuffix + padding; break; case '=': value = valuePrefix + padding + value + valueSuffix; break; case '^': totalLength = padding.length / 2; value = padding.slice(0, totalLength) + valuePrefix + value + valueSuffix + padding.slice(totalLength); break; default: value = padding + valuePrefix + value + valueSuffix; } return this.getCustomPrefix() + this.localeInfo.numerals(value) + this.getCustomSuffix(); }; Formatter.prototype.setCustomPrefix = function setCustomPrefix(prefix) { this._customPrefix = prefix + ''; return this; }; Formatter.prototype.getCustomPrefix = function getCustomPrefix() { return this._customPrefix; }; Formatter.prototype.setCustomSuffix = function setCustomSuffix(suffix) { this._customSuffix = suffix + ''; return this; }; Formatter.prototype.getCustomSuffix = function getCustomSuffix() { return this._customSuffix; }; Formatter.prototype.toString = function toString() { return this.specifier.toString(); }; return Formatter; }(); exports['default'] = Formatter; /***/ }), /* 409 */ /***/ (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"); } } // [[fill]align][sign][symbol][0][width][,][.precision][~][type] var RE = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i, isNil = function isNil(x) { return typeof x === 'undefined' || x === null; }; var FormatSpecifier = function () { function FormatSpecifier(specifier) { _classCallCheck(this, FormatSpecifier); // Silently fail in case of an invalid specifier. // Should probably throw an error here var match = RE.exec(specifier); if (!match) throw new Error('Invalid number format specifier: ' + specifier); this.fill = match[1] || ' '; this.align = match[2] || '>'; this.sign = match[3] || '-'; this.symbol = match[4] || ''; this.zero = Boolean(match[5]); this.width = match[6] && Number(match[6]); this.comma = Boolean(match[7]); this.precision = match[8] && Number(match[8].slice(1)); this.trim = Boolean(match[9]); this.type = match[10] || ''; } FormatSpecifier.prototype.toString = function toString() { return this.fill + this.align + this.sign + this.symbol + (this.zero ? '0' : '') + (isNil(this.width) ? '' : Math.max(1, this.width | 0)) + (this.comma ? ',' : '') + (isNil(this.precision) ? '' : '.' + Math.max(0, this.precision | 0)) + (this.trim ? '~' : '') + this.type; }; return FormatSpecifier; }(); exports['default'] = FormatSpecifier; /***/ }), /* 410 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _formatPrefixAuto = __webpack_require__(411); var _formatPrefixAuto2 = _interopRequireDefault(_formatPrefixAuto); var _formatRounded = __webpack_require__(412); var _formatRounded2 = _interopRequireDefault(_formatRounded); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { '%': function _(x, p) { return (x * 100).toFixed(p); }, 'b': function b(x) { return Math.round(x).toString(2); }, 'c': function c(x) { return x + ''; }, 'd': function d(x) { return Math.round(x).toString(10); }, 'e': function e(x, p) { return x.toExponential(p); }, 'f': function f(x, p) { return x.toFixed(p); }, 'g': function g(x, p) { return x.toPrecision(p); }, 'o': function o(x) { return Math.round(x).toString(8); }, 'p': function p(x, _p) { return (0, _formatRounded2['default'])(x * 100, _p); }, 'r': _formatRounded2['default'], 's': _formatPrefixAuto2['default'], 'X': function X(x) { return Math.round(x).toString(16).toUpperCase(); }, 'x': function x(_x) { return Math.round(_x).toString(16); } }; /***/ }), /* 411 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.prefixExponent = undefined; var _formatDecimal = __webpack_require__(407); var _formatDecimal2 = _interopRequireDefault(_formatDecimal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var prefixExponent = void 0; var formatPrefixAuto = function formatPrefixAuto(x, p) { var d = (0, _formatDecimal2['default'])(x, p); var coefficient = void 0, exponent = void 0, i = void 0, n = void 0; if (!d) return x + ''; coefficient = d[0]; exponent = d[1]; i = exponent - (exports.prefixExponent = prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1; n = coefficient.length; if (i === n) { return coefficient; } else if (i > n) { return coefficient + new Array(i - n + 1).join('0'); } else if (i > 0) { return coefficient.slice(0, i) + '.' + coefficient.slice(i); } else { // seriously minuscule numbers! return '0.' + new Array(1 - i).join('0') + (0, _formatDecimal2['default'])(x, Math.max(0, p + i - 1))[0]; } }; exports.prefixExponent = prefixExponent; exports['default'] = formatPrefixAuto; /***/ }), /* 412 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _formatDecimal = __webpack_require__(407); var _formatDecimal2 = _interopRequireDefault(_formatDecimal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var formatRounded = function formatRounded(x, p) { var d = (0, _formatDecimal2['default'])(x, p); var coefficient = void 0, exponent = void 0; if (!d) return x + ''; coefficient = d[0]; exponent = d[1]; if (Number(exponent) < 0) { return '0.' + new Array(-exponent).join('0') + coefficient; } else if (coefficient.length > exponent + 1) { return coefficient.slice(0, exponent + 1) + '.' + coefficient.slice(exponent + 1); } else { return coefficient + new Array(exponent - coefficient.length + 2).join('0'); } }; exports['default'] = formatRounded; /***/ }), /* 413 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; // Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k. function formatTrim(str) { var n = str.length, i = 1, i0 = -1, i1 = void 0; for (; i < n; ++i) { if (str[i] === '.') { i0 = i1 = i; } else if (str[i] === '0') { if (i0 === 0) i0 = i; i1 = i; } else { if (i0 > 0) { if (!+str[i]) break; i0 = 0; } } } return i0 > 0 ? str.slice(0, i0) + str.slice(i1 + 1) : str; } exports['default'] = formatTrim; /***/ }), /* 414 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var formatGroup = function formatGroup(grouping, thousands) { return function (value, width) { var i = value.length, t = [], j = 0, g = grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = grouping[j = (j + 1) % grouping.length]; } return t.reverse().join(thousands); }; }; exports["default"] = formatGroup; /***/ }), /* 415 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var formatNumerals = function formatNumerals(numerals) { return function (value) { return value.replace(/[0-9]/g, function (i) { return numerals[+i]; }); }; }; exports["default"] = formatNumerals; /***/ }), /* 416 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var E10 = Math.sqrt(50), E5 = Math.sqrt(10), E2 = Math.sqrt(2); function getMultiplier(error) { var errorFactor = void 0; if (error >= E10) { errorFactor = 10; } else if (error >= E5) { errorFactor = 5; } else if (error >= E2) { errorFactor = 2; } else { errorFactor = 1; } return errorFactor; } function tickIncrement() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power); if (power >= 0) { return getMultiplier(error) * Math.pow(10, power); } else { return -Math.pow(10, -power) / getMultiplier(error); } } function tickStep() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var step0 = Math.abs(stop - start) / Math.max(0, count), power = Math.floor(Math.log(step0) / Math.LN10), step1 = Math.pow(10, power), error = step0 / step1; if (error >= E10) { step1 *= 10; } else if (error >= E5) { step1 *= 5; } else if (error >= E2) { step1 *= 2; } return stop < start ? -step1 : step1; } function ticks() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var reverse = void 0, i = -1, n = void 0, tickArr = [], step = void 0; stop = +stop; start = +start; count = +count; if (start === stop && count > 0) return [start]; reverse = stop < start; if (reverse) { n = start; start = stop; stop = n; } step = tickIncrement(start, stop, count); if (step === 0 || !isFinite(step)) return []; if (step > 0) { start = Math.ceil(start / step); stop = Math.floor(stop / step); n = Math.ceil(stop - start + 1); while (++i < n) { tickArr[i] = (start + i) * step; } } else { start = Math.floor(start * step); stop = Math.ceil(stop * step); n = Math.ceil(start - stop + 1); while (++i < n) { tickArr[i] = (start - i) / step; } } if (reverse) tickArr.reverse(); return tickArr; } exports["default"] = ticks; exports.tickIncrement = tickIncrement; exports.tickStep = tickStep; /***/ }), /* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.tickFormat = exports.tickStep = exports.tickIncrement = undefined; var _numberConverter = __webpack_require__(405); var _numberConverter2 = _interopRequireDefault(_numberConverter); var _precisionFixed = __webpack_require__(418); var _precisionFixed2 = _interopRequireDefault(_precisionFixed); var _precisionRound = __webpack_require__(419); var _precisionRound2 = _interopRequireDefault(_precisionRound); var _formatSpecifier = __webpack_require__(409); var _formatSpecifier2 = _interopRequireDefault(_formatSpecifier); var _precisionPrefix = __webpack_require__(420); var _precisionPrefix2 = _interopRequireDefault(_precisionPrefix); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var E10 = Math.sqrt(50), E5 = Math.sqrt(10), E2 = Math.sqrt(2), isNil = function isNil(x) { return x === null || typeof x === 'undefined'; }; function getMultiplier(error) { var errorFactor = void 0; if (error >= E10) { errorFactor = 10; } else if (error >= E5) { errorFactor = 5; } else if (error >= E2) { errorFactor = 2; } else { errorFactor = 1; } return errorFactor; } function tickIncrement() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power); if (power >= 0) { return getMultiplier(error) * Math.pow(10, power); } else { return -Math.pow(10, -power) / getMultiplier(error); } } function tickStep() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var step0 = Math.abs(stop - start) / Math.max(0, count), power = Math.floor(Math.log(step0) / Math.LN10), step1 = Math.pow(10, power), error = step0 / step1; if (error >= E10) { step1 *= 10; } else if (error >= E5) { step1 *= 5; } else if (error >= E2) { step1 *= 2; } return stop < start ? -step1 : step1; } function ticks() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var stop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var count = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 7; var reverse = void 0, i = -1, n = void 0, tickArr = [], step = void 0; stop = +stop; start = +start; count = +count; if (start === stop && count > 0) return [start]; reverse = stop < start; if (reverse) { n = start; start = stop; stop = n; } step = tickIncrement(start, stop, count); if (step === 0 || !isFinite(step)) return []; if (step > 0) { start = Math.ceil(start / step); stop = Math.floor(stop / step); n = Math.ceil(stop - start + 1); while (++i < n) { tickArr[i] = (start + i) * step; } } else { start = Math.floor(start * step); stop = Math.ceil(stop * step); n = Math.ceil(start - stop + 1); while (++i < n) { tickArr[i] = (start - i) / step; } } if (reverse) tickArr.reverse(); return tickArr; } function tickFormat(domain, count, specifier) { var converter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _numberConverter2['default']; var start = domain[0], stop = domain[domain.length - 1], step = tickStep(start, stop, isNil(count) ? 7 : count); var precision = void 0, value = void 0; specifier = new _formatSpecifier2['default'](isNil(specifier) ? ',f' : specifier); switch (specifier.type) { case 's': { value = Math.max(Math.abs(start), Math.abs(stop)); precision = (0, _precisionPrefix2['default'])(step, value); if (isNil(specifier.precision) && !isNaN(precision)) { specifier.precision = precision; } return function (v) { return converter.formatPrefix(specifier, value).format(v); }; } case '': case 'e': case 'g': case 'p': case 'r': { precision = (0, _precisionRound2['default'])(step, Math.max(Math.abs(start), Math.abs(stop))); if (isNil(specifier.precision) && !isNaN(precision)) { specifier.precision = precision - (specifier.type === 'e'); } break; } case 'f': case '%': { precision = (0, _precisionFixed2['default'])(step); if (isNil(specifier.precision) && !isNaN(precision)) { specifier.precision = precision - (specifier.type === '%') * 2; } break; } } return function (v) { return converter.formatter(specifier).format(v); }; } exports['default'] = ticks; exports.tickIncrement = tickIncrement; exports.tickStep = tickStep; exports.tickFormat = tickFormat; /***/ }), /* 418 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _exponent = __webpack_require__(406); var _exponent2 = _interopRequireDefault(_exponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var precisionFixed = function precisionFixed(step) { return Math.max(0, -(0, _exponent2['default'])(Math.abs(step))); }; exports['default'] = precisionFixed; /***/ }), /* 419 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _exponent = __webpack_require__(406); var _exponent2 = _interopRequireDefault(_exponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var precisionRound = function precisionRound(step, max) { step = Math.abs(step); max = Math.abs(max) - step; return Math.max(0, (0, _exponent2['default'])(max) - (0, _exponent2['default'])(step)) + 1; }; exports['default'] = precisionRound; /***/ }), /* 420 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _exponent = __webpack_require__(406); var _exponent2 = _interopRequireDefault(_exponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var precisionPrefix = function precisionPrefix(step, value) { return Math.max(0, Math.max(-8, Math.min(8, Math.floor((0, _exponent2['default'])(value) / 3))) * 3 - (0, _exponent2['default'])(Math.abs(step))); }; exports['default'] = precisionPrefix; /***/ }), /* 421 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _range = __webpack_require__(398); var _range2 = _interopRequireDefault(_range); var _lib = __webpack_require__(125); var _continuous = __webpack_require__(400); var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var errorMapping = (0, _continuous.bimap)([2, 100], [80, 20], _continuous.deInterpolateLinear, _number2['default']), /** * function to get error value * @param {number} count the count * @returns {number} error value */ getErrorValue = function getErrorValue(count) { if (count >= 100) return 0.2; if (count <= 1) return 0; return errorMapping(count) / 100; }, /** * api to return the nearest nice value of interval * @param {number} interval is a number * @return {number} nice interval */ niceInterval = function niceInterval(interval) { if (interval <= 1) return 1; var arr = [], ceilInterval = Math.ceil(interval); arr[2] = ceilInterval % 2; arr[5] = ceilInterval % 5; arr[10] = ceilInterval % 10; return (0, _lib.safeMin)(arr) + ceilInterval; }, /** * api to return the interval values * @param {number} min minimum value * @param {number} max maximum value * @param {number} count of divisions required * @param {number} errorLimit error ratio * @param {boolean} forceZeroTick decides if we have to forcefully add zero * @param {Object} scale instance of scale class * @return {Object} containing interval array and interval */ noLimitChange = function noLimitChange(min, max, count, errorLimit, forceZeroTick, scale) { var diff = max - min, interval = void 0, j = void 0, addZero = void 0, k = min, minCount = Math.ceil(count * (1 - errorLimit)), maxCount = Math.floor(count * (1 + errorLimit)), noOfInterval = void 0, isZeroTickForced = void 0, errorInterval = void 0, outputLen = void 0, firstNum = void 0, lastNum = void 0, output = [], /** * @param {number} value value that needs to be checked * @returns {number} return if its multiple */ checkMultiple = function checkMultiple(value) { var arr = [10, 5, 2, 1], i = void 0, len = arr.length, rem = void 0, isMultiple = void 0; for (i = 0; i < len; ++i) { rem = value % arr[i]; if (rem % 1 === 0) { isMultiple = true; break; } } return isMultiple; }, counter = -1, minCovered = void 0, maxCovered = void 0, temp = void 0, /** * @param {number} value - number that needs to be checked * @returns {boolean} true/false */ willBreak = function willBreak(value) { return checkMultiple(interval = diff / (value + 1)) ? value : _lib.UNDEF; }; while (!minCovered || !maxCovered) { ++counter; temp = count + counter; if (temp >= maxCount) maxCovered = true; noOfInterval = willBreak(temp); if (noOfInterval) break; temp = count - counter; if (temp <= minCount) minCovered = true; noOfInterval = willBreak(temp); if (noOfInterval) break; } if (min < 0 && max > 0 && forceZeroTick) addZero = true; for (j = 0; j < noOfInterval; j++) { if (addZero && k < 0 && k + interval > 0) { output.push(0); isZeroTickForced = true; } k += interval; output.push(k); } // when we cannnot decide a good interval then we will use the ticks internally and // it will be only done for charts, so we are checking the forceZeroTick since that // is off for gauges if (noOfInterval === _lib.UNDEF && forceZeroTick) { output = scale.ticks(count); outputLen = output.length; if (outputLen > 1) { interval = Math.abs(output[0] - output[1]); errorInterval = interval * 0.2; firstNum = output[0]; lastNum = output[outputLen - 1]; if (Math.abs(min - firstNum) <= errorInterval && firstNum !== 0) output.shift(); if (Math.abs(max - lastNum) <= errorInterval && lastNum !== 0) output.pop(); if (firstNum === 0 || lastNum === 0) isZeroTickForced = true; } else if (output[0] === 0) isZeroTickForced = true; } if (addZero && !isZeroTickForced && output.indexOf(0) === -1) { if (min < 0 && output[0] > 0) { output = [0].concat(output); } else if (max > 0 && output[output.length - 1] < 0) { output.push(0); } else { output = [0]; } isZeroTickForced = true; } return { output: output, interval: interval, isZeroTickForced: isZeroTickForced }; }, /** * Function to update the domain and set information in axis * @param {number} min of domain * @param {number} max of domain * @param {Object} scale being used by axis * @param {Object} axisConfig the configuration of axis */ domainUpdater = function domainUpdater(min, max, scale, axisConfig) { var axisMinValue = axisConfig.isPercent ? 0 : axisConfig.axisMinValue, axisMaxValue = axisConfig.isPercent ? 100 : axisConfig.axisMaxValue, adjustDiv = !!axisConfig.adjustDiv, originalDivLines = axisConfig.numDivLines, numDivLines, divisions, setAdaptiveMin = !!axisConfig.setAdaptiveMin, axisRange = axisConfig.axisRange, minPowerOfTen, maxPowerOfTen, powerOfTen, interval, tickInterval, topBound, lowerBound, yMaxGiven, yMinGiven, rangePowerOfTen, rangeInterval, intervalArr, EPSILON = Math.pow(2, -24), extendDomain = true, tempMin, tempMax, errorLimit = 0.2, domain, negitiveTicks, ticksNotCreated = true, positiveMin, noLimitChangeObj, intervalArrLen, isZeroTickForced, xAxisLabelMode = axisConfig.xAxisLabelMode, dependentInfo = axisConfig.dependentInfo; numDivLines = axisConfig.majorTMNumber !== _lib.UNDEF ? Math.max(0, originalDivLines - 2) : originalDivLines; // if the axis has some dependent info then it will take it into consideration // if the axis is also dependent in the limits then we do not need change the // the adjustdiv and numdivlines since it will automatically follow the steps // followed by the primary axis if (dependentInfo && dependentInfo.count && !dependentInfo.limit) { if (dependentInfo.numDivLines !== _lib.UNDEF) { numDivLines = originalDivLines = dependentInfo.numDivLines; // this is done to sync the divlines adjustDiv = false; } } divisions = numDivLines + 1; // when the data has no limit then axis will be from 0 to 1 and it will not get // extended if (min === _lib.UNDEF && max === _lib.UNDEF) { min = 0; max = 1; extendDomain = false; } // if both max and min is zero then axis will be from 0 to 1 and domain will not be extended if (max === min && max === 0) { max = 1; extendDomain = false; } // If the axis is a numeric axis with tickValues, it is not eligible for domain extension if (xAxisLabelMode === 'categories' || xAxisLabelMode === 'mixed') { extendDomain = false; } if (extendDomain) { maxPowerOfTen = Math.floor(Math.log(Math.abs(max)) / Math.LN10); minPowerOfTen = Math.floor(Math.log(Math.abs(min)) / Math.LN10); powerOfTen = Math.max(minPowerOfTen, maxPowerOfTen); interval = Math.pow(10, powerOfTen); // For accomodating smaller range values (so that scale doesn't represent too large an interval if (Math.abs(max) / interval < 2 && Math.abs(min) / interval < 2) { powerOfTen--; interval = Math.pow(10, powerOfTen); } // If the interval of min and max is way more than that of range. // We need to reset the interval as per range rangePowerOfTen = Math.floor(Math.log(max - min) / Math.LN10); rangeInterval = Math.pow(10, rangePowerOfTen); // Now, if rangeInterval is 10 times less than y_interval, we need to re-set // the limits, as the range is too less to adjust the axis for max,min. // We do this only if range is greater than 0 (in case of 1 data on chart). if (max - min > 0 && interval / rangeInterval >= 10) { interval = rangeInterval; powerOfTen = rangePowerOfTen; } // Calculate the y-axis upper limit topBound = (Math.floor(max / interval) + 1) * interval; // Calculate the y-axis lower limit // yLowerBound; // Delta in range // deltaRange; // If the min value is less than 0 if (min < 0) { // Then calculate by multiplying negative numbers with y-axis interval lowerBound = -1 * ((Math.floor(Math.abs(min / interval)) + 1) * interval); } else { // Else, simply set it to 0. if (!setAdaptiveMin) { lowerBound = 0; } else { lowerBound = Math.floor(Math.abs(min / interval) - 1) * interval; // Now, if minValue>=0, we keep x_lowerBound to 0 - as for values like minValue 2 // lower bound goes negative, which is not required. lowerBound = lowerBound < 0 ? 0 : lowerBound; } } // MaxValue cannot be less than 0 if stopMaxAtZero is set to true if (!setAdaptiveMin && max <= 0) { topBound = 0; } // Now, we need to make a check as to whether the user has provided an upper limit // and lower limit. if (!axisMaxValue && axisMaxValue !== 0) { yMaxGiven = false; } else { yMaxGiven = true; } if (!axisMinValue && axisMinValue !== 0) { yMinGiven = false; } else { yMinGiven = true; } // If he has provided it and it is valid, we leave it as the upper limit // Else, we enforced the value calculate by us as the upper limit. if (!axisConfig.freezeLimit) { if (yMaxGiven === false || yMaxGiven === true && Number(axisMaxValue) < max && max - Number(axisMaxValue) > EPSILON) { max = topBound; // if the user given max value is less then data max then we will consider // that axis max is not given so that we can nice the axis yMaxGiven = false; } else { max = Number(axisMaxValue); } // Now, we do the same for y-axis lower limit if (yMinGiven === false || yMinGiven === true && Number(axisMinValue) > min && Number(axisMinValue) - min > EPSILON) { min = lowerBound; // if the user given min value is less then data min then we will consider // that axis min is not given so that we can nice the axis yMinGiven = false; } else { min = Number(axisMinValue); } } } else { if (!axisMaxValue && axisMaxValue !== 0) { yMaxGiven = false; } else { yMaxGiven = true; } if (!axisMinValue && axisMinValue !== 0) { yMinGiven = false; } else { yMinGiven = true; } if (yMaxGiven === true && Number(axisMaxValue) >= max) { max = Number(axisMaxValue); } else { // if the user given max value is less then data max then we will consider // that axis max is not given so that we can nice the axis yMaxGiven = false; } if (yMinGiven === true && Number(axisMinValue) <= min) { min = Number(axisMinValue); } else { // if the user given min value is less then data min then we will consider // that axis min is not given so that we can nice the axis yMinGiven = false; } } domain = [min, max]; scale.setDomain(domain); // for x axis of candlestick domain will neither be niced and nor be changed changed if (adjustDiv && !axisConfig.freezeLimit) { if (!yMaxGiven && !yMinGiven) { // if axis limits is not given and we have to adjust the divs then we will // nice the domain and calculate from ticks // if the divlines to be created is 0 then then we just have to show the limit axisConfig.ticks = !numDivLines ? scale.getDomain() : scale.nice(divisions).ticks(divisions); tickInterval = Math.abs(axisConfig.ticks[1] - axisConfig.ticks[0]); ticksNotCreated = false; } else { errorLimit = getErrorValue(numDivLines); // if any of the limit is given then we will calculate the intervals that we can create in between the data noLimitChangeObj = noLimitChange(min, max, numDivLines, errorLimit, axisConfig.forceZeroTick, scale); intervalArr = noLimitChangeObj.output; intervalArrLen = intervalArr.length; isZeroTickForced = noLimitChangeObj.isZeroTickForced; // if the change in numdivlines to be created is more than 20% than we will normally use range // Here if the numDivLines is zero then the given check will produce infinity // this is intentional so that after the calcualtion we will get the limits as ticks in // general flow // we will not consider the zero tick as interval if it is added forcefully if (Math.abs((numDivLines - intervalArrLen + (isZeroTickForced ? 1 : 0)) / numDivLines) > errorLimit) { tickInterval = (max - min) / divisions; } else { tickInterval = intervalArrLen === 0 || intervalArrLen === 1 && isZeroTickForced ? max - min : noLimitChangeObj.interval; axisConfig.isZeroTickForced = isZeroTickForced; axisConfig.ticks = [min].concat(intervalArr, max); ticksNotCreated = false; } } } else { // if adjustdiv is off then and limit is not given then we will try to adjust the limit if (!yMaxGiven && !yMinGiven && !axisConfig.freezeLimit) { var _scale$nice$getDomain = scale.nice(divisions).getDomain(); tempMin = _scale$nice$getDomain[0]; tempMax = _scale$nice$getDomain[1]; interval = (tempMax - tempMin) / divisions; tickInterval = niceInterval(interval); tempMax = tempMin + tickInterval * divisions; // if the change in max or min is more than 20% then it will not change the limit if ((tempMax - max) / max > errorLimit || (tempMin - min) / min > errorLimit) { // since the error is more than 20% we will reset the scale to original max and min scale.setDomain([min, max]); tickInterval = (max - min) / divisions; } else { // if the change is under error threshold then we will use changed // limit and update to scale min = tempMin; max = tempMax; scale.setDomain([min, max]); } } else { // the limit is given and we cant change the div lines then we will use // range itself tickInterval = (max - min) / divisions; } } if (ticksNotCreated) { if (min < 0 && max > 0 && axisConfig.forceZeroTick) { negitiveTicks = (0, _range2['default'])(min, 0, tickInterval); positiveMin = negitiveTicks[negitiveTicks.length - 1] + tickInterval; positiveMin === 0 ? positiveMin += tickInterval : axisConfig.isZeroTickForced = true; axisConfig.ticks = negitiveTicks.concat(0, (0, _range2['default'])(positiveMin, max, tickInterval), max); } else { axisConfig.ticks = (0, _range2['default'])(min, max, tickInterval).concat(max); } } var _scale$getDomain = scale.getDomain(); min = _scale$getDomain[0]; max = _scale$getDomain[1]; axisConfig._allTicks = axisConfig.ticks.slice(); axisRange.tickInterval = tickInterval; axisRange.min = min; axisRange.max = max; }; exports['default'] = domainUpdater; /***/ }), /* 422 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesianLabelManager = __webpack_require__(378); var _cartesianLabelManager2 = _interopRequireDefault(_cartesianLabelManager); var _range = __webpack_require__(398); var _range2 = _interopRequireDefault(_range); var _category = __webpack_require__(423); var _category2 = _interopRequireDefault(_category); var _lib = __webpack_require__(125); var _commonApi = __webpack_require__(386); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var DASH_DEF = 'none', TRUE_STRING = 'true', ONE_STRING = '1', POSITION_START = _lib.preDefStr.POSITION_START, POSITION_MIDDLE = _lib.preDefStr.POSITION_MIDDLE, POSITION_TOP = _lib.preDefStr.POSITION_TOP, POSITION_BOTTOM = _lib.preDefStr.POSITION_BOTTOM, POSITION_END = _lib.preDefStr.POSITION_END, queryOptions = { wrtVisible: true }; var CategoryAxis = function (_CartesianLabelManage) { _inherits(CategoryAxis, _CartesianLabelManage); function CategoryAxis() { _classCallCheck(this, CategoryAxis); var _this = _possibleConstructorReturn(this, _CartesianLabelManage.call(this)); _this.config.scale = new _category2['default'](); return _this; } /** * Sets the name of the component * @return {string} name */ CategoryAxis.prototype.getName = function getName() { return 'category'; }; CategoryAxis.prototype.getCategoryFromId = function getCategoryFromId(id) { var config = this.config, tickValues = config.tickValues, tickIdMap = tickValues && tickValues.tickIdMap; return tickIdMap[id] || {}; }; CategoryAxis.prototype.generateTicks = function generateTicks() { var scale = this.getScale(), axisConfig = this.config, domain = scale.getDomain(), divs = axisConfig.categoryNumDivLines + 1, step = (domain[1] - domain[0]) / divs, axisRange = axisConfig.axisRange, min = axisRange.min, max = axisRange.max, tickInterval = (max - min) / divs; axisConfig._allTicks = (0, _range2['default'])(min, max, tickInterval).concat(max); axisRange.tickInterval = tickInterval; return (0, _range2['default'])(domain[0], domain[1], step).concat(domain[1]); }; CategoryAxis.prototype._parseCategoryVline = function _parseCategoryVline() { var axis = this, axisConfig = axis.config, axisRange = axisConfig.axisRange, min = axisRange.min, max = axisRange.max, chart = axis.getFromEnv('chart'), chartConfig = chart.config, chartStyle = chartConfig.style || {}, isHorizontal = axisConfig.isVertical, divlineStyle = { fontFamily: chartConfig.style.inCanfontFamily, fontSize: chartConfig.style.inCanfontSize, color: chartConfig.style.inCancolor, lineHeight: chartConfig.style.inCanLineHeight }, showLabelBackground, vlines, len, vline, label, i, showLabelBorder, labelHAlign, labelVAlign, labelPosition, linePosition, showVLines, alpha, color, bgColor, thickness, isDashed, dashLen, fontSizeInt, dashGap, vLineDrawingAttrObj, css, vLineTextAttrObj, labelColor, labelRotation, borderPadding, finalValue, checkForLimit, getLimit, referenceObj, showOnTop, vlineStartIndex; vlines = axisConfig.tickValues.vline; len = vlines.length; checkForLimit = axis.getZoom() !== 1; getLimit = axis.getVisibleConfig(); for (i = 0; i < len; i++) { vline = vlines[i]; label = (0, _lib.parseUnsafeString)(vline.label); showLabelBorder = Boolean((0, _lib.pluckNumber)(vline.showlabelborder, axisConfig.showVLineLabelBorder, 1)); showLabelBackground = Boolean((0, _lib.pluckNumber)(vline.showlabelbackground, 1)); labelHAlign = (0, _lib.pluck)(vline.labelhalign, isHorizontal ? POSITION_START : POSITION_MIDDLE); if (labelHAlign === 'center') { labelHAlign = POSITION_MIDDLE; } else if (labelHAlign === 'left') { labelHAlign = POSITION_START; } else if (labelHAlign === 'right') { labelHAlign = POSITION_END; } labelVAlign = (0, _lib.pluck)(vline.labelvalign, isHorizontal ? POSITION_MIDDLE : POSITION_BOTTOM).toLowerCase(); if (labelVAlign === POSITION_MIDDLE) { labelVAlign = POSITION_MIDDLE; } else if (labelVAlign === POSITION_TOP) { labelVAlign = POSITION_BOTTOM; } else if (labelVAlign === POSITION_BOTTOM) { labelVAlign = POSITION_TOP; } /** TODO: need to calculate in px, to set y */ labelPosition = (0, _lib.pluckNumber)(vline.labelposition, 0); linePosition = (0, _lib.pluckNumber)(vline.lineposition, 0.5); showVLines = (0, _lib.pluckNumber)(vline.showvlines, axisConfig.showVLines, 1); alpha = (0, _lib.pluckNumber)(vline.alpha, axisConfig.vLineAlpha, 80); color = (0, _lib.pluck)(vline.color, axisConfig.vLineColor).replace(/^#?/, '#'); // Extract the background color of the vline label bgColor = showLabelBackground ? (0, _lib.pluck)(vline.labelbgcolor, axisConfig.vLineLabelBgColor, '333333').replace(/^#?/, '#') : _lib.BLANKSTRING; labelColor = (0, _lib.pluck)(vline.labelcolor, axisConfig.vLineLabelColor, vline.color, chartStyle.inCancolor, axisConfig.vLineColor).replace(/^#?/, '#'); thickness = (0, _lib.pluckNumber)(vline.thickness, axisConfig.vLineThickness, 1); borderPadding = 2; isDashed = Boolean(Number((0, _lib.pluck)(vline.dashed, 0))); dashLen = (0, _lib.pluckNumber)(vline.dashlen, 5); dashGap = (0, _lib.pluckNumber)(vline.dashgap, 2); fontSizeInt = divlineStyle.fontSize; fontSizeInt = parseInt(fontSizeInt.replace(/px/i, ''), 10); labelRotation = (0, _lib.pluckNumber)(vline.rotatelabel, axisConfig.rotateVLineLabels) ? 270 : 0; linePosition = linePosition < 0 || linePosition > 1 ? 0.5 : linePosition; labelPosition = labelPosition < 0 || labelPosition > 1 ? 0 : labelPosition; color = (0, _lib.convertColor)(color, showVLines ? alpha : '0'); // For realtime charts if animation is there in vline drawing vlineStartIndex = vline.animate && !isHorizontal ? vline.startIndex + 1 : vline.startIndex; finalValue = axis._getVlinePos(vlineStartIndex, linePosition) - (vline.animate ? vline.leftShift : 0); // if value is not between the visual limit increment it and continue if (checkForLimit && (finalValue < getLimit.minValue || finalValue > getLimit.maxValue)) { continue; } if (finalValue < min || finalValue > max) { continue; } vLineDrawingAttrObj = { opacity: 1, stroke: color, 'stroke-width': thickness, 'stroke-dasharray': isDashed ? (0, _lib.getDashStyle)(dashLen, dashGap) : DASH_DEF }; vLineTextAttrObj = { opacity: 1, 'text': label, 'text-anchor': labelHAlign, 'vertical-align': labelVAlign, 'text-bound': [] }; css = { fontSize: divlineStyle.fontSize, fontFamily: divlineStyle.fontFamily, lineHeight: divlineStyle.lineHeight }; showOnTop = (0, _lib.pluckNumber)(vline.showontop, axisConfig.showVLinesOnTop, 0); referenceObj = { from: finalValue, layer: showOnTop ? 3 : 2, attr: vLineDrawingAttrObj, type: 'line', startIndex: vline.startIndex, linePosition: linePosition }; if (label) { vLineTextAttrObj['text-bound'] = [bgColor, showVLines && showLabelBorder ? color : _lib.BLANKSTRING, showVLines && showLabelBorder ? 1 : 0, borderPadding, _lib.UNDEF, showVLines && showLabelBorder ? 'solid' : _lib.BLANKSTRING]; vLineTextAttrObj.fill = showVLines ? labelColor : color; referenceObj.text = { label: label, attr: vLineTextAttrObj, layer: 4, labelRotation: labelRotation, labelPosition: labelPosition, css: css }; } axis.setReferenceInfo(referenceObj); axis.config.parsedVlineInfo.push(referenceObj); } }; CategoryAxis.prototype._parseReferenceVisuals = function _parseReferenceVisuals() { _CartesianLabelManage.prototype._parseReferenceVisuals.call(this); this.config.drawPlotlines && this._parseCategoryVline(); }; /** * Function helps to insert category dynamically * @param {number} index the index from which the category will be inserted * @param {Array} data the array containing the list of categories and vlines * @param {boolean} adjustRange decided the axis range will be redefined or not */ CategoryAxis.prototype.categoryInsert = function categoryInsert(index, data, adjustRange) { var axis = this, axisConfig = axis.config, min = axisConfig.axisRange.min, len = data.length, endPad = axisConfig.endPad || 0, category, vline, tickIdMap, i, tickObj; category = axisConfig.tickValues.tickValue; tickIdMap = axisConfig.tickValues.tickIdMap; vline = axisConfig.tickValues.vline; // storing category and vline for (i = 0; i < len; i += 1) { tickObj = (0, _lib.extend2)({}, data[i]); if (!(tickObj.vline === TRUE_STRING || tickObj.vline === true || tickObj.vline === 1 || tickObj.vline === ONE_STRING)) { // parse and store the category ID if (tickObj.id) { tickIdMap[tickObj.id] = { tickObj: tickObj, i: index }; } category.splice(index, 0, tickObj); index += 1; } else { tickObj.startIndex = index - 2; vline.push(tickObj); } } if (adjustRange) { // axisRange.max = Number(toPrecision(category.length - 1 + endPad, 10)); axis._setAxisRange({ min: min, max: Number((0, _lib.toPrecision)(category.length - 1 + endPad, 10)) }); } }; /** * Function helps to delete the category starting from the startIndex upto the length * @param {number} startIndex the starting position of the index from which the data will be remove * @param {number} length the length upto which the array will be deleted * @param {boolean} adjustRange if the range will be redifined */ CategoryAxis.prototype.categoryDelete = function categoryDelete(startIndex, length, adjustRange) { var axis = this, axisConfig = axis.config, axisRange = axisConfig.axisRange, min = axisRange.min, animateVline, i, len, category; animateVline = axisConfig.tickValues.vline; for (i = 0, len = animateVline.length; i < len; i++) { animateVline[i].animate = true; animateVline[i].leftShift = length; } category = axisConfig.tickValues.tickValue; category.splice(startIndex, length); axis._shiftVline(startIndex, length, 'left'); if (adjustRange) { axis._setAxisRange({ min: min, max: axisRange.max - length }); } }; /** * function used internally to shift the vline left of the given index to the direction defined * @param {number} index The index right of whose every vline will be shifted * @param {number} shift no of place by which the label will be shifted * @param {string} direction direction to be shifted right or left */ CategoryAxis.prototype._shiftVline = function _shiftVline(index, shift, direction) { var axis = this, axisConfig = axis.config, vline = axisConfig.tickValues.vline, catLen = axisConfig.tickValues.tickValue.length, len = vline.length, i, curVline; for (i = 0; i < len; i += 1) { curVline = vline[i]; if (curVline.startIndex >= index) { if (direction === 'right') { curVline.startIndex += shift; } else { curVline.startIndex -= shift; } // if vline get out of canvas delete the vline if (curVline.startIndex < 0 || curVline.startIndex >= catLen) { vline.splice(i, 1); len -= 1; i -= 1; } } } }; /** * Gets the translation string of the category for realtime updates * @param {number} x The amount by which to translate the category in the x direction */ CategoryAxis.prototype.categoryTranslate = function categoryTranslate(x) { var axis = this, axisConfig = axis.config, diff = axis.getPixel(1, queryOptions) - axis.getPixel(0, queryOptions), translationStr; x = (x || 0) * diff; if (axisConfig.isReverse) { x = -x; } translationStr = ['T', x, ',', '0'].join(''); axis.realTimeTranslatableGroups = [{ group: axisConfig.axisContainer, translationStr: translationStr }, { group: axisConfig.axisTrendLabelContainer, translationStr: translationStr }]; }; /** * Function used to update the category property * @param {number} id the id of the cateory * @param {Object} object The object containing the attribute to be updated */ CategoryAxis.prototype.updateTicksValues = function updateTicksValues(id, object) { var axis = this, axisConfig = axis.config, ticks, isVlineUpdated, vlinesArr = axisConfig.parsedVlineInfo, vline, i, ln, index, prop; ticks = axisConfig.tickValues.tickValue; if (ticks[id]) { for (prop in object) { if (object.hasOwnProperty(prop)) { if (prop === 'x') isVlineUpdated = true; ticks[id][prop] = object[prop]; } } } // this is used marimekko chart if (isVlineUpdated) { for (i = 0, ln = vlinesArr.length; i < ln; ++i) { vline = vlinesArr[i]; index = vline.startIndex; if (index === id) { vline.from = axis._getVlinePos(index, vline.linePosition); } else if (index + 1 === id) { vline.from = axis._getVlinePos(index, vline.linePosition); break; } } } }; /** * api to give the vline position * @param {number} index of vline * @param {number} linePosition of vline */ CategoryAxis.prototype._getVlinePos = function _getVlinePos(index, linePosition) { var ticks = this.getTickValues(), axisConfig = this.config, _getLimit = this.getLimit(), min = _getLimit.min, max = _getLimit.max, categoryStart = ticks[index], categoryEnd = ticks[index + 1], categoryStartPos = void 0, posRelCategory = void 0, isExtreme = void 0; // invalid vline or vline at the end if (!categoryStart) { categoryStartPos = ticks[0] && ticks[0].x ? min : -1; isExtreme = true; } else if (!categoryEnd) { categoryStartPos = ticks[0] && ticks[0].x ? max : axisConfig.oriCatLen - 1; isExtreme = true; } if (!isExtreme) { categoryStartPos = (0, _lib.pluckNumber)(categoryStart.x, categoryStart.y, index); posRelCategory = (categoryStartPos - (0, _lib.pluckNumber)(categoryEnd.x, categoryEnd.y, index + 1)) * linePosition; } else { posRelCategory = linePosition; } return categoryStartPos + Math.abs(posRelCategory); }; /** * the function will return only 1 since it is a category axis * @returns {number} returns 1 for category axis */ CategoryAxis.prototype.getInterval = function getInterval() { if (this) return 1; }; CategoryAxis.prototype._setAxisRange = function _setAxisRange(data) { var min = data.min, max = data.max, axisConfig = this.config, axisRange = axisConfig.axisRange, periodLength = axisConfig.periodLength, dataLimit = axisConfig.dataLimit, oldMax = dataLimit.max, oldMin = dataLimit.min, limitChanged, step; if (min > max) { return; } if (oldMax !== max || oldMin !== min) limitChanged = true; if (axisConfig.visibleMin !== _lib.UNDEF && !axisConfig.setPadding && !limitChanged) { axisConfig.setPadding = false; } else { dataLimit.max = max; dataLimit.min = min; // for spark charts the period length will be given in axisconfig if (periodLength) { axisConfig.categoryNumDivLines = (max - min) / periodLength - 1; } step = (max - min) / (axisConfig.categoryNumDivLines + 1); this.getScale().setDomain([min, max]); axisConfig.ticks = (0, _range2['default'])(min, max, step).concat(max); axisConfig._allTicks = axisConfig.ticks.slice(); axisRange.min = min; axisRange.max = max; axisRange.tickInterval = step; this.setVisibleConfig(axisRange.min, axisRange.max); } }; return CategoryAxis; }(_cartesianLabelManager2['default']); CategoryAxis.prototype.setTickValues = _commonApi.setTickValues; exports['default'] = CategoryAxis; /***/ }), /* 423 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _continuous = __webpack_require__(400); var _continuous2 = _interopRequireDefault(_continuous); var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var ScaleCategory = function (_ScaleContinuous) { _inherits(ScaleCategory, _ScaleContinuous); function ScaleCategory() { _classCallCheck(this, ScaleCategory); return _possibleConstructorReturn(this, _ScaleContinuous.call(this, _continuous.deInterpolateLinear, _number2['default'])); } /** * creates a new copy of the scale with configiration of the current scale * @return {Object} instance of new scale */ ScaleCategory.prototype.copy = function copy() { return (0, _continuous.copyScale)(this, new ScaleCategory()); }; return ScaleCategory; }(_continuous2['default']); exports['default'] = ScaleCategory; /***/ }), /* 424 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var canvas = void 0, canvasConfig = chart._parseCanvasCosmetics && chart._parseCanvasCosmetics(); (0, _lib.componentFactory)(chart, _canvas2['default'], 'canvas', chart.config.showVolumeChart ? 2 : 1); canvas = chart.getChildren('canvas'); if (canvas) { for (var i = 0, len = canvas.length; i < len; i++) { canvas[i].configure(canvasConfig); (0, _lib.componentFactory)(canvas[i], _axisRefComponent2['default'], 'axisRefVisualCartesian'); } } }; var _canvas = __webpack_require__(364); var _canvas2 = _interopRequireDefault(_canvas); var _axisRefComponent = __webpack_require__(425); var _axisRefComponent2 = _interopRequireDefault(_axisRefComponent); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 425 */ /***/ (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 _componentInterface = __webpack_require__(138); var _number = __webpack_require__(382); var _number2 = _interopRequireDefault(_number); var _diff = __webpack_require__(383); var _diff2 = _interopRequireDefault(_diff); var _cartesian = __webpack_require__(379); var _cartesianAxisRef = __webpack_require__(426); var _cartesianAxisRef2 = _interopRequireDefault(_cartesianAxisRef); var _dependencyManager = __webpack_require__(132); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var isValid = function isValid(val) { return !(typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'undefined' || val !== null; }; var UNDEF = void 0; (0, _dependencyManager.addDep)({ name: 'cartesianAxisRefAnimation', type: 'animationRule', extension: _cartesianAxisRef2['default'] }); var AxisRefVisual = function (_ComponentInterface) { _inherits(AxisRefVisual, _ComponentInterface); function AxisRefVisual() { _classCallCheck(this, AxisRefVisual); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this.config.map = {}; _this.config.explicitDrawItems = {}; return _this; } /** * Sets the type of the component * @return {string} type */ AxisRefVisual.prototype.getType = function getType() { return 'axisRefVisuals'; }; /** * Sets the name of the component * @return {string} name */ AxisRefVisual.prototype.getName = function getName() { return 'axisRefVisualsCartesian'; }; AxisRefVisual.prototype.draw = function draw() { var drawingInfo = this.getDrawingInfo(), eachCompInfo = void 0, explicitDrawItems = this.getexplicitDrawItems(), axisRefConf = this.config, oldMap = axisRefConf.map, map = {}, i = void 0, type = void 0, key = void 0, axis = void 0, elementIdArr = void 0, eachDrawInfo = void 0, parent = this.getLinkedParent(), axes = parent.getAxes(), axesIdArr = [], baseContainer = parent.getChildContainer('axisReferenceVisualsFloor'), bottomContainer = parent.getChildContainer('axisReferenceVisualsBottom'), middleContainer = parent.getChildContainer('axisReferenceVisualsMiddle'), topContainer = parent.getChildContainer('axisReferenceVisualsTop'), ceilContainer = parent.getChildContainer('axisReferenceVisualsCeil'); parent.config.trendlines = []; parent.config.vtrendlines = []; for (i = 0; i < axes.length; ++i) { axesIdArr.push(axes[i].axis.getId()); } axisRefConf.containers = [baseContainer, bottomContainer, middleContainer, topContainer, ceilContainer]; for (key in drawingInfo) { if (drawingInfo.hasOwnProperty(key)) { axis = this.getLinkedItem(key); if (axesIdArr.indexOf(axis.getId()) >= 0) { elementIdArr = map[key]; if (!elementIdArr) { elementIdArr = map[key] = []; } eachCompInfo = drawingInfo[key]; for (i = 0; i < eachCompInfo.length; ++i) { eachDrawInfo = eachCompInfo[i]; type = eachDrawInfo.type; if (type === 'band') { elementIdArr.push.apply(elementIdArr, this.createBand(eachDrawInfo, axis)); } else if (type === 'line') { elementIdArr.push.apply(elementIdArr, this.createLine(eachDrawInfo, axis)); } } } } } // if axis draws for some explicit items then after drawing it adds rest // of the mapping of iother items so that it does not get removed if (axisRefConf.isSmartDrawing) { for (key in oldMap) { if (oldMap.hasOwnProperty(key) && !explicitDrawItems[key] && this.getLinkedItem(key)) { map[key] = oldMap[key]; } } } // explicit items will be reset irrespective of smartDrawing or not this.resetexplicitDrawItems(); this.removeExtraElements(map); }; AxisRefVisual.prototype.getDrawingInfo = function getDrawingInfo() { var drawingInfo = {}, key = void 0, item = void 0, explicitDrawItems = this.getexplicitDrawItems(), canvasChanged = this.isCanvasChnaged(), isSmartDrawing = this.config.isSmartDrawing = Object.keys(explicitDrawItems).length && !canvasChanged, linkItems = isSmartDrawing ? explicitDrawItems : this.getLinkedItem(); for (key in linkItems) { if (linkItems.hasOwnProperty(key)) { item = linkItems[key]; drawingInfo[key] = item.getReferenceInfo(); } } return drawingInfo; }; AxisRefVisual.prototype.createLine = function createLine(lineInfo, axis) { var containersArr = this.config.containers, container = containersArr[lineInfo.layer], axisConf = axis.config, paper = this.getFromEnv('paper'), chartType = this.getFromEnv('chart').getName(), canvas = this.getLinkedParent(), animationManager = this.getFromEnv('animationManager'), toolTipController = this.getFromEnv('toolTipController'), canvasConf = canvas.config, trendLines = canvasConf.trendlines, isVertical = axisConf.isVertical, canvasLeft = canvasConf.canvasLeft, canvasTop = canvasConf.canvasTop, canvasBottom = canvasTop + canvasConf.canvasHeight, canvasRight = canvasLeft + canvasConf.canvasWidth, interpolatorLeftRight = (0, _number2['default'])(canvasLeft, canvasRight), interpolatorTopBottom = (0, _number2['default'])(canvasTop, canvasBottom), scale = axis.getScale(), start = scale.getRangeValue(lineInfo.from), end = lineInfo.to !== UNDEF && scale.getRangeValue(lineInfo.to) || start, path = isVertical ? ['M', canvasLeft, start, 'L', canvasRight, end] : ['M', start, canvasBottom, 'L', end, canvasTop], lineAttr = lineInfo.attr, text = lineInfo.text, textAttr = text && text.attr, labelPosition = text && text.labelPosition || 0, compId = axis.getId(), eleId = lineInfo.id || lineInfo.from, lineEleId = compId + '_' + eleId, textEleId = void 0, element = this.getGraphicalElement(lineEleId), textElem = void 0, key = void 0, handlers = lineInfo.handlers, value = { start: lineInfo.from, end: lineInfo.to }; lineAttr.path = (0, _cartesian.getCrispPath)(path, isValid(lineAttr['stroke-width']) ? lineAttr['stroke-width'] : 1).path.toString(); if (/trend/.test(lineInfo.id)) { trendLines.push({ x1: path[1], y1: path[2], x2: path[4], y2: path[5], tooltext: lineInfo.toolText, tolerance: lineAttr['stroke-width'] < 5 ? 2.5 : lineAttr['stroke-width'] / 2 }); } lineAttr['stroke-linecap'] = 'butt'; element = this.addGraphicalElement(lineEleId, animationManager.setAnimation({ container: container, el: element || 'path', attr: lineAttr, component: this, axis: axis, data: { value: value, path: path }, label: 'path' })); element.data('data', value); if (text) { textEleId = compId + '_' + eleId + textAttr.text; textElem = this.getGraphicalElement(textEleId); if (isVertical) { textAttr.x = interpolatorLeftRight(labelPosition); textAttr.y = start; } else { textAttr.x = start; textAttr.y = interpolatorTopBottom(labelPosition); } textAttr.text = text.label; textAttr.transform = paper.getSuggestiveRotation(text.labelRotation, textAttr.x, textAttr.y); textElem = this.addGraphicalElement(textEleId, animationManager.setAnimation({ container: containersArr[text.layer], el: textElem || 'text', attr: textAttr, component: this, axis: axis, data: { value: lineInfo.from }, label: 'text', css: text.css })); textElem.data('data', lineInfo.from); } // do no assign implicit tooltip for trendlines for zoomscatter if (!/zoomscatter/i.test(chartType)) { if (lineInfo.toolText) { toolTipController.enableToolTip(element, lineInfo.toolText); } else { toolTipController.disableToolTip(element); } } for (key in handlers) { if (handlers.hasOwnProperty(key)) { element.on(key, handlers[key].bind(axis)); textElem && textElem.on(key, handlers[key].bind(axis)); } } return text ? [lineEleId, textEleId] : [lineEleId]; }; AxisRefVisual.prototype.createBand = function createBand(bandInfo, axis) { var container = this.config.containers[bandInfo.layer], axisConf = axis.config, animationManager = this.getFromEnv('animationManager'), toolTipController = this.getFromEnv('toolTipController'), canvas = this.getLinkedParent(), chartType = this.getFromEnv('chart').getName(), canvasConf = canvas.config, isVertical = axisConf.isVertical, canvasLeft = canvasConf.canvasLeft, canvasTop = canvasConf.canvasTop, canvasBottom = canvasTop + canvasConf.canvasHeight, canvasRight = canvasLeft + canvasConf.canvasWidth, scale = axis.getScale(), startVal = bandInfo.from, endVal = bandInfo.to !== UNDEF ? bandInfo.to : startVal, startPx = void 0, endPx = void 0, compId = axis.getId(), eleId = void 0, bandElemId = void 0, element = void 0, key = void 0, elemAttr = bandInfo.attr, difference = void 0, handlers = bandInfo.handlers; // for bands to be drawn from canvas start if (startVal === 'canvasStart') { startPx = isVertical ? canvasTop : canvasLeft; } else { startPx = scale.getRangeValue(startVal); } // for bands to be drawn from canvas end if (endVal === 'canvasEnd') { endPx = isVertical ? canvasBottom : canvasRight; } else { endPx = scale.getRangeValue(endVal); } difference = Math.abs(startPx - endPx); if (isVertical) { elemAttr.x = canvasLeft; elemAttr.y = Math.min(startPx, endPx); elemAttr.width = canvasRight - canvasLeft; elemAttr.height = difference; } else { elemAttr.x = Math.min(startPx, endPx); elemAttr.y = canvasTop; elemAttr.width = difference; elemAttr.height = canvasBottom - canvasTop; } eleId = bandInfo.id || elemAttr.x + '_' + elemAttr.y; bandElemId = compId + '_' + eleId; element = this.getGraphicalElement(bandElemId); if (/trend/.test(bandInfo.id)) { canvas.config.vtrendlines.push({ x1: elemAttr.x, y1: elemAttr.y, x2: elemAttr.x + elemAttr.width, y2: elemAttr.y + elemAttr.height, tooltext: bandInfo.toolText, tolerance: elemAttr['stroke-width'] < 5 ? 2.5 : elemAttr['stroke-width'] / 2, isTrendZone: 1 }); } element = this.addGraphicalElement(bandElemId, animationManager.setAnimation({ container: container, el: element || 'rect', attr: elemAttr, component: this, label: 'rect' })); // do no assign implicit tooltip for trendlines for zoomscatter if (!/zoomscatter/i.test(chartType)) { if (bandInfo.toolText) { toolTipController.enableToolTip(element, bandInfo.toolText); } else { toolTipController.disableToolTip(element); } } for (key in handlers) { if (handlers.hasOwnProperty(key)) { element.on(key, handlers[key].bind(axis)); } } return [bandElemId]; }; AxisRefVisual.prototype.removeExtraElements = function removeExtraElements(newMap) { var oldMap = this.config.map, key = void 0, idArr = void 0, i = void 0, len = void 0, removingElement = void 0, removeElemId = void 0; for (key in oldMap) { if (!newMap[key]) { idArr = oldMap[key]; len = idArr.length; for (i = 0; i < len; ++i) { removingElement = this.getGraphicalElement(idArr[i]); removingElement && this.removeGraphicalElement(removingElement); } } else { removeElemId = (0, _diff2['default'])(oldMap[key], newMap[key]); len = removeElemId.length; for (i = 0; i < len; ++i) { removingElement = this.getGraphicalElement(removeElemId[i]); removingElement && this.removeGraphicalElement(removingElement); } } } this.config.map = newMap; }; /** * api which add external event listener to axis to call the draw of ref visuals when * the axis is going to be removed * @param {*} itemName is the id * @param {*} item is linked item */ AxisRefVisual.prototype.setLinkedItem = function setLinkedItem(itemName, item) { _ComponentInterface.prototype.setLinkedItem.call(this, itemName, item); var axisRefComp = this; if (item.getType() === 'axis') { axisRefComp.addExtEventListener('preremove', function (event) { axisRefComp.removeLinkedItem(event.sender.getId()); axisRefComp.asyncDraw(); }, item); } }; AxisRefVisual.prototype.addexplicitDrawItems = function addexplicitDrawItems(key, item) { this.config.explicitDrawItems[key] = item; }; AxisRefVisual.prototype.getexplicitDrawItems = function getexplicitDrawItems() { return this.config.explicitDrawItems; }; AxisRefVisual.prototype.resetexplicitDrawItems = function resetexplicitDrawItems() { this.config.explicitDrawItems = {}; }; AxisRefVisual.prototype.isCanvasChnaged = function isCanvasChnaged() { var canvasDim = this.getLinkedParent().getEffectiveDimensions(), axisRefConf = this.config, isCanvasChnaged = void 0; isCanvasChnaged = JSON.stringify(canvasDim) !== JSON.stringify(axisRefConf.canvasDim); axisRefConf.canvasDim = canvasDim; return isCanvasChnaged; }; return AxisRefVisual; }(_componentInterface.ComponentInterface); exports['default'] = AxisRefVisual; /***/ }), /* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesianAxis = __webpack_require__(381); exports['default'] = { 'initial.axisRefVisuals.axisRefVisualsCartesian': _cartesianAxis.axisAnimationAxis, 'update.axisRefVisuals.axisRefVisualsCartesian': _cartesianAxis.axisAnimationFinal }; /***/ }), /* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var canvas, canvasArr = chart.getChildren('canvas'), canvasLen = canvasArr.length, vCanvas, xAxis = [], yAxis = [], axes, l, i, k, j; for (l = 0; l < canvasLen; l++, xAxis = [], yAxis = []) { canvas = canvasArr[l]; if (canvas.getState('removed')) { continue; } axes = canvas.getFromEnv('xAxis'); for (k = 0; k < (axes && axes.length); k++) { if (!axes[k].getState('removed')) { xAxis.push(axes[k]); } } axes = canvas.getFromEnv('yAxis'); for (k = 0; k < (axes && axes.length); k++) { if (!axes[k].getState('removed')) { yAxis.push(axes[k]); } } (0, _lib.componentFactory)(canvas, _vcanvas2['default'], 'vCanvas', xAxis.length * yAxis.length); vCanvas = canvas.getChildren('vCanvas'); for (i = 0, k = 0; i < (xAxis && xAxis.length); i++) { for (j = 0; j < (yAxis && yAxis.length); j++, k++) { vCanvas[k].xAxis(xAxis[i]).yAxis(yAxis[j]).canvas(canvas); vCanvas[k].configure(); vCanvas[k].addToEnv('vCanvas', vCanvas[k]); } } } }; var _vcanvas = __webpack_require__(428); var _vcanvas2 = _interopRequireDefault(_vcanvas); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var setterGetter = function setterGetter(key, value) { key = 'comp_' + key; value && (this.config[key] = value); return (value || !this.config[key]) && this || this.config[key]; }, _getTranslationString = function _getTranslationString(scaleX, scaleY) { return ['T', scaleX, ',', scaleY].join(''); }, _getTranslation = function _getTranslation(axis) { return -axis.getTranslation(); }, // global = this, // Calculate final transform string based on both axis calculateTranslation = function calculateTranslation(axes) { return _getTranslationString(_getTranslation(axes.h), _getTranslation(axes.v)); }, // Simple function to get object // based on parameters getHVOb = function getHVOb(h, v) { return { h: h, v: v }; }, groupsArr = ['columnShadowVcanvasGroup', 'columnVcanvasGroup', 'areaShadowVcanvasGroup', 'areaVcanvasGroup', 'lineShadowVcanvasGroup', 'lineVcanvasGroup', 'defaultShadowVcanvasGroup', 'defaultVcanvasGroup', 'sumLabelsLayer', 'vcanvasLabelGroup'], /** * Helper function to create a RedRaphael group. * @param {string} groupName Name of the group to be created. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} dataset The concerned dataset * @return {Element} The group that was created. */ createGroup = function createGroup(groupName, parentContainer, vCanvas) { var animationManager = vCanvas.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: { name: groupName }, container: parentContainer, state: 'appearing', component: vCanvas, label: 'group' }); }, UNDEF, limitToBeUpdated = function limitToBeUpdated(axis) { return !/category/i.test(axis.getName()); }; var VISIBLE = 'visible', REMOVED = 'removed', DATASET = 'dataset'; /** *

VCanvas

*

Requirement

* vCanvas is a component that was introduced to centralize all scrolling and add new capabilities * to chart like multiple canvas. *

Concept

* Every vCanvas has always only one x-axis and one y-axis attached to it but multiple vcanvas can be * linked to one axis. And any number of datasets can attach themselves * to a vcanvas. * When a axis scrolls all vcanvas linked to that axis scrolls and all dataset attached to that vcanvas * also scrolls. * * Example: * * Assume there are 3 x-Axis : x1, x2, x3 * * and 2 y-Axis y1 and y2. * * There are 3 vcanvas v1, v2, v3 * * who are attached to axes in these manner: * * - v1 - x1 and y1 * - v2 - x1 and y2 * - v3 - x2 and y2 * * And there are 4 dataset d1, d2, d3, d4 * * attached to vanvas in these manner: * - d1 - v1 * - d2 - v2 * - d3 - v1 * - d4 - v3 * * When axis x1 scroll: * - v1 and v2 are attached to x1 so they will scroll * - d1 and d3 are attached to v1 and d2 is attached to v2 so they d1, d2, d3 will scroll. */ var VirtualCanvas = function (_ComponentInterface) { _inherits(VirtualCanvas, _ComponentInterface); function VirtualCanvas() { _classCallCheck(this, VirtualCanvas); return _possibleConstructorReturn(this, _ComponentInterface.apply(this, arguments)); } /** * Sets the name of the component * @return {string} name */ VirtualCanvas.prototype.getName = function getName() { return 'virtualCanvas'; }; /** * Sets the type of the component * @return {string} type */ VirtualCanvas.prototype.getType = function getType() { return 'canvas'; }; /** * Setter getter for xAxis * @param {Object} xAxis x-axis * @return {Object} xAxis reference */ VirtualCanvas.prototype.xAxis = function xAxis(_xAxis) { var axis = setterGetter.call(this, 'xAxis', _xAxis); _xAxis && this.listenToAxis(_xAxis); _xAxis && this.addToEnv('xAxis', _xAxis); return axis; }; /** * Setter getter for yAxis * @param {Object} yAxis yAxis * @return {Object} yAxis reference */ VirtualCanvas.prototype.yAxis = function yAxis(_yAxis) { var axis = setterGetter.call(this, 'yAxis', _yAxis); _yAxis && this.listenToAxis(_yAxis); _yAxis && this.addToEnv('yAxis', _yAxis); return axis; }; /** * Setter getter for paper * @param {Object} paper */ VirtualCanvas.prototype.paper = function paper(_paper) { return setterGetter.call(this, 'paper', _paper); }; /** * Setter getter for canvas * @param {Object} canvas */ VirtualCanvas.prototype.canvas = function canvas(_canvas) { return setterGetter.call(this, 'canvas', _canvas); }; /** * function to configure itself and its children */ VirtualCanvas.prototype.configure = function configure() { var conf = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var vCanvas = this, chartConfig = vCanvas.getFromEnv('chartConfig'), config = vCanvas.config; Object.assign(config, conf); config.transposeAxis = chartConfig.transposeAxis; this._mapChildren(function (child) { if (child.getState(REMOVED) || child.getType() === DATASET) { return; } child.configure && child.configure(); }); }; VirtualCanvas.prototype.getHorizontalVerticalAxes = function getHorizontalVerticalAxes() { var vcanvas = this, xAxis = vcanvas.xAxis(), yAxis = vcanvas.yAxis(); // Returning axes based on who is // horizontal or vertical return yAxis.config.isVertical ? getHVOb(xAxis, yAxis) : getHVOb(yAxis, xAxis); }; VirtualCanvas.prototype.preDraw = function preDraw() { this._mapChildren(function (child) { if (child.getState('removed') || child.getType() === 'dataset') { return; } child.setVisibility && child.setVisibility(); }); var transposeAxis = this.config.transposeAxis, limit = void 0, chart = this.getFromEnv('chart'), _getAxisValuePadding = this.getAxisValuePadding(), left = _getAxisValuePadding.left, right = _getAxisValuePadding.right, top = _getAxisValuePadding.top, bottom = _getAxisValuePadding.bottom; limit = this.getDataLimits(!transposeAxis); // store initial limits for drag charts will only be stored during initial draw if (limit.min !== Infinity || limit.max !== -Infinity) { this._setYAxisLimits(limit.min, limit.max); chart._storeIntialLimit && chart._storeIntialLimit(limit.min, limit.max); } else { this._setYAxisLimits(UNDEF, UNDEF); chart._storeIntialLimit && chart._storeIntialLimit(UNDEF, UNDEF); } this._setXAxisLimits(limit.xMin, limit.xMax); // axis value padding will be set after the limit of the axis has been set this._setAxisValuePadding(left, right, top, bottom); }; /** * function to accomodate the changes of its child and notify its parent for further action if its needed * @param {Object} updateInfo is an object with the informations about the changes in its child */ VirtualCanvas.prototype.childChanged = function childChanged() { var updateInfo = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var vCanvas = this, config = vCanvas.config, transposeAxis = config.transposeAxis, range = void 0; if (updateInfo.dataLimitChanged !== false) { // if datalimit is changed then we will get the datalimits of the axis based on transposeaxis range = vCanvas.getDataLimits(!transposeAxis); if (transposeAxis && (range.min !== config.range.min || range.max !== config.range.max)) { config.range.min = range.min; config.range.max = range.max; // reset the limits when child is chnaged during legend interaction this.getFromEnv('yAxis').resetStoredLimits(); // When all the child (dataset) is hidden then we reset the yaxis limits range.min !== Infinity || range.max !== -Infinity ? vCanvas._setYAxisLimits(range.min, range.max) : vCanvas._setYAxisLimits(UNDEF, UNDEF); } if (range.xMin !== config.range.xMin || range.xMax !== config.range.xMax) { config.range.xMin = range.xMin; config.range.xMax = range.xMax; // reset the limits when child is chnaged during legend interaction this.getFromEnv('xAxis').resetStoredLimits(); vCanvas._setXAxisLimits(range.xMin, range.xMax); } } vCanvas.asyncDraw(); }; VirtualCanvas.prototype._setAxisValuePadding = function _setAxisValuePadding(left, right, top, bottom) { this.getFromEnv('xAxis').setAxisPadding(left, right); top && bottom && this.getFromEnv('yAxis').setAxisPadding(left, right); }; VirtualCanvas.prototype.getAxisValuePadding = function getAxisValuePadding() { var paddingObj = {}, axisPaddingLeft = -Infinity, axisPaddingRight = -Infinity, axisPaddingTop = -Infinity, axisPaddingBottom = -Infinity; this._mapChildren(function (child) { if (child.getState(REMOVED)) { return; } paddingObj = child.getAxisValuePadding && child.getAxisValuePadding() || {}; axisPaddingLeft = Math.max(axisPaddingLeft, paddingObj.left || -Infinity); axisPaddingRight = Math.max(axisPaddingRight, paddingObj.right || -Infinity); axisPaddingTop = Math.max(axisPaddingTop, paddingObj.top || -Infinity); axisPaddingBottom = Math.max(axisPaddingBottom, paddingObj.bottom || -Infinity); }); if (axisPaddingLeft === -Infinity) { axisPaddingLeft = 0; } if (axisPaddingRight === -Infinity) { axisPaddingRight = 0; } if (axisPaddingTop === -Infinity) { axisPaddingTop = 0; } if (axisPaddingBottom === -Infinity) { axisPaddingBottom = 0; } if (!this.config.padding) { this.config.padding = {}; this.config.padding.left = axisPaddingLeft; this.config.padding.right = axisPaddingRight; this.config.padding.top = axisPaddingTop; this.config.padding.bottom = axisPaddingBottom; } return { left: axisPaddingLeft, right: axisPaddingRight, top: axisPaddingTop, bottom: axisPaddingBottom }; }; VirtualCanvas.prototype._setYAxisLimits = function _setYAxisLimits(min, max) { var yAxis = this.getFromEnv('yAxis'); limitToBeUpdated(yAxis) && yAxis.setDataLimit(max, min); }; VirtualCanvas.prototype._setXAxisLimits = function _setXAxisLimits(xMin, xMax) { var xAxis = this.getFromEnv('xAxis'); if (limitToBeUpdated(xAxis)) { xMax !== -Infinity || xMin !== +Infinity ? xAxis.setDataLimit(xMax, xMin) : xAxis.setDataLimit(UNDEF, UNDEF); } }; VirtualCanvas.prototype.getDataLimits = function getDataLimits(allVisible) { var vcanvas = this, chart = vcanvas.getFromEnv('chart'), infMin = -Infinity, infMax = +Infinity, max = infMin, min = infMax, xMin = infMax, xMax = infMin, maxminObj, xMaxValue, xMinValue, getMaxMin = function getMaxMin(_maxminObj) { xMaxValue = (0, _lib.pluck)(_maxminObj.xMax, infMin); xMinValue = (0, _lib.pluck)(_maxminObj.xMin, infMax); max = Math.max(max, _maxminObj.max); min = Math.min(min, _maxminObj.min); xMax = Math.max(xMax, xMaxValue); xMin = Math.min(xMin, xMinValue); }; vcanvas._mapChildren(function (child) { // if the child is removed or the child (dataset) is not visible then no need to fetch data limits if (!child.getDataLimits || child.getState(REMOVED) || !allVisible && !child.getState(VISIBLE)) { return; } maxminObj = child.getDataLimits(allVisible); getMaxMin(maxminObj); }); // (max === -Infinity) && (max = 0); // (min === +Infinity) && (min = 0); if (!this.config.range) { this.config.range = {}; this.config.range.min = min; this.config.range.max = max; this.config.range.xMin = xMin; this.config.range.xMax = xMax; } chart.config.yMax = max; chart.config.yMin = min; return { min: min, max: max, xMin: xMin, xMax: xMax }; }; // event listeners /** * Set a listener to axis so that any change in visible range could be catched and * proper action should be taken * @param {Axis} axis */ VirtualCanvas.prototype.listenToAxis = function listenToAxis(axis) { var vcanvas = this, axisScrollFn; axisScrollFn = function axisScrollFn() { if (vcanvas.getState('drawn')) { vcanvas.asyncDraw(); } }; /** * Multiple listeners were attached on updating chart. As a consequence, allocatePosition API of dataset * was being multiple times. * Fix: Only attach listeners when the chart is in initial state. No listeners will be attached on update * and resize */ if (!this.getState('visiblerangeset' + axis.getId())) { this.setState('visiblerangeset' + axis.getId(), true); vcanvas.addExtEventListener('visiblerangeset', axisScrollFn, axis); } }; /** * Get or create containers that will be parent containers of datasets */ VirtualCanvas.prototype.createContainer = function createContainer() { var vcanvas = this, canvas = vcanvas.getLinkedParent(); !vcanvas.getChildContainer('columnShadowVcanvasGroup') && vcanvas.addChildContainer('columnShadowVcanvasGroup', createGroup('vcanvas-column-shadow', canvas.getChildContainer('columnShadowGroup'), vcanvas)); !vcanvas.getChildContainer('columnVcanvasGroup') && vcanvas.addChildContainer('columnVcanvasGroup', createGroup('vcanvas-column-plot', canvas.getChildContainer('columnGroup'), vcanvas)); !vcanvas.getChildContainer('areaShadowVcanvasGroup') && vcanvas.addChildContainer('areaShadowVcanvasGroup', createGroup('vcanvas-area-shadow', canvas.getChildContainer('areaShadowGroup'), vcanvas)); !vcanvas.getChildContainer('areaVcanvasGroup') && vcanvas.addChildContainer('areaVcanvasGroup', createGroup('vcanvas-area-plot', canvas.getChildContainer('areaGroup'), vcanvas)); !vcanvas.getChildContainer('lineShadowVcanvasGroup') && vcanvas.addChildContainer('lineShadowVcanvasGroup', createGroup('vcanvas-line-shadow', canvas.getChildContainer('lineShadowGroup'), vcanvas)); !vcanvas.getChildContainer('lineVcanvasGroup') && vcanvas.addChildContainer('lineVcanvasGroup', createGroup('vcanvas-line-plot', canvas.getChildContainer('lineGroup'), vcanvas)); !vcanvas.getChildContainer('defaultShadowVcanvasGroup') && vcanvas.addChildContainer('defaultShadowVcanvasGroup', createGroup('vcanvas-default-shadow', canvas.getChildContainer('defaultShadowGroup'), vcanvas)); !vcanvas.getChildContainer('defaultVcanvasGroup') && vcanvas.addChildContainer('defaultVcanvasGroup', createGroup('vcanvas-default-plot', canvas.getChildContainer('defaultGroup'), vcanvas)); !vcanvas.getChildContainer('vcanvasLabelGroup') && vcanvas.addChildContainer('vcanvasLabelGroup', createGroup('vcanvas-label', canvas.getChildContainer('datalabelsGroup'), vcanvas)); !vcanvas.getChildContainer('columnTrendGroup') && vcanvas.addChildContainer('columnTrendGroup', createGroup('columnTrendGroup', vcanvas.getChildContainer('columnVcanvasGroup'), vcanvas)); !vcanvas.getChildContainer('sumLabelsLayer') && vcanvas.addChildContainer('sumLabelsLayer', createGroup('vcanvas-sumLabelsLayer', canvas.getChildContainer('sumLabelsLayer'), vcanvas)); }; // Apply translation VirtualCanvas.prototype.applyTranslation = function applyTranslation() { var vcanvas = this, axes = vcanvas.getHorizontalVerticalAxes(), translation = calculateTranslation(axes), pushAnimData = function pushAnimData(el) { el = vcanvas.getChildContainer(el); // Changing the vCanvas translation via attr as internally it is executed as 0 animation. As a result we can // apply translation on vCanvas el.attr({ transform: translation }); }; // Creating container vcanvas.createContainer(); groupsArr.forEach(function (val) { pushAnimData(val); }); }; // Calculate zooming or panning VirtualCanvas.prototype.draw = function draw() { // apply translation this.applyTranslation(); this.setState('drawn', true); }; /** * function to return canvas padding by calculating the max padding need to be applied * @return {{paddingLeft : Number, paddingRight: Number, paddingTop: Number, paddingBottom: Number}} */ VirtualCanvas.prototype.getCanvasPadding = function getCanvasPadding() { var iapi = this, dim, key, returnDimension = { paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 }; iapi._mapChildren(function (child) { if (!child.getCanvasPadding || child.getState(REMOVED)) { return; } dim = child.getCanvasPadding() || {}; for (key in dim) { if (dim.hasOwnProperty(key)) { returnDimension[key] = Math.max(dim[key], returnDimension[key]); } } }); return returnDimension; }; /** * Used in realtime scenarios, to make the realtime animation look proper */ VirtualCanvas.prototype.rtShiftAnim = function rtShiftAnim(x, y) { var vcanvas = this, translateString, xAxis = vcanvas.getFromEnv('xAxis'), yAxis = vcanvas.getFromEnv('yAxis'), xDiff = xAxis.getPixel(1) - xAxis.getPixel(0), yDiff = yAxis.getPixel(1) - yAxis.getPixel(0), animationManager = vcanvas.getFromEnv('animationManager'); x = (x || 0) * xDiff; y = (y || 0) * yDiff; translateString = _getTranslationString(x, y); groupsArr.forEach(function (val) { vcanvas.getChildContainer(val).attr({ transform: translateString }); animationManager.setAnimation({ el: vcanvas.getChildContainer(val), attrs: { transform: 'T0,0' } }); }); }; return VirtualCanvas; }(_componentInterface.ComponentInterface); exports['default'] = VirtualCanvas; /***/ }), /* 429 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var mouseTracker = void 0; if (chart.config.enablemousetracking) { (0, _lib.componentFactory)(chart, _mouseTracker2['default'], 'mouseTracker'); mouseTracker = chart.getChildren('mouseTracker')[0]; // if mouse tracker events are already added then do not add the events if (!chart.config.mouseTrackerEventAdded) { mouseTracker.addEvents(); chart.config.mouseTrackerEventAdded = true; } } else { mouseTracker = chart.getChildren('mouseTracker') && chart.getChildren('mouseTracker')[0]; mouseTracker && mouseTracker._removeListners(); chart.config.mouseTrackerEventAdded = false; } }; var _mouseTracker = __webpack_require__(430); var _mouseTracker2 = _interopRequireDefault(_mouseTracker); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 430 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * A derived event generated as a result of a sequence of actual events. * @typedef {Object} DerivedEvent * @property {boolean} fireOut Indicates whether the event results in the mouse moving out of a * component * @property {Array} events The sequence of events that led to this derived event */ var MOUSEOVER = 'fc-mouseover', MOUSEDOWN = 'fc-mousedown', MOUSEUP = 'fc-mouseup', MOUSEMOVE = 'fc-mousemove', MOUSEOUT = 'fc-mouseout', CLICK = 'fc-click', UNDEF; /** * The MouseTracker component is responsible for attaching mouse events on the chart and deciding * what event to fire under which situation. For example, it tracks mouse movement inside the chart * and when the mouse moves inside one plot and out of another, it derives that the mouse has * entered on plot and left another. * @class */ var MouseTracker = function (_ComponentInterface) { _inherits(MouseTracker, _ComponentInterface); /** * When instantiating MouseTracker, it needs to be provided an instance of the chart on which it will add events. */ function MouseTracker() { _classCallCheck(this, MouseTracker); var _this2 = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this2.pIndex = 1; _this2.handler = function (_this) { return function (e) { // call the handler only for trusted events e.originalEvent && _this.getFromEnv('chart')._mouseEvtHandler(e, _this.config.evtData); }; }(_this2); _this2.eventsList = [MOUSEDOWN, MOUSEUP, MOUSEMOVE, CLICK, MOUSEOVER]; _this2.config = {}; _this2.config.evtData = {}; return _this2; } /** * Given the event object, the index of the dataset and the index of the plot in the dataset, this * method determines which event has occured on a dataset's plot * @param {Event} e original mouse event that is being trapped * @param {number} datasetIndex Index of the dataset that is being interacted * @param {number} plotIndex Index of the plot that is being interacted * @return {DerivedEvent} An object containg the details of the mouse events that need to be fired * @todo has scope to reduce no of line */ MouseTracker.prototype.getMouseEvents = function getMouseEvents(e, datasetIndex, plotIndex) { var mouseTracker = this, lastDatasetIndex = mouseTracker._lastDatasetIndex, lastPointIndex = mouseTracker._lastPointIndex, eventType = e.type, derivedEvensInfo = { fireOut: false, events: [] }; switch (eventType) { case CLICK: derivedEvensInfo.events.push(CLICK); break; case MOUSEMOVE: if (lastDatasetIndex === datasetIndex && lastPointIndex === plotIndex) { // clear mouseout timer(if any) if mousemove happens over the same plot clearTimeout(mouseTracker.mouseoutTimer); derivedEvensInfo.events.push(MOUSEMOVE); } else { derivedEvensInfo.events.push(MOUSEOVER); derivedEvensInfo.fireOut = true; } break; case MOUSEDOWN: if (lastDatasetIndex !== datasetIndex || lastPointIndex !== plotIndex) { derivedEvensInfo.fireOut = true; derivedEvensInfo.events.push(MOUSEOVER); } derivedEvensInfo.events.push(MOUSEDOWN); break; case MOUSEOVER: if (lastDatasetIndex === datasetIndex && lastPointIndex === plotIndex) { // clear mouseout timer(if any) if mouseover happens over the same plot clearTimeout(mouseTracker.mouseoutTimer); } else { // when hovering over an element that lies over the last hovered element the fireout the last hovered element derivedEvensInfo.fireOut = true; derivedEvensInfo.events.push(MOUSEOVER); } break; case MOUSEUP: mouseTracker.hasTouchEvent = false; derivedEvensInfo.events.push(MOUSEUP); // @todo: implement clcik from mouseend as well break; case MOUSEOUT: derivedEvensInfo.fireOut = true; } return derivedEvensInfo; }; /** * This method simply removes previously added listeners and adds all events in its event list to * the chart */ MouseTracker.prototype.addEvents = function addEvents() { var mouseTracker = this, chart = mouseTracker.getFromEnv('chart'), allCanvas = chart.getChildren('canvas'), canvas, evtData = mouseTracker.config.evtData, eventsList = mouseTracker.eventsList, i, eventIndex; chart.config.enableMouseOutEvent && eventsList.push(MOUSEOUT); // Remove old listners mouseTracker._removeListners(); evtData.chart = chart; evtData.mouseTracker = mouseTracker; for (i = 0; i < allCanvas.length; i++) { canvas = allCanvas[i]; // Attach all related mouse / touch events. for (eventIndex in eventsList) { canvas.addEventListener(eventsList[eventIndex], mouseTracker.handler); } } }; /** * Removes all event listeners added to the chart, if any * @private */ MouseTracker.prototype._removeListners = function _removeListners() { var mouseTracker = this, chart = mouseTracker.getFromEnv('chart'), allCanvas = chart.getChildren('canvas'), canvas, eventsList = mouseTracker.eventsList, eventIndex, i; // remove all previously attached events for (i = 0; i < allCanvas.length; i++) { canvas = allCanvas[i]; // Remove all related mouse / touch events. for (eventIndex in eventsList) { canvas.removeEventListener(eventsList[eventIndex], mouseTracker.handler); } } mouseTracker._removeDocEvents(); }; /** * Function to remove the eventListeners attached on the doc */ MouseTracker.prototype._removeDocEvents = function _removeDocEvents() { this.eventOutput && this.eventOutput.unlisten(); this.eventOutput = UNDEF; }; /** * This method is used to remove all event listeners attached by MouseTracker to the chart. */ MouseTracker.prototype._dispose = function _dispose() { this._removeListners(); _ComponentInterface.prototype._dispose.call(this); }; return MouseTracker; }(_componentInterface.ComponentInterface); exports['default'] = MouseTracker; /***/ }), /* 431 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var children = chart.getChildren(), canvas = children.canvas && children.canvas[0], vCanvas = canvas && canvas.getChildren('vCanvas'), datasetParent = vCanvas && vCanvas[0] || canvas || chart, dataObj = chart.getFromEnv('dataSource'), dataset = dataObj.dataset, data = dataObj.data || dataset && dataset[0].data, DSClass = void 0, datasetJSON = void 0; datasetJSON = _dataSegregator(data); if (!(data && data.length !== 0)) { chart.setChartMessage(); return; } DSClass = chart.getDSdef(); (0, _lib.datasetFactory)(datasetParent, DSClass, 'dataset', 1, [datasetJSON]); }; var _lib = __webpack_require__(125); var TRUE_STRING = 'true', ONE_STRING = '1', /** * Seggregates the original data to data and vline. * @param {Object} data Original data used for seggregation. * @return {Object} JSON data to be used further by the child components, e.g. dataSet. */ _dataSegregator = function _dataSegregator(data) { var dataOnlyArr = [], catOnlyArr = []; (0, _lib.fcEach)(data, function (datum, i) { if (!(datum.vline === TRUE_STRING || datum.vline === true || datum.vline === 1 || datum.vline === ONE_STRING)) { dataOnlyArr.push(datum); } else { catOnlyArr.push({ index: i, data: datum }); } }); return { catData: catOnlyArr, data: dataOnlyArr }; }; /** * function to create dataset. * assign dataset to vCanvas. * @param {Object} chart chart API **/ /***/ }), /* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports._removePlots = undefined; var _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(433); var _index2 = _interopRequireDefault(_index); var _schedular = __webpack_require__(136); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var UNDEF = void 0, MOUSEOVER = 'mouseOver', MOUSEOUT = 'mouseOut', ROLLOVER = 'DataPlotRollOver', ROLLOUT = 'DataPlotRollOut', HTP = _lib.hasTouch ? _lib.TOUCH_THRESHOLD_PIXELS : _lib.CLICK_THRESHOLD_PIXELS, dropHash = _lib.regex.dropHash, PLOTBORDERCOLOR = 'plotBorderColor', PLOTGRADIENTCOLOR = 'plotGradientColor', SHOWSHADOW = 'showShadow', POINTER = 'pointer', EVENTARGS = 'eventArgs', DEFAULT_CURSOR = _lib.preDefStr.DEFAULT, showHoverEffectStr = _lib.preDefStr.showHoverEffectStr, SETROLLOVERATTR = _lib.preDefStr.setRolloverAttrStr, SETROLLOUTATTR = _lib.preDefStr.setRolloutAttrStr, math = Math, mathMin = math.min, mathMax = math.max, mathAbs = math.abs, crispTop = { 'top': true }, crispRight = { 'right': true }, crispLeft = { 'left': true }, crispBottom = { 'bottom': true }, mathCeil = math.ceil, mathRound = math.round, _graphicsIterator = function _graphicsIterator() { var store = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = arguments[1]; if (typeof callback !== 'function') { return; } var _loop = function _loop(key) { if (store.hasOwnProperty(key)) { var elems = store[key]; if (Array.isArray(elems)) { elems.forEach(function (el) { return callback(el, key); }); } else { store[key] && callback(store[key], key); } } }; for (var key in store) { _loop(key); } }, _rolloverResponseSetter = function _rolloverResponseSetter(chart, data, event, onlyHoverEffect, dataset) { var dataGraphics = data.graphics, elem = dataGraphics && dataGraphics.element, animationManager = chart.getFromEnv('animationManager'), elData = elem && elem.getData(); // Check whether the plot is in dragged state or not if // drag then dont fire rolloverevent if (elData.draged !== true) { if (elem && elData.showHoverEffect !== 0) { animationManager.setAnimationState(MOUSEOVER); animationManager.setAnimation({ el: elem, label: 'rect', component: dataset, attr: elem.getData().setRolloverAttr }); } !onlyHoverEffect && elem && chart.plotEventHandler(elem, event, ROLLOVER); } }, _rolloutResponseSetter = function _rolloutResponseSetter(chart, data, event, onlyHoverEffect, dataset) { var dataGraphics = data.graphics, elem = dataGraphics && dataGraphics.element, animationManager = chart.getFromEnv('animationManager'), elData = elem && elem.getData(); // Check whether the plot is in draggedstate or not if drag then dont fire rolloutevent if (elData.draged !== true) { if (elem && elData.showHoverEffect !== 0) { animationManager.setAnimationState(MOUSEOUT); animationManager.setAnimation({ el: elem, label: 'rect', component: dataset, attr: elem.getData().setRolloutAttr }); } !onlyHoverEffect && elem && chart.plotEventHandler(elem, event, ROLLOUT); } }, /** * Helper function to create a RedRaphael group. * @param {string} groupName Name of the group to be created. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} dataset The concerned dataset * @return {Element} The group that was created. */ createGroup = function createGroup(groupName, parentContainer, dataset) { var animationManager = dataset.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: { name: groupName }, container: parentContainer, state: 'appearing', component: dataset, label: 'group' }); }, /** * removes the graphics of removedData. * removedData contains all the data objects which are not required anymore * * @param {Array} removeDataArr - array consisting of data object which are to be cleaned * @param {function} removeElem - api to handle the removal */ _removePlots = function _removePlots() { var removeDataArr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var removeElem = arguments[1]; removeDataArr.forEach(function (removeData) { return _graphicsIterator(removeData && removeData.graphics, removeElem); }); removeDataArr.length = 0; }; (0, _dependencyManager.addDep)({ name: 'columnAnimation', type: 'animationRule', extension: _index2['default'] }); /** * This is the base class(Column class) which is inhereited by the other classes. */ var ColumnDataset = function (_ComponentInterface) { _inherits(ColumnDataset, _ComponentInterface); /** * constructor function this class */ function ColumnDataset() { _classCallCheck(this, ColumnDataset); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); var ds = _this; ds.components = {}; ds.components.removeDataArr = []; ds.__hideElem = function (el, type) { ds._setRemoveAnim(el, type === 'label' ? 'plotLabel' : 'rect'); }; ds.__removeElem = function (el, type) { ds.__hideElem(el, type); }; ds.config.primitiveType = 'column'; return _this; } /** * Sets the type of the component * @return {string} type */ ColumnDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ ColumnDataset.prototype.getName = function getName() { return 'column'; }; /** * parse defualt configuration of the chart */ ColumnDataset.prototype.__setDefaultConfig = function __setDefaultConfig() { _ComponentInterface.prototype.__setDefaultConfig.call(this); var config = this.config; config.showvalues = UNDEF; config.includeinlegend = 1; config.plotfillalpha = UNDEF; config.plotfillangle = UNDEF; config.ratio = UNDEF; }; /** * preConfigure function for dataset * * @param {Object} datasetJSON JSON for dataset configurations * @return {boolean} Indicates whether the configuration was successful or not */ ColumnDataset.prototype.preConfigure = function preConfigure(datasetJSON) { var dataSet = this; if (!datasetJSON) { return false; } dataSet.trimData(datasetJSON); dataSet.config.JSONData = datasetJSON; _ComponentInterface.prototype.preConfigure.call(this, datasetJSON); }; /** * sets the skipping information for the given data set * @param {Object} skipInfo contains skipping info of the dataset */ ColumnDataset.prototype.setSkippingInfo = function setSkippingInfo(skipInfo) { this.addToEnv('skipInfo', skipInfo || { plotsPerBin: 1, drawOnlyMap: [], draw: [], hide: [], skippingApplied: false, dragHashMap: [] }); }; /** * method to get the skipping information of the dataset * @return {Object} contains the skipping information of the dataset */ ColumnDataset.prototype.getSkippingInfo = function getSkippingInfo() { return this.getFromEnv('skipInfo') || { plotsPerBin: 1, drawOnlyMap: [], // draw index map draw: [], // indeies of allowed data for drawing hide: [], // indeies of allowed data for hiding skippingApplied: false, dragHashMap: [] }; }; /** * Configure function for dataset * * @param {Object} datasetJSON JSON for dataset configurations * @return {boolean} Indicates whether the configuration was successful or not */ ColumnDataset.prototype.configure = function configure(datasetJSON) { if (!datasetJSON) { return false; } _ComponentInterface.prototype.configure.call(this, datasetJSON); }; /** * Function for parsing all the attributes and value given by the user at chart,dataset and set level. * This function is called once from the init() function of the Column class. */ ColumnDataset.prototype.configureAttributes = function configureAttributes() { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config; dataSet.parseAttributes(); dataSet._setConfigure(); if (dataSet.getState('visible') && conf.oldVisible === false) { conf.appearing = true; } conf.oldVisible = dataSet.getState('visible'); dataSet._realTimeConfigure && dataSet._realTimeConfigure(); chart.config.hasLegend !== false && chart.config.showLegend && dataSet._addLegend(); dataSet.ErrorValueConfigure && dataSet.ErrorValueConfigure(); dataSet.config.YForStackUpdated = false; dataSet.setState('dirty', true); }; ColumnDataset.prototype.parseAttributes = function parseAttributes() { var dataSet = this, chart = dataSet.getFromEnv('chart'), yaxis = chart.getChildren('yAxis')[0], isInverseAxis = yaxis.config.isReverse, conf = dataSet.config, JSONData = dataSet.config.JSONData, singleSeries = chart.config.singleseries, chartConfig = chart.config, chartAttr = chart.getFromEnv('dataSource').chart, colorM = dataSet.getFromEnv('color-manager'), index = dataSet.getJSONIndex(), plotColor = conf.plotColor = colorM.getPlotColor(index), plotBorderDash = (0, _lib.pluckNumber)(JSONData.dashed, chartAttr.plotborderdashed), usePlotGradientColor = (0, _lib.pluckNumber)(chartAttr.useplotgradientcolor, 1), plotDashLen = void 0, plotDashGap = void 0, plotBorderThickness = void 0, plotFillAlpha = void 0, // getDashStyle = lib.getDashStyle, isBar = chart.isBar, is3D = chart.config.is3D, isDual = chart.config.isdual; if (isDual) { conf.parentYAxis = (0, _lib.pluck)(JSONData.parentyaxis && JSONData.parentyaxis.toLowerCase(), 'p') === 's' ? 1 : 0; } else { conf.parentYAxis = 0; } conf.maxValue = -Infinity; conf.minValue = Infinity; conf.defaultPadding = { left: 0.5, right: 0.5 }; (0, _lib.parseConfiguration)(JSONData, conf, chartConfig, { data: true }); conf.seriesname = (0, _lib.parseUnsafeString)(JSONData.seriesname); conf.showValues = (0, _lib.pluckNumber)(JSONData.showvalues, chartAttr.showvalues, 1); conf.showplotborder = (0, _lib.pluckNumber)(chartAttr.showplotborder, is3D ? 0 : 1); plotDashLen = chartConfig.plotborderdashlen; plotDashGap = chartConfig.plotborderdashgap; conf.plotfillangle = (0, _lib.pluckNumber)(360 - chartAttr.plotfillangle, isBar ? 180 : isInverseAxis ? 90 : 270); conf.plotfillalpha = plotFillAlpha = (0, _lib.pluck)(JSONData.alpha, chartAttr.plotfillalpha, _lib.HUNDREDSTRING); conf.plotColor = plotColor = (0, _lib.pluck)(JSONData.color, plotColor); conf.legendSymbolColor = (0, _lib.getFirstColor)(conf.plotColor); conf.plotgradientcolor = (0, _lib.getDefinedColor)(chartAttr.plotgradientcolor, colorM.getColor(PLOTGRADIENTCOLOR)); !usePlotGradientColor && (conf.plotgradientcolor = ''); conf.plotborderalpha = (0, _lib.pluck)(chartAttr.plotborderalpha, plotFillAlpha, _lib.HUNDREDSTRING); conf.plotbordercolor = (0, _lib.pluck)(chartAttr.plotbordercolor, is3D && !singleSeries ? '#ffffff' : colorM.getColor(PLOTBORDERCOLOR)); conf.plotborderdashstyle = plotBorderDash ? (0, _lib.getDashStyle)(plotDashLen, plotDashGap, plotBorderThickness) : 'none'; conf.showShadow = is3D ? (0, _lib.pluckNumber)(chartAttr.showshadow, 1) : (0, _lib.pluckNumber)(chartAttr.showshadow, colorM.getColor(SHOWSHADOW)); conf.definedGroupPadding = mathMax(chartConfig.plotSpacePercent, 0); conf.includeinlegend = (0, _lib.pluckNumber)(JSONData.includeinlegend, conf.seriesname ? 1 : 0); dataSet.setState('visible', (0, _lib.pluckNumber)(JSONData.visible, !Number(JSONData.initiallyhidden), 1) === 1); if (dataSet.getState('visible') === true) { dataSet._conatinerHidden = false; } else { dataSet._containerHidden = true; } conf.legendInteractivity = false; dataSet.setState('visible', (0, _lib.pluckNumber)(dataSet.getState('visible'), conf.JSONData.visible, !Number(conf.JSONData.initiallyhidden), 1) === 1); }; /** * function to Remove data plots if the number of current data plots/categories * is more than the existing ones. * @param {Object} datasetJSON JSON for dataset configurations */ ColumnDataset.prototype.trimData = function trimData(datasetJSON) { if (!this.components && this.components.data && this.components.data.length) { return; } var dataSet = this, comps = dataSet.components, config = dataSet.config, context = config && config.context, isRealTime = dataSet.getFromEnv('chart').isRealTime, prevCatlen = context && context.prevCatlen, xAxis = dataSet.getFromEnv('xAxis'), currCatLen = isRealTime ? 0 : xAxis.getTicksLen(), catDiff = prevCatlen - currCatLen, prevData = comps && comps.data, prevDataLength = prevData && prevData.length, currDataLength = datasetJSON.data && datasetJSON.data.length || 0, dataDiff = prevDataLength - currDataLength, diff = void 0, startIndex = void 0; if (catDiff > dataDiff) { diff = catDiff; startIndex = currCatLen; } else { diff = dataDiff; startIndex = currDataLength; } // Removing data plots if the number of current data plots/categories // is more than the existing ones. if (diff > 0) { this.removeData(startIndex, diff, false); } }; /** * method to hide the plots */ ColumnDataset.prototype.hidePlots = function hidePlots() { var dataSet = this, components = dataSet.components, dataStore = components.data, dataObj, skipInfo = dataSet.getSkippingInfo(), hideArray = skipInfo.hide, hideLabelArray = skipInfo.hideLabel; hideArray.forEach(function (v) { dataObj = dataStore[v]; if (dataObj && dataObj.graphics) { _graphicsIterator(dataObj.graphics, dataSet.__removeElem); dataObj && (dataObj.graphics = {}); } }); hideLabelArray.forEach(function (v) { dataObj = dataStore[v]; if (dataObj && dataObj.graphics) { _graphicsIterator(dataObj.graphics, dataSet.__removeElem); dataObj && (dataObj.graphics = {}); } }); }; /** * Function for parsing all the attributes and value given by the user at dataset level. * This function is called once from the configure() function of the Column class. * @param {Object} newDataset JSON for dataset configurations for new data only in a case of realtime chart * @param {number} newIndex JSON for dataset configurations for new data only in a case of realtime chart */ ColumnDataset.prototype._setConfigure = function _setConfigure(newDataset, newIndex) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, conf = dataSet.config, xAxis = dataSet.getFromEnv('xAxis'), isRealTime = chart.isRealTime, numDisplaySets = chartConfig.realTimeConfig && chartConfig.realTimeConfig.numDisplaySets, categories = dataSet.getFromEnv('dataSource').categories && dataSet.getFromEnv('dataSource').categories[0] && dataSet.getFromEnv('dataSource').categories[0].category, catLen = conf.initCatLen = isRealTime ? categories && Array.isArray(categories) && categories.filter(function (data) { return !data.vline; }).length || 0 : xAxis.getTicksLen(), JSONData = conf.JSONData || [], setDataArr = newDataset || JSONData.data, newDataSetLen = newDataset && newDataset.data.length, len, showplotborder = conf.showplotborder, plotBorderThickness = chartConfig.plotborderthickness, setData, plotIndex, dataObj, dataStore = dataSet.components.data, isDrag = chartConfig.isDrag, i, j, shiftIndex, tempIndex, skippingInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), configureOnly = skippingInfo && skippingInfo.draw || [], skippingApplied = skippingInfo && skippingInfo.skippingApplied; // shiftIndex: how much index shift is needed in realtime column charts when numDisplaySets is lesser // than catLen. While on other cases shiftIndex should be 0. So, It will work as it is. shiftIndex = newDataSetLen === UNDEF && catLen > numDisplaySets ? catLen - numDisplaySets : 0; len = isRealTime ? (0, _lib.pluckNumber)(newDataSetLen, catLen) : Math.min(catLen, setDataArr && setDataArr.length); chartConfig.dragTolerance = isDrag ? (showplotborder && plotBorderThickness > 5 ? plotBorderThickness / 2 + 1 : 5) + HTP : 0; if (!dataStore) { dataStore = dataSet.components.data = []; } // Parsing the attributes and values at set level. if (skippingApplied) { len = configureOnly.length; } for (j = shiftIndex; j < len; j++) { i = configureOnly[j] || j; if (newDataset) { setData = newDataset && newDataset.data[i] || {}; if (newIndex !== UNDEF) { tempIndex = newIndex + i; dataObj = dataStore[tempIndex]; } else { tempIndex = dataStore.length - len + i; dataObj = dataStore[tempIndex]; } plotIndex = tempIndex; } else { setData = setDataArr && setDataArr[i] || {}; i = i - shiftIndex; dataObj = dataStore[i]; plotIndex = i; } if (!dataObj) { dataObj = dataStore[plotIndex] = {}; } if (!dataObj.config) { dataObj.config = {}; dataObj.graphics = {}; } dataSet._plotConfigure(plotIndex, setData, newDataSetLen); tempIndex && tempIndex++; } if (skippingApplied) { dataSet.addJob('configureRestID', function () { dataSet._configureRestData(); }, _schedular.priorityList.postRender); } }; /** * method to configure the rest of data that have not been drawn during use of data skipping */ ColumnDataset.prototype._configureRestData = function _configureRestData() { var dataSet = this, conf = dataSet.config, JSONData = dataSet.config.JSONData, setDataArr = JSONData.data, chartAttr = dataSet.getFromEnv('chart-attrib'), xAxis = dataSet.getFromEnv('xAxis'), catLen = xAxis.getTicksLen(), len = catLen, setData, plotIndex, dataObj, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), drawOnlyMap = skipInfo.drawOnlyMap, dataStore = dataSet.components.data, i, tempIndex; if (!dataStore) { dataStore = dataSet.components.data = []; } conf.maxValue = -Infinity; conf.minValue = Infinity; for (i = 0; i < len; i++) { if (drawOnlyMap[i]) { continue; } dataObj = dataStore[i]; setData = setDataArr && setDataArr[i] || {}; plotIndex = i; if (setData.tooltext !== UNDEF) { setData.tooltext = (0, _lib.parseTooltext)(setData.tooltext, [3], { label: setData.label }, setData, chartAttr, JSONData); } if (!dataObj) { dataObj = dataStore[i] = {}; } if (!dataObj.config) { dataStore[i].config = {}; } dataSet._plotConfigure(plotIndex, setData); tempIndex && tempIndex++; } }; /** * method to configure a particular data plot object * @param {number} i index of the data object to be configured * @param {Object} setData particular plot information in of i'th index in input json * @param {number} newDataSetLen new data set length for RT charts */ ColumnDataset.prototype._plotConfigure = function _plotConfigure(i, setData, newDataSetLen) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, conf = dataSet.config, JSONData = conf.JSONData, singleSeries = chart.config.singleseries, yAxis = dataSet.getFromEnv('yAxis'), xAxis = dataSet.getFromEnv('xAxis'), dataStore = dataSet.components.data, dataObj = dataStore[i], chartAttr = chart.getFromEnv('dataSource').chart, colorM = dataSet.getFromEnv('color-manager'), showplotborder = conf.showplotborder, plotColor = conf.plotColor, showTooltip = chartConfig.showtooltip, yAxisName = chartConfig.yaxisname, xAxisName = chartConfig.xaxisname, tooltipSepChar = chartConfig.tooltipsepchar, seriesNameInTooltip = chartConfig.seriesnameintooltip, // parseTooltext = parseTooltext, formatedVal, parserConfig, setTooltext, seriesname, macroIndices, tempPlotfillAngle, toolText, plotDashLen = chartConfig.plotborderdashlen, plotDashGap = chartConfig.plotborderdashgap, plotBorderThickness = chartConfig.plotborderthickness, isRoundEdges = (0, _lib.pluckNumber)(chartConfig.useroundedges, 0), showHoverEffect = chartConfig.plothovereffect, plotfillAngle = conf.plotfillangle, plotFillAlpha, plotFillRatio, plotBorderAlpha, plotBorderDashStyle, initailPlotBorderDashStyle = conf.plotborderdashstyle, setValue, config = dataObj.config, label, colorArr, hoverColor, hoverAlpha, hoverGradientColor, hoverRatio, hoverAngle, hoverBorderColor, hoverBorderAlpha, hoverBorderThickness, hoverBorderDashed, hoverBorderDashGap, hoverBorderDashLen, hoverDashStyle, hoverColorArr, // getDashStyle = lib.getDashStyle, toolTipValue, setDisplayValue, isBar = chart.isBar, is3D = chart.config.is3D, setDataDashed, setDataPlotDashLen, setDataPlotDashGap, origLabel, labelObj, use3dlighting = chartConfig.use3dlighting, numDisplaySets = chartConfig.realTimeConfig && chartConfig.realTimeConfig.numDisplaySets, diffLen = numDisplaySets - conf.initCatLen, additive = numDisplaySets && diffLen >= 0 ? diffLen : 0, useDataPlotColorForLabels = chartConfig.usedataplotcolorforlabels; labelObj = xAxis.getLabel(newDataSetLen ? i - newDataSetLen : additive + i); config.origLabel = origLabel = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(labelObj.label)); label = config.label = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(labelObj.tooltext)) || origLabel; if (setData.tooltext !== UNDEF) { setData.tooltext = (0, _lib.parseTooltext)(setData.tooltext, [3], { label: labelObj.label }, setData, chartAttr, JSONData); } config.showValue = (0, _lib.pluckNumber)(setData.showvalue, conf.showValues); config.setValue = setValue = yAxis.getCleanValue(setData.value, (0, _lib.pluckNumber)(chartConfig.stack100percent)); config.setLink = (0, _lib.pluck)(setData.link); config.toolTipValue = toolTipValue = yAxis.dataLabels(setValue); config.setDisplayValue = setDisplayValue = (0, _lib.parseUnsafeString)(setData.displayvalue); config.displayValue = (0, _lib.pluck)(setDisplayValue, toolTipValue); setDataDashed = (0, _lib.pluckNumber)(setData.dashed); setDataPlotDashLen = (0, _lib.pluckNumber)(setData.dashlen, plotDashLen); setDataPlotDashGap = plotDashGap = (0, _lib.pluckNumber)(setData.dashgap, plotDashGap); if (setValue !== null) { conf.maxValue = mathMax(conf.maxValue, setValue); conf.minValue = mathMin(conf.minValue, setValue); } config.plotBorderDashStyle = plotBorderDashStyle = setDataDashed === 1 ? (0, _lib.getDashStyle)(setDataPlotDashLen, setDataPlotDashGap) : setDataDashed === 0 ? 'none' : initailPlotBorderDashStyle; if (singleSeries) { plotColor = colorM.getPlotColor((0, _lib.pluckNumber)(i - newDataSetLen, i)); plotColor = (0, _lib.pluck)(setData.color, plotColor); useDataPlotColorForLabels && xAxis.updateTicksValues(i, { labelfontcolor: (0, _lib.convertColor)(plotColor) }); plotBorderAlpha = (0, _lib.pluck)(setData.alpha, setData.borderalpha, conf.plotborderalpha, plotFillAlpha).toString(); } else { plotColor = (0, _lib.pluck)(setData.color, conf.plotColor); plotBorderAlpha = (0, _lib.pluck)(setData.alpha, conf.plotborderalpha, plotFillAlpha).toString(); } plotFillRatio = (0, _lib.pluck)(setData.ratio, conf.ratio); plotFillAlpha = (0, _lib.pluck)(setData.alpha, conf.plotfillalpha); config.shadow = { opacity: conf.showShadow ? plotFillAlpha / 100 : 0 }; // Setting the angle for plot fill for negative data if (setValue < 0 && !isRoundEdges) { tempPlotfillAngle = conf.plotfillangle; plotfillAngle = isBar ? 180 - plotfillAngle : 360 - plotfillAngle; } // Setting the color Array to be applied to the bar/column. config.colorArr = colorArr = (0, _lib.getColumnColor)(plotColor + ',' + conf.plotgradientcolor, plotFillAlpha, plotFillRatio, plotfillAngle, isRoundEdges, conf.plotbordercolor, plotBorderAlpha, isBar ? 1 : 0, !!is3D); config.originalPlotColor = plotColor; // Parsing the hover effects only if showhovereffect is not 0. if (showHoverEffect !== 0) { hoverColor = (0, _lib.pluck)(setData.hovercolor, JSONData.hovercolor, chartAttr.plotfillhovercolor, chartAttr.columnhovercolor, plotColor); hoverAlpha = (0, _lib.pluck)(setData.hoveralpha, JSONData.hoveralpha, chartAttr.plotfillhoveralpha, chartAttr.columnhoveralpha, plotFillAlpha); hoverGradientColor = (0, _lib.pluck)(setData.hovergradientcolor, JSONData.hovergradientcolor, chartAttr.plothovergradientcolor, conf.plotgradientcolor); !hoverGradientColor && (hoverGradientColor = ''); hoverRatio = (0, _lib.pluck)(setData.hoverratio, JSONData.hoverratio, chartAttr.plothoverratio, plotFillRatio); hoverAngle = (0, _lib.pluckNumber)(360 - setData.hoverangle, 360 - JSONData.hoverangle, 360 - chartAttr.plothoverangle, plotfillAngle); hoverBorderColor = (0, _lib.pluck)(setData.borderhovercolor, JSONData.borderhovercolor, chartAttr.plotborderhovercolor, conf.plotbordercolor); hoverBorderAlpha = (0, _lib.pluck)(setData.borderhoveralpha, JSONData.borderhoveralpha, chartAttr.plotborderhoveralpha, chartAttr.plotfillhoveralpha, chartAttr.columnhoveralpha, plotBorderAlpha, plotFillAlpha); hoverBorderThickness = (0, _lib.pluckNumber)(setData.borderhoverthickness, JSONData.borderhoverthickness, chartAttr.plotborderhoverthickness, conf.showplotborder && plotBorderThickness); hoverBorderDashed = setData.borderhoverdashed || JSONData.borderhoverdashed || chartAttr.plotborderhoverdashed; hoverBorderDashGap = (0, _lib.pluckNumber)(setData.borderhoverdashgap, JSONData.borderhoverdashgap, chartAttr.plotborderhoverdashgap, plotDashLen); hoverBorderDashLen = (0, _lib.pluckNumber)(setData.borderhoverdashlen, JSONData.borderhoverdashlen, chartAttr.plotborderhoverdashlen, plotDashGap); hoverDashStyle = hoverBorderDashed !== UNDEF ? Number(hoverBorderDashed) ? (0, _lib.getDashStyle)(hoverBorderDashLen, hoverBorderDashGap) : '' : plotBorderDashStyle; /* If no hover effects are explicitly defined and * showHoverEffect is not 0 then hoverColor is set. */ if (chartConfig.drawTrendRegion && !is3D || showHoverEffect == 1 && hoverColor === plotColor) { hoverColor = (0, _lib.getLightColor)(hoverColor, 70); } // setting the hover color array which is always applied except when showHoverEffect is not 0. hoverColorArr = (0, _lib.getColumnColor)(hoverColor + ',' + hoverGradientColor, hoverAlpha, hoverRatio, hoverAngle, isRoundEdges, hoverBorderColor, hoverBorderAlpha.toString(), isBar ? 1 : 0, !!is3D); config.setRolloutAttr = { fill: !is3D ? (0, _lib.toRaphaelColor)(colorArr[0]) : [(0, _lib.toRaphaelColor)(colorArr[0]), !use3dlighting], stroke: showplotborder ? (0, _lib.toRaphaelColor)(colorArr[1]) : _lib.TRACKER_FILL, 'stroke-width': showplotborder ? plotBorderThickness : 0, 'stroke-dasharray': plotBorderDashStyle }; config.setRolloverAttr = { fill: !is3D ? (0, _lib.toRaphaelColor)(hoverColorArr[0]) : [(0, _lib.toRaphaelColor)(hoverColorArr[0]), !use3dlighting], stroke: hoverBorderColor ? (0, _lib.toRaphaelColor)(hoverColorArr[1]) : _lib.TRACKER_FILL, 'stroke-width': hoverBorderThickness, 'stroke-dasharray': hoverDashStyle }; } formatedVal = config.toolTipValue; // Parsing tooltext against various configurations provided by the user. config.origToolText = setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(setData.tooltext, JSONData.plottooltext, chartAttr.plottooltext))); if (!showTooltip) { toolText = false; } else { if (formatedVal === null) { toolText = false; } else if (setTooltext !== UNDEF) { macroIndices = [1, 2, 3, 4, 5, 6, 7]; parserConfig = { yaxisName: yAxisName, xaxisName: xAxisName, formattedValue: formatedVal, label: label }; toolText = (0, _lib.parseTooltext)(setTooltext, macroIndices, parserConfig, setData, chartAttr, JSONData); } else { if (seriesNameInTooltip) { seriesname = (0, _lib.getFirstValue)(JSONData && JSONData.seriesname); } toolText = seriesname ? seriesname + tooltipSepChar : ''; toolText += label ? label + tooltipSepChar : ''; } } config.toolText = toolText; config.setTooltext = toolText; tempPlotfillAngle && (plotfillAngle = tempPlotfillAngle); config._x = i; config._y = setValue; }; /** * Recalculate Y position of plot for stack */ ColumnDataset.prototype.updateYForStack = function updateYForStack() { var dataSet = this, chartConfig = dataSet.getFromEnv('chartConfig'), showPercentValues = (0, _lib.pluckNumber)(chartConfig.showpercentvalues), showPercentInToolTip = (0, _lib.pluckNumber)(chartConfig.showpercentintooltip), JSONData = dataSet.config.JSONData, chartAttr = dataSet.getFromEnv('chart-attrib'), xAxis = dataSet.getFromEnv('xAxis'), dataObj, config, i, j, len = xAxis.getTicksLen(), components = dataSet.components, dataStore = components.data, setTooltext, stackValues = dataSet.getFromEnv('stackValues'), stackSumValue, negativeValueFactor = showPercentValues || showPercentInToolTip ? -1 : 1, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), skippingApplied = skipInfo && skipInfo.skippingApplied, plotDrawArray = skipInfo && skipInfo.draw || [], plotDrawArrayLength = plotDrawArray && plotDrawArray.length; if (skippingApplied) { len = plotDrawArrayLength; } for (j = 0; j < len; j++) { i = plotDrawArray[j] || j; dataObj = dataStore[i]; config = dataObj && dataObj.config; if (dataObj === UNDEF) { continue; } setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(config.origToolText, JSONData.plottooltext, chartAttr.plottooltext))); /* * If it is a stacked chart then the display value, tooltext value and data plots * (if stack 100percent is active) is recalculated. */ stackSumValue = stackValues[i] && stackValues[i].positive + negativeValueFactor * stackValues[i].negative || 1; config._b = dataSet._parseValues(i, config._b, stackSumValue, setTooltext); if (chartConfig.stack100percent) { config._y = config.value + config._b; } } }; /** * This function is called from draw() of each data plot of a dataset if it is a stacked chart and * is used for setting proper data for the tooltip and display value. * @param {number} index - index of the data plot for which variable values has to be calculated. * @param {number} previousY - previous sum value of the stack from the current plot. * @param {number} stackSumValue - the total of all the data plots in a stack in a dataset. * @param {string} setTooltext - semi-formatted tooltext entered by the user. * @return {number} previousY - previous sum value of the stack from the current plot. */ ColumnDataset.prototype._parseValues = function _parseValues(index, previousY, stackSumValue, setTooltext) { var dataSet = this, chartConfig = dataSet.getFromEnv('chartConfig'), config = dataSet.components.data[index].config, showPercentValues = (0, _lib.pluckNumber)(chartConfig.showpercentvalues), showPercentInToolTip = (0, _lib.pluckNumber)(chartConfig.showpercentintooltip), visible = dataSet.getState('visible'), setValue = config.setValue, stack100Percent = (0, _lib.pluckNumber)(chartConfig.stack100percent), numberFormatter = dataSet.getFromEnv('number-formatter'), yAxis = dataSet.getFromEnv('yAxis'), setDisplayValue = config.setDisplayValue, formatedPercentValue, percentValue; percentValue = (visible ? setValue || 0 : 0) / stackSumValue * 100; formatedPercentValue = numberFormatter.percentValue(percentValue); if (stack100Percent) { config.value = percentValue; previousY = (previousY || 0) / stackSumValue * 100; } if (showPercentInToolTip) { config.toolTipValue = formatedPercentValue; } if (showPercentValues) { !setDisplayValue && (config.displayValue = formatedPercentValue); } // Applying macros at set level. if (setTooltext) { config.toolText = (0, _lib.parseTooltext)(config.setTooltext, [14, 24, 25, 112], { percentValue: formatedPercentValue, sum: yAxis.dataLabels(stackSumValue), unformattedSum: stackSumValue }); } return previousY; }; /** * Function to register datasets in the internal data store of legend class. */ ColumnDataset.prototype._addLegend = function _addLegend() { var dataset = this, chart = dataset.getFromEnv('chart'), isBar = chart.isBar, chartAttr = dataset.getFromEnv('chart-attrib'), fillColor, lightColor, config, legendItem, conf = dataset.config, color = (0, _lib.getFirstColor)(conf.legendSymbolColor), legend = dataset.getFromEnv('legend'), use3DLighting = (0, _lib.pluckNumber)(chartAttr.use3dlighting, chartAttr.useplotgradientcolor, 1), strokeColor = (0, _lib.getLightColor)(color, 60).replace(dropHash, _lib.HASHSTRING); if (conf.includeinlegend) { if (use3DLighting) { lightColor = (0, _lib.getLightColor)(color, 40); fillColor = { FCcolor: { color: color + ',' + color + ',' + lightColor + ',' + color + ',' + color, ratio: '0,30,30,30,10', angle: isBar ? 0 : 270, alpha: '100,100,100,100,100' } }; } else { fillColor = { FCcolor: { color: color, angle: isBar ? 0 : 270, ratio: '0', alpha: '100' } }; } legendItem = legend.getItem(dataset.config.legendItemId); config = { type: dataset.getName(), index: dataset.getJSONIndex(), label: (0, _lib.getFirstValue)(dataset.config.JSONData.seriesname) }; if (!legendItem) { dataset.config.legendItemId = legend.createItem(dataset); legendItem = legend.getItem(dataset.config.legendItemId); dataset.addExtEventListener('fc-click', function () { legendItem.itemClickFn(); }, legendItem); } legendItem.configure(config); legendItem.setStateCosmetics('default', { symbol: { fill: (0, _lib.toRaphaelColor)(fillColor), rawFillColor: color, stroke: (0, _lib.toRaphaelColor)(strokeColor) } }); // check if dataset is initiallyhidden if (!dataset.getState('visible')) { legendItem.setLegendState('hidden'); } else { // remove hidden state of legend item is dataset is not hidden legendItem.removeLegendState('hidden'); } } else if (dataset.config.legendItemId) { legend.disposeItem(dataset.config.legendItemId); } }; /** * legend Interactivity function to be called on legenditem click. * @param {Object} legendItem item component object of legend */ ColumnDataset.prototype.legendInteractivity = function legendInteractivity(legendItem) { var dataSet = this, legend = legendItem.getLinkedParent(), chart = legend.getFromEnv('chart'), visible = dataSet.getState('visible'), dsConfig = dataSet.config; chart.getFromEnv('animationManager').setAnimationState('legendInteraction'); dsConfig.legendInteractivity = true; visible ? dataSet.hide() : dataSet.show(); // this fixes glitches in firefox when clip rect is applied on some parent containers if (_lib.isFirefox) { var plotGroup = chart.getChildContainer('plotGroup'); plotGroup.attrs['clip-rect'] && plotGroup.attr({ 'clip-rect': plotGroup.attrs['clip-rect'] }); } if (!dsConfig.drawnEvtListenerAttached) { dsConfig.drawnEvtListenerAttached = true; // Dataset will listen to its own drawn event. When drawn event is fired, // it will change the legendInteractivy to false. dataSet.addEventListener('drawn', function () { dsConfig.legendInteractivity = false; }); } }; /** * Creates Pinnable graphics of a dataset for Pin feature */ ColumnDataset.prototype.createPinElem = function createPinElem() { var dataset = this, chart = dataset.getFromEnv('chart'), group = arguments[1].group, dataStore = dataset.components.data, element, pinElems = dataset.graphics.pinElems || (dataset.graphics.pinElems = []), columnGroup = dataset.getLinkedParent().getChildContainer().columnVcanvasGroup, i, pinEl, dataObj; for (i = pinElems.length - 1; i >= 0; i--) { pinElems[i].remove(); pinElems.pop(); } if (dataset.getState('visible')) { for (i = dataset.config.scrollMinVal; i < dataset.config.scrollMaxVal; i++) { dataObj = dataStore[i]; if (dataObj && dataObj.graphics) { element = dataObj.graphics.element; pinEl = element.clone().attr({ 'transform': ['T', -(chart.config._visx + mathAbs(columnGroup.transform()[0][1])), -chart.config.canvasBottom] }); group.appendChild(pinEl); pinElems.push(pinEl); } } } }; /** * function to check if given x,y coordiante is over a column plot or not * @param {number} pX index of column * @param {number} chartX x co-ordinate * @param {number} chartY y co-ordinate * @return {Object} hovered information */ ColumnDataset.prototype._checkPointerOverColumn = function _checkPointerOverColumn(pX, chartX, chartY) { var dataset = this, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, // xAxis = dataset.getFromEnv('xAxis'), // xAxisRange = xAxis.getAxisConfig('axisRange'), // xAxisTotalRange = xAxisRange.max - xAxisRange.min, // xAxisVisibleConfig = xAxis.getVisibleConfig(), // xAxisVisibleRange = xAxisVisibleConfig.maxValue - xAxisVisibleConfig.minValue, plotBorderThickness = chartConfig.plotborderthickness, showPlotBorder = chartConfig.showplotborder, components = dataset.components, dataStore = components.data, pointObj /* = dataStore[pX] */ , pY, dx, dy, hovered, halfPlotBorderThickness, lenDataStore = dataStore && dataStore.length, i, heightTolerance = 0, widthTolerance = 0, numBin, binStrtIndex, binStopIndex, dragTolerance = chartConfig.dragTolerance || 0, skipInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotsPerBin = skipInfo.plotsPerBin; numBin = mathCeil(pX / plotsPerBin); binStrtIndex = (numBin - 1) * plotsPerBin + 1; binStopIndex = binStrtIndex + plotsPerBin - 1; binStopIndex = binStopIndex < lenDataStore ? binStopIndex : lenDataStore; for (i = binStopIndex; i >= binStrtIndex; i--) { pointObj = dataStore[i]; if (!pointObj) { return; } // Setting the tolerance incase of small height or width of column/bar if (pointObj._height < HTP) { heightTolerance = HTP; } if (pointObj._width < HTP) { widthTolerance = HTP; } if (!pointObj._xPos && !pointObj._yPos) { continue; } pY = pointObj.config.setValue; if (showPlotBorder && plotBorderThickness !== UNDEF) { halfPlotBorderThickness = plotBorderThickness / 2; // halfPlotBorderThickness = halfPlotBorderThickness % 2 === 0 ? halfPlotBorderThickness + 1 : // Math.round(halfPlotBorderThickness); } else { plotBorderThickness = halfPlotBorderThickness = 0; } if (pY !== null) { dx = chartX - pointObj._xPos + halfPlotBorderThickness; dy = chartY - pointObj._yPos + halfPlotBorderThickness + (pY >= 0 ? dragTolerance : 0); hovered = dx >= -widthTolerance / 2 && dx <= (widthTolerance || pointObj._width) + plotBorderThickness && dy >= -heightTolerance / 2 && dy <= (heightTolerance || pointObj._height) + plotBorderThickness + (pY < 0 ? 2 * dragTolerance : dragTolerance); if (hovered) { return { pointIndex: i, hovered: hovered, pointObj: dataStore[i] }; } } } }; /** * Function that retunr the nearest plot details * @param {number} chartX x-axis position of the mouse cordinate * @param {number} chartY x-axis position of the mouse cordinate * @return {Object} return an object with details of nearest polt and whether it is hovered or not */ ColumnDataset.prototype._getHoveredPlot = function _getHoveredPlot(chartX, chartY) { var dataset = this, chart = dataset.getFromEnv('chart'), isBar = chart.isBar, xAxis = dataset.getFromEnv('xAxis'), x, pX; chartX += xAxis.getTranslation(); x = xAxis.getValue(isBar ? chartY : chartX); pX = Math.round(x); // Checking for overlap between two cosecutive column plots along x-axis return pX - x > 0 ? dataset._checkPointerOverColumn(pX, chartX, chartY) || dataset._checkPointerOverColumn(pX - 1, chartX, chartY) : dataset._checkPointerOverColumn(pX + 1, chartX, chartY) || dataset._checkPointerOverColumn(pX, chartX, chartY); }; /** * Returns the details of the plot in the category band that the givennt x and y co-ordinates * are in. * * @param {number} [chartX=0] x-axis position of the mouse cordinate * @param {number} [chartY=0] y-axis position of the mouse cordinate * * @return {Object} Return an object with details of nearest plot in the category band. */ ColumnDataset.prototype.getPlotInCategoryAt = function getPlotInCategoryAt() { var chartX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var chartY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var plots = this.components.data, xAxis = this.getFromEnv('xAxis'), yAxis = this.getFromEnv('yAxis'), xTranslation = xAxis.getTranslation() || 0, yTranslation = yAxis.getTranslation() || 0, isDatasetVisible = this.getState('visible'), xCoords = chartX + xTranslation, yCoords = chartY + yTranslation, foundPlot = void 0, categoryAxis = void 0, isAxisVertical = void 0, hoveredCategoryIndex = void 0, hoveredPlotInfo = void 0; // Proceed further into the function only if at least one of the axes attached to the dataset // is a category axis if (xAxis.getName() === 'category' && xAxis.config.hasCategory) { categoryAxis = xAxis; } else if (yAxis.getName() === 'category' && yAxis.config.hasCategory) { categoryAxis = yAxis; } else { return false; } isAxisVertical = categoryAxis.config.isVertical; // If an axis' vertical or horizontal orientation could not be found, its not possible to // determine where along the axis a category's plot lies. An exception to this rule is the radar // dataset. It has its own RadarDataset#getPlotInCategoryAt method which overrides this one. if (isAxisVertical === null || typeof isAxisVertical === 'undefined') return false; // Find which category the mouse is over hoveredCategoryIndex = Math.round(categoryAxis.getValue(isAxisVertical ? yCoords : xCoords)); // Find which plot is at the same category as the mouse foundPlot = plots[hoveredCategoryIndex]; // Ascertain if the mouse is directly over a plot hoveredPlotInfo = this._getHoveredPlot(chartX, chartY); if (isDatasetVisible && hoveredPlotInfo) { // If dataset is visible and the mouse is exactly over a plot return hoveredPlotInfo; } else if (isDatasetVisible && foundPlot) { // If dataset is visible and the mouse is over a category band return { pointIndex: foundPlot._index, hovered: false, pointObj: foundPlot }; } else { // If dataset is not visible and no relevant plot was found return false; } }; /** * Helper function of _firePlotEvent which decides single/consolidated tooltip * @param {number} plotIndex plot index * @param {Object} e reference of the original mouse event * @param {Object} datasets column datasets */ ColumnDataset.prototype._decideTooltipType = function _decideTooltipType(plotIndex, e) { var dataset = this, chart = dataset.getFromEnv('chart'), // @todo have to remove this code related to draw crossline drawTrendRegion = chart.config.drawTrendRegion, components = dataset.components, toolTipController = dataset.getFromEnv('toolTipController'), dataStore = components.data, data = dataStore[plotIndex], toolText = data && (data.config.finalTooltext || data.config.toolText), currentToolTip = dataset.config.currentToolTip, originalEvent = e.originalEvent; if (toolText && !drawTrendRegion) { if (currentToolTip) { toolTipController.draw(originalEvent, toolText, currentToolTip); } else { currentToolTip = dataset.config.currentToolTip = toolTipController.draw(originalEvent, toolText); } } }; /** * This method handles all mouse events of an dataset. * @param {string} eventType name of the event * @param {number} plotIndex index of the plot where this event has been occured * @param {Event} e reference of the original mouse event * @param {Event} datasets column dataset */ ColumnDataset.prototype._firePlotEvent = function _firePlotEvent(eventType, plotIndex, e) { var dataset = this, chart = dataset.getFromEnv('chart'), components = dataset.components, toolTipController = dataset.getFromEnv('toolTipController'), dataStore = components.data, data = dataStore[plotIndex], setElement = data.graphics && data.graphics.element, toolTip = dataset.config.currentToolTip, // Now instead of original event, derived event is passed on, as there has been a change to how events work // originalEvent = e.originalEvent, config, setLink; if (setElement) { config = data.config; setLink = config.setLink; switch (eventType) { case 'fc-mouseover': dataset._decideTooltipType(plotIndex, e); _rolloverResponseSetter(chart, data, e, UNDEF, this); // Setting cursor style to pointer on the set element instead of the root SVG element // so that hybrid IE11 fires the click event correctly on touch setLink && (setElement.node.style.cursor = POINTER); break; case 'fc-mouseout': toolTipController.hide(toolTip); _rolloutResponseSetter(chart, data, e, UNDEF, this); // Removing cursor style from the set element instead of the root SVG element so that // hybrid IE11 fires the click event correctly on touch setLink && (setElement.node.style.cursor = DEFAULT_CURSOR); break; case 'fc-click': chart.plotEventHandler(setElement, e); break; case 'fc-mousemove': dataset._decideTooltipType(plotIndex, e); } } }; /** * function to create group for dataset */ ColumnDataset.prototype.createContainer = function createContainer() { var dataset = this, dsType = dataset.getType(), chart = dataset.getFromEnv('chart'), parent = dataset.getLinkedParent(), group = dataset.config.primitiveType || dsType, parentContainer, commonElemsParentContainer, anchorElemsParentContainer, parentShadowContainer; !parent.getChildContainer(group + 'VcanvasGroup') && (group = 'default'); parentContainer = parent.getChildContainer(group + 'VcanvasGroup'); parentShadowContainer = parent.getChildContainer(group + 'ShadowVcanvasGroup'); commonElemsParentContainer = parent.getChildContainer('commonElemGroup') || parentContainer; anchorElemsParentContainer = parent.getChildContainer('anchorGroup') || parentContainer; !dataset.getContainer('shadowGroup') && dataset.addContainer('shadowGroup', createGroup('shadow-group', parentShadowContainer, dataset)); !dataset.getContainer('errorShadowGroup') && dataset.addContainer('errorShadowGroup', createGroup('error-shadow-group', parentShadowContainer, dataset)); !dataset.getContainer('commonElemsGroup') && dataset.addContainer('commonElemsGroup', createGroup('common-elems-group', commonElemsParentContainer, dataset)); !dataset.getContainer('plotGroup') && dataset.addContainer('plotGroup', createGroup('plot-group', anchorElemsParentContainer, dataset)); !dataset.getContainer('errorPlotGroup') && dataset.addContainer('errorPlotGroup', createGroup('error-plot-group', parentContainer, dataset)); chart.hasAnchor && dataset.getContainer('errorPlotGroup').insertBefore(dataset.getContainer('plotGroup')); !dataset.getContainer('labelGroup') && dataset.addContainer('labelGroup', createGroup('label-group', parent.getChildContainer('vcanvasLabelGroup'), dataset).attr('class', 'fusioncharts-datalabels')); }; /** * Create pixel coordinates for the plots */ ColumnDataset.prototype.createCoordinates = function createCoordinates() { var dataSet = this, dsComponents = dataSet.components, dsData = dsComponents.data, chart = dataSet.getFromEnv('chart'), isBar = chart.isBar, yAxis = dataSet.getFromEnv('yAxis'), xAxis = dataSet.getFromEnv('xAxis'), yBase = yAxis.getAxisBase(), yBasePos = yAxis.getPixel(yBase), isVertical = xAxis.config.isVertical, dataObj, config, previousY, i, j, Px, Py, Pb, xDepth = chart.config.xDepth || 0, yDepth = chart.config.yDepth || 0, len = dsData.length, components = dataSet.components, groupManager = dataSet.getLinkedParent(), stackConf = groupManager.getstackConf && groupManager.getstackConf(), dataStore = components.data, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), skippingApplied = skipInfo && skipInfo.skippingApplied, plotDrawArray = skipInfo && skipInfo.draw || [], plotDrawArrayLength = plotDrawArray && plotDrawArray.length, xPx, yPx; !isBar && (xDepth = -xDepth); isBar && (yDepth = -yDepth); if (skippingApplied) { len = plotDrawArrayLength; } for (j = 0; j < len; j++) { i = plotDrawArray[j] || j; dataObj = dataStore[i]; config = dataObj && dataObj.config; if (dataObj === UNDEF) { continue; } previousY = config._b; xPx = xAxis.getPixel(stackConf && stackConf[i] && stackConf[i].x || config._x); Px = (isFinite(xPx) ? xPx : 0) + xDepth; yPx = yAxis.getPixel(config._y); Py = (isFinite(yPx) ? yPx : 0) + yDepth; Pb = (previousY ? yAxis.getPixel(previousY) : yBasePos) + yDepth; if (isVertical) { config._Px = Py; config._Py = Px; config._Pby = Px; config._Pbx = Pb; } else { config._Px = Px; config._Py = Py; config._Pby = Pb; config._Pbx = Px; } if (dataSet.getLineShift) { config._Py += dataSet.getLineShift('y'); } } }; /** * Set visibilty of containers * @param {boolean} show whether visible or not */ ColumnDataset.prototype.setContainerVisibility = function setContainerVisibility(show) { var dataSet = this, // graphics = dataSet.graphics, containers = dataSet.getContainer(), container; for (container in containers) { if (containers.hasOwnProperty(container)) { if (dataSet.getState('visible') === false && (dataSet._conatinerHidden === false || dataSet._conatinerHidden === UNDEF) && !show) { containers[container].hide(); dataSet._conatinerHidden = true; } else { containers[container].show(); dataSet._conatinerHidden = false; } } } }; /** * Manages the animation of plot elements * @param {Object} dataObj reference of a specific data plot * @param {Object} attrObj reference of attr of the data plot * @param {number} i index * @param {number} length The total number of data plots */ ColumnDataset.prototype.plotAnimManager = function plotAnimManager(dataObj, attrObj, i, length) { var dataSet = this, chart = dataSet.getFromEnv('chart'), animationManager = chart.getFromEnv('animationManager'), is3D = chart.config.is3D, chartConfig = chart.config, visible = dataSet.getState('visible'), xPos = attrObj.x, // components = dataSet.components, setElement, setValue, relativeGroupArray, config, configObj, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), plotDrawArray = skipInfo && skipInfo.draw || [], // element, // TODO: need to have similar place in case of 3d as well container, isNegative, plotGroup3d = dataSet.getFromEnv('plotGroup3d'), attr; config = dataObj && dataObj.config; setValue = config && config.setValue; isNegative = setValue < 0; // For the 3d Chanrts the containers are different to make the 3D looks proper if (is3D) { relativeGroupArray = isNegative ? plotGroup3d.negativeGroupArray : plotGroup3d.positiveGroupAarray; container = relativeGroupArray[chart.isBar ? relativeGroupArray.length - 1 - i : i]; } else { container = dataSet.getContainer('plotGroup'); } setElement = dataObj.graphics.element; // TODO: will remove this non-IE < 8 compitable code attr = attrObj; configObj = { el: setElement || (is3D ? 'cubepath' : 'rect'), container: container, attr: visible && attr, doNotRemove: true, props: { originalIndex: plotDrawArray[i] || i }, index: i, length: length, component: dataSet, label: 'rect' }; if (!visible) { configObj.callback = function () { this.hide(); }; } // Sending the data to animationManager so that it can take the decision what to do next dataObj.graphics.element = setElement = animationManager.setAnimation(configObj); if (is3D) { setElement.appendTo(container); if (chartConfig.isstacked && isNegative || !chartConfig.isstacked && chart.isBar) { setElement.toBack(); } } if (dataObj.config.setValue !== null) { dataSet.getState('visible') && setElement.show(); } else { setElement.remove(); delete dataObj.graphics.element; } config._oldPx = config._Px; config._oldX = xPos; // TODO remove this code. Temporary code to make animation working // Also, for hiding datasets this should be UNDEF visible && (dataObj.oldPrevDataObj = dataObj.prevDataObj); }; /** * function to flush data graphics on scroll draw. When scrolling is apllied on a scroll chart then those * plots which are outside of the view port, thier graphics are flushed. * So that unnecessary dom elements will be removed from the dom tree. * And the newly appeared elements will be well managed. * @param {number} start start index * @param {number} end end index */ ColumnDataset.prototype.flushOnScroll = function flushOnScroll(start, end) { var dataSet = this, components = dataSet.components, datum = void 0, dataStore = components.data; for (var i = start, len = end - 1; i <= len; i++) { datum = dataStore[i]; if (!(datum && datum.graphics)) { continue; } _graphicsIterator(datum.graphics, dataSet.__removeElem); datum.graphics = {}; } }; /** * Generalised function for removing an entire instance of a component */ ColumnDataset.prototype.removingDraw = function removingDraw() { var dataset = this, datastore = dataset.components.data; datastore.forEach(function (datum) { _graphicsIterator(datum.graphics, dataset.__removeElem); delete datum.graphics; }); _ComponentInterface.prototype.removingDraw.call(this); }; /** * function to check if the context of dataset is chanegd or not * if changed then it will return staus true. It is for further infomormation to redraw a dataset * @return {boolean} status of context change */ ColumnDataset.prototype._contextChanged = function _contextChanged() { var catLen; if (!this.config.context) { this.config.context = {}; } var dataset = this, context = dataset.config.context, oldShift = context.shift, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), stringifiedOldLimits = context.axisLimit, stringifiedNewLimits = void 0, status = false, newAxisLimit = { yAxis: { limit: yAxis.getVisibleConfig() }, xAxis: { limit: xAxis.getVisibleConfig() } }; newAxisLimit.yAxis.limitPixel = { min: yAxis.getPixel(newAxisLimit.yAxis.limit.minValue), max: yAxis.getPixel(newAxisLimit.yAxis.limit.maxValue) }; newAxisLimit.xAxis.limitPixel = { min: xAxis.getPixel(newAxisLimit.xAxis.limit.minValue), max: xAxis.getPixel(newAxisLimit.xAxis.limit.maxValue) }; stringifiedNewLimits = JSON.stringify(newAxisLimit); if (stringifiedOldLimits !== stringifiedNewLimits) { context.axisLimit = stringifiedNewLimits; status = true; } if (oldShift !== dataset.getFromEnv('shift')) { context.shift = dataset.getFromEnv('shift'); status = true; } if (context.prevColNum !== dataset.getFromEnv('numOfColumns')) { context.prevColNum = dataset.getFromEnv('numOfColumns'); status = true; } // Gantt if (xAxis.getProcessLen) { catLen = xAxis.getProcessLen(); } else if (xAxis.getTicksLen) { catLen = xAxis.getTicksLen(); } if (context.prevCatlen !== catLen) { context.prevCatlen = catLen; status = true; } if (this.getFromEnv('chart').isRealTime) { return true; } return status; }; /** * calculate min and max position to scroll */ ColumnDataset.prototype.calculateScrollRange = function calculateScrollRange() { var dataSet = this, conf = dataSet.config, xAxis = dataSet.getFromEnv('xAxis'), len = void 0, catLen = xAxis.getTicksLen(), skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo() || {}, skippingApplied = skipInfo.skippingApplied, plotDrawArray = skipInfo.draw || [], labelDrawArray = skipInfo.labelDraw || [], plotDrawArrayLength = plotDrawArray.length; len = skippingApplied ? plotDrawArrayLength - 1 : catLen; conf.scrollMinVal = mathMax(mathRound(xAxis.getVisibleConfig().minValue), 0) - 1; conf.scrollMaxVal = mathMin(mathRound(xAxis.getVisibleConfig().maxValue) + 1, len) + 1; len = skippingApplied ? labelDrawArray.length - 1 : catLen; conf.scrollMinValForLabel = mathMax(mathRound(xAxis.getVisibleConfig().minValue), 0) - 1; conf.scrollMaxValForLabel = mathMin(mathRound(xAxis.getVisibleConfig().maxValue) + 1, len) + 1; }; /** * Draws and updates the plots' graphics * @param {Object} anim Object reference of animation manager argument consist of elements and * their configuration */ ColumnDataset.prototype.drawPlots = function drawPlots() { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, i, j, chartConfig = chart.config, showHoverEffect = chartConfig.plothovereffect, crispBox, dataObj, setElement, config, dataStore = dataSet.components.data, shadowContainer = dataSet.getContainer('shadowGroup'), trackerConfig, attrObj, scrollMinVal, scrollMaxVal, _oldStartIndex = conf._oldStartIndex, _oldEndIndex = conf._oldEndIndex, fi, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), plotDrawArray = skipInfo && skipInfo.draw; scrollMinVal = conf.scrollMinVal; scrollMaxVal = conf.scrollMaxVal; if (scrollMinVal > _oldStartIndex) { dataSet.flushOnScroll(_oldStartIndex, scrollMinVal > _oldEndIndex ? _oldEndIndex : scrollMinVal); } if (scrollMaxVal < _oldEndIndex) { dataSet.flushOnScroll(scrollMaxVal < _oldStartIndex ? _oldStartIndex : scrollMaxVal, _oldEndIndex); } conf._oldStartIndex = scrollMinVal; conf._oldEndIndex = scrollMaxVal; for (j = scrollMinVal, fi = scrollMaxVal - 1; j < scrollMaxVal; j++, fi--) { i = plotDrawArray[j] || j; dataObj = dataStore[i]; if (!dataObj) { continue; } config = dataObj.config; attrObj = config.props.element.attr; dataSet.plotAnimManager(dataObj, attrObj, j, scrollMaxVal); trackerConfig = dataObj.trackerConfig; setElement = dataObj.graphics.element; if (!setElement) { continue; } // The shadow element is set for the dataplots. setElement.shadow(config.shadow, shadowContainer).data('BBox', crispBox); // If algorithmic mouseTracking is enabled then attach these data to setElement // because tracker element will not be drawn chart.config.enablemousetracking && setElement.data(EVENTARGS, trackerConfig.eventArgs).data(showHoverEffectStr, showHoverEffect).data(SETROLLOVERATTR, config.setRolloverAttr || {}).data(SETROLLOUTATTR, config.setRolloutAttr || {}); } conf.appearing && (conf.appearing = false); }; /** * function to calculate width, hieght and dataset shift */ ColumnDataset.prototype.setColumnPosition = function setColumnPosition() { var dataSet = this, columnWidth = void 0, shift = void 0; if ((columnWidth = dataSet.getFromEnv('plotWidth')) === UNDEF) { var xAxis = dataSet.getFromEnv('xAxis'), chartConfig = this.getFromEnv('chartConfig'), skippingInfo = dataSet.getSkippingInfo(), offSetColNo = skippingInfo.plotsPerBin, definedGroupPadding = mathMax(chartConfig.plotSpacePercent, 0), plotSpacePercent = mathMax((0, _lib.pluckNumber)(definedGroupPadding, 20) % 100, 0), groupPadding = offSetColNo === 1 ? plotSpacePercent / 200 : 0, xAxisZeroPos = xAxis.getPixel(0), xAxisFirstPos = xAxis.getPixel(offSetColNo), chart = dataSet.getFromEnv('chart'), maxColWidth = chart.isBar ? chart.config.maxBarHeight : chart.config.maxColWidth, groupMaxWidth = mathAbs(xAxisFirstPos - xAxisZeroPos), groupNetWidth = void 0, xPosFirst = void 0, xPosNext = void 0, isCrisp = true, groupNetGapWidth = 4, groupNetHalfWidth = void 0, numOfColumns = 1; groupNetWidth = (1 - definedGroupPadding * 0.01) * groupMaxWidth || mathMin(groupMaxWidth * (1 - groupPadding * 2), maxColWidth * (numOfColumns || 1)); columnWidth = numOfColumns === 0 ? groupNetWidth : groupNetWidth / numOfColumns; groupNetHalfWidth = groupNetWidth / 2; xPosFirst = xAxisZeroPos - groupNetHalfWidth; xPosNext = xAxisFirstPos - groupNetHalfWidth; if (xPosNext - (xPosFirst + groupNetWidth) < groupNetGapWidth) { isCrisp = false; } if (plotSpacePercent === 0) { isCrisp = true; } dataSet.addToEnv('isCrisp', isCrisp); } dataSet.addToEnv('columnWidth', columnWidth); shift = dataSet.getFromEnv('shift') || 0; dataSet.addToEnv('columnXShift', shift - dataSet.getFromEnv('columnWidth') / 2); }; /** * Parsing of plot attrs * * @param {any} dataObj dataObj * @param {any} index index * @memberof ColumnDataset */ ColumnDataset.prototype.parsePlotAttributes = function parsePlotAttributes(dataObj, index) { var dataSet = this, dsConfig = dataSet.config, JSONData = dataSet.config.JSONData, chart = dataSet.getFromEnv('chart'), chartAttr = chart.getFromEnv('dataSource').chart, isStacked = chart.config.isstacked, conf = dataSet.config, groupManager = dataSet.groupManager, datasetIndex = dataSet.getJSONIndex(), i = index, visible = dataSet.getState('visible'), chartConfig = chart.config, is3D = chart.config.is3D, isBar = chart.isBar, crispObj, xDepth = chartConfig.xDepth || 0, yDepth = chartConfig.yDepth || 0, yAxis = dataSet.getFromEnv('yAxis'), xAxis = dataSet.getFromEnv('xAxis'), xPos, yPos, plotGap, showTooltip = chartConfig.showtooltip, isVisible = dataSet.getState('visible') !== false, initialColumnWidth, xPosOffset, yPosOffset, initialColumnHeight, columnWidth, height, toolText, components = dataSet.components, dataStore = components.data, setTooltext, setLink, setValue, displayValue, config = dataObj.config, yBase = yAxis.getAxisBase(), yBasePos = yAxis.yBasePos = yAxis.getPixel(yBase), plotBorderThickness = (0, _lib.pluckNumber)(conf.plotborderthickness, chartConfig.plotborderthickness), plotRadius = (0, _lib.pluckNumber)(chartConfig.useroundedges, 0), colorArr, plotBorderDashStyle, crispDim, trackerConfig, Px, Py, tempWidth, tempHeight, use3DLighting = conf.use3dlighting, currentYBaseTouched, minPx = mathMin(dsConfig.yAxisMinPixel, dsConfig.yAxisMaxPixel), stackConf = groupManager && groupManager.stackConf, tunedAttr, shift = dataSet.getFromEnv('columnXShift'), viewPortConfig = chart.config.viewPortConfig, x = viewPortConfig.x, scaleX = viewPortConfig.scaleX, showPlotBorder = (0, _lib.pluckNumber)(chartConfig.showplotborder); setLink = config.setLink; colorArr = config.colorArr || []; if (xAxis.config.isVertical) { initialColumnHeight = dataSet.getFromEnv('columnWidth'); yPosOffset = shift; } else { initialColumnWidth = dataSet.getFromEnv('columnWidth'); xPosOffset = shift; } // Creating the data structure if not present for storing the graphics elements. if (!dataObj.graphics) { dataStore[i].graphics = {}; } displayValue = config.displayValue; // When dataset is not visbile during legend interactivity !isVisible && (config._Py = config._Pby); Px = mathMin(config._Px, config._Pbx) + (xPosOffset || 0) + x * scaleX; Py = mathMin(config._Py, config._Pby) + (yPosOffset || 0); stackConf && (Px -= initialColumnWidth / 2); tempWidth = initialColumnWidth || mathAbs(config._Px - config._Pbx); tempHeight = initialColumnHeight || mathAbs(config._Py - config._Pby); if (isBar) { if (config._Px - config._Pbx > 0) { // positive plots crispObj = crispRight; } else { // negative plots crispObj = crispLeft; } } else { if (config._Py - config._Pby > 0) { // positive plots crispObj = crispBottom; } else { // negative plots crispObj = crispTop; } } setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(config.origToolText, JSONData.plottooltext, chartAttr.plottooltext))); if (dataSet.fineTunePlotDimension) { tunedAttr = dataSet.fineTunePlotDimension(Px, Py, tempHeight, tempWidth, i); Px = tunedAttr.xPos; Py = tunedAttr.yPos; tempWidth = tunedAttr.width; tempHeight = tunedAttr.height; } xPos = Px; yPos = Py; columnWidth = tempWidth; height = tempHeight; plotGap = xAxis.getPixel(1) - xAxis.getPixel(0) - (isBar ? height : columnWidth); !isFinite(height) && (height = 0); // adjustments made when plotborder thicknesss is applied. if (visible) { // crisped and include the stroke width within the boundary if (!(plotGap < 5 && dataSet.getFromEnv('columnWidth') < 5)) { crispDim = (0, _lib.crispBound)(Px, Py, columnWidth, height, plotBorderThickness, crispObj, isStacked); } if (crispDim) { xPos = crispDim.x; yPos = crispDim.y; plotBorderThickness = crispDim['stroke-width']; columnWidth = crispDim.width; height = crispDim.height || 1; } else { xPos = Px; yPos = Py; } // when yAxis base is present at the edge of the canvas and not in between if (!xAxis.config.isVertical) { if (yPos + height === minPx) { // base is at the bottom edge of the canvas height += plotBorderThickness; } else if (yPos === minPx) { // base is at the top edge of the canvas yPos -= plotBorderThickness; height += plotBorderThickness; } } else { if (xPos === minPx) { // base is at the left edge of the canvas xPos -= plotBorderThickness; columnWidth += plotBorderThickness; } } config.setRolloutAttr && (config.setRolloutAttr['stroke-width'] = dsConfig.showplotborder ? plotBorderThickness : 0); } // Setting the final tooltext. toolText = config.finalTooltext = config.toolText !== false ? config.toolText + (setTooltext ? '' : config.toolTipValue) : ''; plotBorderDashStyle = config.plotBorderDashStyle; trackerConfig = dataObj.trackerConfig = {}; // Setting the event arguments. trackerConfig.eventArgs = { index: i, link: setLink, value: config.setValue, displayValue: displayValue, categoryLabel: config.origLabel, toolText: toolText, id: '', datasetIndex: datasetIndex, datasetName: JSONData.seriesname, visible: visible }; currentYBaseTouched = yBasePos === yPos + (setValue > 0 ? height : 0); config.props = { element: { attr: { x: xPos || 0, width: columnWidth || 0, // Not updating the width and xpos, if column is not visible // applicable during legend interactivity. height: height || 0, y: yPos || 0, r: plotRadius, fill: (0, _lib.toRaphaelColor)(colorArr[0]) || '', stroke: showPlotBorder ? (0, _lib.toRaphaelColor)(colorArr[1]) || '' : _lib.TRACKER_FILL, 'stroke-width': showPlotBorder ? plotBorderThickness : 0, 'stroke-dasharray': plotBorderDashStyle, 'stroke-linejoin': 'miter', 'visibility': visible, cursor: setLink ? POINTER : '' } } }; if (is3D) { config.props.element.attr.noGradient = !use3DLighting; config.props.element.attr.xDepth = xDepth; config.props.element.attr.yDepth = yDepth; } dataObj._xPos = xPos + xDepth; dataObj._width = columnWidth; dataObj._yPos = yPos - yDepth; dataObj._height = height; dataObj._index = i; // Need for crisping of removed plot dataObj._plotBorderThickness = plotBorderThickness; if (setLink || showTooltip) { // Fix for touch devices. if (height < HTP) { yPos -= (HTP - height) / 2; height = HTP; } // Setting attributes for the hotelement. trackerConfig.attr = { x: xPos, y: yPos, width: columnWidth, height: height, r: plotRadius, cursor: setLink ? POINTER : '', stroke: _lib.TRACKER_FILL, 'stroke-width': showPlotBorder ? plotBorderThickness : 0, fill: _lib.TRACKER_FILL, visibility: visible }; } config.oldValue = setValue; dataObj._oldYBaseTouched = currentYBaseTouched; }; /** * Parses the cosmetics of data labels * * @param {any} dataObj dataObj * @param {any} index required in case of data skipping * @memberof ColumnDataset */ ColumnDataset.prototype.parseLabelAttributes = function parseLabelAttributes(dataObj) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, smartLabel = chart.getFromEnv('smartLabel'), style = chart.config.dataLabelStyle, conf = dataSet.config, legendInteractivity = conf.legendInteractivity, visible = dataSet.getState('visible'), attr, displayValue, rotateValues = chartConfig.rotatevalues ? 270 : 0, bBoxObj, graphic, textY, textX, yPos, xPos, setValue, config, showValue, pos, tempGraphics; config = dataObj && dataObj.config; setValue = config && config.setValue; // Condition arises when user has removed data in real time update if (dataObj === UNDEF || setValue === UNDEF || setValue === null || config.labelSkip === true) { config && delete config.labelSkip; tempGraphics = dataObj && dataObj.graphics; if (tempGraphics) { tempGraphics.label && tempGraphics.label.hide(); } return; } graphic = dataObj.graphics; // Condition arises when feedData enters less number of data in a dataset compared to the other. if (!graphic) { return; } yPos = dataObj._yPos; xPos = dataObj._xPos; displayValue = config.displayValue; showValue = config.showValue; if (!showValue || setValue === null) { if (graphic.label) { graphic.label.attr({ 'text-bound': [] }); graphic.label.hide(); } return; } if (!legendInteractivity || !config._state) { smartLabel.setStyle(style); bBoxObj = smartLabel.getOriSize(displayValue); if (rotateValues) { // If rotated values we use the width of // the text as height config._state = { labelWidth: bBoxObj.height, labelHeight: bBoxObj.width }; } else { config._state = { labelWidth: bBoxObj.width, labelHeight: bBoxObj.height }; } } pos = dataSet._getValuePosition({ labelWidth: config._state.labelWidth, labelHeight: config._state.labelHeight, width: dataObj._width, height: dataObj._height, yPos: yPos, xPos: xPos, value: setValue }); textX = pos.textX; textY = pos.textY; if (!config.props) { config.props = {}; } config.props.label = { attr: { x: textX, y: textY, text: displayValue, 'text-bound': [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash], opacity: visible ? 1 : 0 } }; attr = config.props.label.attr; if (!legendInteractivity) { // These parameters do not change on legendInteractivity, it is done to improve performance. attr['line-height'] = style.lineHeight; attr.fill = style.color; } }; /** * Sets position of individual plots * * @memberof ColumnDataset */ ColumnDataset.prototype.allocatePosition = function allocatePosition() { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, showpercentvalues = chartConfig.showpercentvalues, showPercentInToolTip = chartConfig.showpercentintooltip, conf = dataSet.config, i, j, len = dataSet.components.data.length, yAxis = dataSet.getFromEnv('yAxis'), components = dataSet.components, dataStore = components.data, dataObj, yAxisLimit, isStacked = chartConfig.isstacked, stack100Percent = Number(chartConfig.stack100percent), visibleStart, visibleEnd, maxPx, minPx, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), plotDrawArray = skipInfo && skipInfo.draw; dataSet.deleteFromEnv('columnWidth'); dataSet.setColumnPosition(); dataSet.calculateScrollRange(); // For Stack charts recalculate the y pos isStacked && (stack100Percent || showpercentvalues || showPercentInToolTip) && dataSet.updateYForStack(); dataSet.createCoordinates(); yAxisLimit = yAxis.getLimit(); maxPx = yAxis.getPixel(yAxisLimit.max); minPx = yAxis.getPixel(yAxisLimit.min); visibleStart = conf.scrollMinVal; visibleEnd = conf.scrollMaxVal; if (maxPx > minPx) { conf.yAxisMaxPixel = maxPx; conf.yAxisMinPixel = minPx; } else { conf.yAxisMaxPixel = minPx; conf.yAxisMinPixel = maxPx; } for (j = 0; j < len; j++) { i = plotDrawArray[j] || j; if (chart.hasScroll && (i < visibleStart || i > visibleEnd)) { continue; } dataObj = dataStore[i]; if (!dataObj) { continue; } // Parse attributes of plots dataSet.parsePlotAttributes(dataObj, i); // Parse attributes of labels dataSet.parseLabelAttributes(dataObj); } }; /** * Function for drawing 2D columns. * This function is called every time for each dataset when they are initially drawn or shown/hidden from * the drawGraph() function. */ ColumnDataset.prototype.draw = function draw() { var dataSet = this, conf = dataSet.config, visible = dataSet.getState('visible'), xAxis = dataSet.getFromEnv('xAxis'), xAxisZeroPos = xAxis.getPixel(0), xAxisFirstPos = xAxis.getPixel(1), groupMaxWidth = dataSet.getFromEnv('groupMaxWidth'), chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, // showpercentvalues = chartConfig.showpercentvalues, xDepth = chartConfig.xDepth || 0, yAxis = dataSet.getFromEnv('yAxis'), drawn = conf.drawn, yAxisMaxmin = yAxis.getLimit(), yMax = yAxisMaxmin.max, yMin = yAxisMaxmin.min, isPositiveNegative = yMax > 0 && yMin < 0, scrollMinValForLabel, scrollMaxValForLabel, isContextChanged = dataSet._contextChanged(), skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo() || {}, skippingApplied = skipInfo.skippingApplied; if (!groupMaxWidth) { groupMaxWidth = mathAbs(xAxisFirstPos - xAxisZeroPos); dataSet.addToEnv('groupMaxWidth', groupMaxWidth); } if (!dataSet.getState('removed') && !dataSet.getState('dirty') && !(isContextChanged && visible)) { return; } !drawn && dataSet.createContainer(); dataSet.setContainerVisibility(true); if (skippingApplied) { dataSet.hidePlots(); } // Draw all the graphic elements dataSet.drawPlots(); dataSet.drawCommonElements && !dataSet.config.skipCommonElements && dataSet.drawCommonElements(); scrollMinValForLabel = conf.scrollMinValForLabel; scrollMaxValForLabel = conf.scrollMaxValForLabel; // Datalabels are drawn in a different thread for the first time and later drawn in the same thread. conf.drawn ? dataSet.drawLabel(scrollMinValForLabel, scrollMaxValForLabel) : dataSet.addJob('labelDrawID', function () { dataSet.drawLabel(scrollMinValForLabel, scrollMaxValForLabel); }, _schedular.priorityList.label); // Setting the drawn flag true to draw differently incase of real time draw. conf.drawn = true; dataSet.removePlots(); conf.oldGroupMaxWidth = groupMaxWidth; conf.oldDataIsPositiveNegative = isPositiveNegative; conf.oldZeroAxisPos = yAxis.getPixel(yAxis.getAxisBase()) + xDepth; dataSet.drawErrorValue && dataSet.drawErrorValue(); conf.prevVisible = visible; conf.catDiff = 0; }; /** * This function is used to make a dataset visible when clicked on its respective legend. * This fucntion is called from drawGraph() every time a deactivated legend is clicked. */ ColumnDataset.prototype.show = function show() { var dataSet = this, parent = dataSet.getLinkedParent(), legend = dataSet.getFromEnv('legend'); if (legend && legend.getItem(dataSet.config.legendItemId)) { legend.getItem(dataSet.config.legendItemId).removeLegendState('hidden'); } dataSet.setState('visible', true); dataSet.config.appearing = true; dataSet._conatinerHidden = false; dataSet.setState('dirty', true); parent.childChanged(); dataSet.config.appearing = false; dataSet.asyncDraw(); }; /** * This function is used to make a dataset hidden when clicked on its respective legend. * This fucntion is fired from drawGraph() every time an activated legend is clicked. */ ColumnDataset.prototype.hide = function hide() { var dataSet = this, parent = dataSet.getLinkedParent(), legend = dataSet.getFromEnv('legend'); if (legend && legend.getItem(dataSet.config.legendItemId)) { legend.getItem(dataSet.config.legendItemId).setLegendState('hidden'); } dataSet.setState('dirty', true); dataSet.setState('visible', false); parent.childChanged(); dataSet.asyncDraw(); }; /** * This function is used for drawing the data labels. * This function is called once for each dataset when the are drawn and shown/hidden from the draw() * function of the Column class. * @param {number} start start index * @param {number} end end index */ ColumnDataset.prototype.drawLabel = function drawLabel(start, end) { var dataSet = this, chart = dataSet.getFromEnv('chart'), animationManager = dataSet.getFromEnv('animationManager'), chartConfig = chart.config, xAxis = dataSet.getFromEnv('xAxis'), paper = dataSet.getFromEnv('paper'), visible = dataSet.getState('visible'), smartLabel = chart.getFromEnv('smartLabel'), style = chart.config.dataLabelStyle, conf = dataSet.config, len = xAxis.getTicksLen(), components = dataSet.components, dataStore = components.data, pool = components.pool, dataObj, attr, i, j, rotateValues = chartConfig.rotatevalues ? 270 : 0, graphic, xPos, setValue, config, showValue, attr2, label, tempGraphics, dataLabelContainer, labelDrawn = conf.labelDrawn, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), skippingApplied = skipInfo && skipInfo.skippingApplied, plotDrawArray = skipInfo && skipInfo.labelDraw || [], plotDrawArrayLength = plotDrawArray.length, startIndex = (0, _lib.pluckNumber)(start, 0), endIndex = (0, _lib.pluckNumber)(end, skippingApplied ? plotDrawArrayLength : len), notParticularLabeDraw = plotDrawArrayLength === Math.abs(endIndex - (startIndex + 1)), callbackFn = function callbackFn() { this.attr({ 'text-bound': [] }); this.hide(); }; dataLabelContainer = dataSet.getContainer('labelGroup'); dataLabelContainer.css({ fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight, fontStyle: style.fontStyle }); dataLabelContainer.show(); smartLabel.useEllipsesOnOverflow(chart.config.useEllipsesWhenOverflow); smartLabel.setStyle(style); for (j = startIndex; j < endIndex; j++) { i = skippingApplied && notParticularLabeDraw ? plotDrawArray[j] : j; dataObj = dataStore[i]; config = dataObj && dataObj.config; setValue = config && config.setValue; // Condition arises when user has removed data in real time update if (dataObj === UNDEF || setValue === UNDEF || setValue === null || config.labelSkip === true) { config && delete config.labelSkip; tempGraphics = dataObj && dataObj.graphics; if (tempGraphics) { tempGraphics.label && tempGraphics.label.hide(); } continue; } graphic = dataObj.graphics; // Condition arises when feedData enters less number of data in a dataset compared to the other. if (!graphic) { continue; } showValue = config.showValue; if (!showValue || setValue === null) { if (graphic.label) { graphic.label.attr({ 'text-bound': [] }); graphic.label.hide(); } continue; } attr = config.props.label.attr; xPos = dataObj._xPos; // Positioning made for real time update. if (!graphic.label && labelDrawn && chart.isRealTime) { attr2 = (0, _lib.extend2)({}, attr); attr2.x = attr.x - xPos + (dataObj._newXPos || 0); attr2.transform = paper.getSuggestiveRotation(rotateValues, attr2.x, attr.y); if (pool && pool.label[0]) { graphic.label = pool.label[0]; pool.label.splice(0, 1); } } attr.transform = paper.getSuggestiveRotation(rotateValues, attr.x, attr.y); if (!(label = graphic.label)) { if (pool && pool.label[0]) { label = graphic.label = pool.label[0]; pool.label.splice(0, 1); } } label = animationManager.setAnimation({ el: graphic.label || 'text', attr: attr, component: dataSet, label: 'plotLabel', index: i, container: dataLabelContainer, callback: !visible && callbackFn }); label && label.show(); if (!graphic.label) { graphic.label = dataSet.addGraphicalElement('plotLabel', label, true); } } conf.labelDrawn = true; }; /** * function to calculate label position * @param {Object} config config reference of the data plot * @return {Object} contains x,y co-ordinate */ ColumnDataset.prototype._getValuePosition = function _getValuePosition(config) { var dataset = this, chart = dataset.getFromEnv('chart'), children = chart.getChildren(), chartConf = chart.config, yAxis = children.yAxis[0], xDepth = chartConf.xDepth || 0, yDepth = chartConf.yDepth || 0, canvasTop = chartConf.canvasTop, canvasHeight = chartConf.canvasHeight + yDepth, outsideColSpace, textX, textY, insideColSpace, isNegative, textHeight, yPos = config.yPos, is3D = chart.config.is3D, isStacked = chart.config.isstacked, valuePadding = chartConf.valuepadding + 2, height = config.height, width = config.width, yAdjust, placeValuesInside = chartConf.placevaluesinside, labelHeight = config.labelHeight, isInverseAxis = yAxis.getAxisConfig('isReverse'), value = config.value, valueBelowPlot, xPos = config.xPos, origTextHeight; if (!isInverseAxis) { if (value < 0) { valueBelowPlot = false; } else { valueBelowPlot = true; } } isNegative = (0, _lib.pluck)(valueBelowPlot, value < 0); textHeight = origTextHeight = labelHeight + valuePadding; insideColSpace = height; yAdjust = origTextHeight * 0.5 + valuePadding; textY = yPos - yAdjust; textX = xPos + width * 0.5; if (isNegative) { outsideColSpace = canvasTop + canvasHeight - (yPos + height + yDepth); textY = yPos; } else { outsideColSpace = yPos - canvasTop; } if (isStacked) { textY = yPos + height * 0.5 + (yDepth || 0); // For stacked charts restrict the data values inside the canvas. textY = mathMin(canvasTop + canvasHeight - textHeight * 0.5, textY); textY = mathMax(canvasTop + textHeight * 0.5, textY); textX -= xDepth; } else { if (placeValuesInside) { // If space available inside column if (insideColSpace >= textHeight) { textY = yPos + (isNegative ? height - yAdjust : yAdjust); if (is3D) { textX -= xDepth; textY += yDepth; } } else if (outsideColSpace >= textHeight) { // If space not available inside column // Try to fit the label outside column textY = yPos + (isNegative ? height + yAdjust : -yAdjust); if (is3D && isNegative) { textX -= xDepth; textY += yDepth; } } else { textY = yPos + (isNegative ? height - yAdjust : yAdjust); if (is3D) { textX -= xDepth; textY += yDepth; } } // If space not available inside or outside column // find the larger space available and place the column } else { // If space is available inside column if (outsideColSpace >= textHeight) { textY = yPos + (isNegative ? height + yAdjust : -yAdjust); if (is3D) { if (isNegative) { textX -= xDepth; textY += yDepth; } else { textX -= xDepth / 2; } } } else if (insideColSpace >= textHeight + yAdjust) { textY = yPos + (isNegative ? height - yAdjust : yAdjust); if (is3D) { textX -= xDepth; textY += yDepth; } } else { textY = yPos + (isNegative ? height - yAdjust : yAdjust); if (is3D) { textX -= xDepth; textY += yDepth; } } } } return { textX: textX, textY: textY }; }; /** * Function to get the maximum and minimum from dataset * @return {Object} contains max, min value */ ColumnDataset.prototype.getDataLimits = function getDataLimits() { return { max: this.config.maxValue, min: this.config.minValue }; }; /* REAL TIME FUNCTIONS */ /** * Function to add dataset to the existing dataset. * @param {Object} dataObj new data to add into dataset * @param {number} index from which index data would be added * @param {boolean} draw whether call draw or not */ ColumnDataset.prototype.addData = function addData(dataObj, index, draw) { var dataSet = this, components = dataSet.components, dataStore = components.data, data = dataObj.data, len = data.length, i; components.addDataArr = dataObj.data; // Storing the direction of input data for the type of animation to be done during draw. if (index === 0) { dataSet.startPosition = true; } else if (index + len === dataStore.length || index === UNDEF) { dataSet.startPosition = false; } for (i = 0; i < len; i++) { if (index !== UNDEF) { dataStore.splice(index + i, 0, { config: {} }); } else { dataStore.push({ config: {} }); } } dataSet._setConfigure(dataObj, index); draw && dataSet.asyncDraw(); }; /** * Function to remove a data with a given index. * @param {number} index from which index data would be removed * @param {number} stretch delete count * @param {boolean} draw whether draw or not */ ColumnDataset.prototype.removeData = function removeData(index, stretch, draw) { var dataSet = this, chart = dataSet.getFromEnv('chart'), components = dataSet.components, dataStore = components.data, removeDataArr = components.removeDataArr || (components.removeDataArr = []), i, len; stretch === UNDEF && (stretch = 1); index = index || 0; // Storing the direction of input data for the type of animation to be done during remove. if (index + stretch === dataStore.length || !chart.isRealTime) { dataSet.endPosition = true; } else if (index === 0 || index === UNDEF) { dataSet.endPosition = false; } components.removeDataArr = removeDataArr = removeDataArr.concat(dataStore.splice(index, stretch)); len = removeDataArr.length; for (i = len - 1; i >= 0; i--) { if (!removeDataArr[i]) { removeDataArr.splice(i, 1); continue; } } dataSet.removeDataLen = len; draw && dataSet.asyncDraw(); }; // @TODO have to remove this function after validation /** * Function to an existing data of a dataset. * @param {Object} dataObj data JSON * @param {integer} index The data index which needs to be updated * @param {boolean} draw Indicates whether the chart should redraw itself or not */ ColumnDataset.prototype.updateData = function updateData(dataObj, index, draw) { var dataSet = this, conf = dataSet.config, prevMax = conf.maxValue, prevMin = conf.prevMin, chart = dataSet.getFromEnv('chart'), drawManager = dataSet.groupManager || dataSet, // chartComponents = chart.components, // hasAxes = chartComponents.xAxis || chartComponents.yAxis, xAxis = chart.getFromEnv('xAxis'), yAxis = chart.getFromEnv('yAxis'); dataSet._setConfigure(dataObj, index); dataSet.getDataLimits(); if (conf.maxValue !== prevMax || conf.minValue !== prevMin) { dataSet.maxminFlag = true; } if (draw) { chart._setAxisLimits(); xAxis && xAxis[0].asyncDraw(); yAxis && yAxis[0].asyncDraw(); drawManager.asyncDraw(); } }; /** * Function to remove a data from a dataset * @param {Object} anim temporary code */ ColumnDataset.prototype.removePlots = function removePlots() { var dataSet = this, components = dataSet.components, removeDataArr = components && components.removeDataArr; _removePlots(removeDataArr, dataSet.__removeElem); }; /** * removes graphical elements as data plots are not components * so this API is basically handles the remove animation and * removal of element for a case of single graphics remove * @param {Element} el graphics elem * @param {String} type type of element */ ColumnDataset.prototype.removeGraphicElem = function removeGraphicElem(el, type) { this.__removeElem(el, type); }; /** * function to return defalut value padding * @return {Object} default padding value for axis */ ColumnDataset.prototype.getAxisValuePadding = function getAxisValuePadding() { return this.config.defaultPadding; }; /** * This functions calculate the space required for a dataset and return that to the chart * @return {Object} dimention */ ColumnDataset.prototype.getCanvasPadding = function getCanvasPadding() { var dataset = this, conf = dataset.config || (dataset.config = {}), components = dataset.components || {}, chart = dataset.getFromEnv('chart'), rotateValues = chart.config.rotatevalues, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), dataLabelStyle = chart.config.dataLabelStyle, skippingInfo = dataset.getSkippingInfo(), skippingApplied = skippingInfo.skippingApplied, drawArr = skippingInfo.draw, data = components.data || [], leftMostDataIndex = skippingApplied ? drawArr[0] : 0, rightMostDataIndex = skippingApplied ? drawArr[drawArr.length - 1] : data.length - 1, firstData = conf.leftMostData || data[leftMostDataIndex], lastData = conf.rightMostData || data[rightMostDataIndex], dataConf, label, dataAnchorConf, labelDimEnd = {}, labelDimStart = {}, anchorSpace = 0, labelSpace = 0, anchorPadding = 0, showValue, paddingPixel, startPixel = xAxis.getPixel(0), SmartLabel = dataset.getFromEnv('smartLabel'), retrunDimension = { paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 }, labelWidth = 0, // getting column width dimensions, padding = xAxis.getValuePadding(), topMostData = conf.topMostData, bottomMostData = conf.bottomMostData; dataset.setColumnPosition(); dimensions = { xPosOffset: dataset.getFromEnv('columnXShift'), columnWidth: dataset.getFromEnv('columnWidth'), height: UNDEF }; if (firstData) { dataConf = firstData.config; showValue = dataConf.showValue; dataAnchorConf = dataConf && dataConf.anchorProps || {}; if (showValue) { label = dataConf.displayValue; SmartLabel.useEllipsesOnOverflow(chart.config.useEllipsesWhenOverflow); SmartLabel.setStyle(dataLabelStyle); labelDimStart = SmartLabel.getOriSize(label); labelWidth = rotateValues ? labelDimStart.height : labelDimStart.width; } if (dataConf.setValue !== null) { paddingPixel = xAxis.getPixel(padding.left); // Check if anchor is enabled, if yes, use anchor radius anchorSpace = dataAnchorConf.enabled && (0, _lib.pluckNumber)(dataAnchorConf.radius, 0) + (0, _lib.pluckNumber)(dataAnchorConf.borderThickness, 0) / 2 || 0; // Finding the overlap of anchor with canvas border of the first data. anchorPadding = anchorSpace - (paddingPixel - startPixel); if (anchorPadding < 0) { anchorPadding = 0; } // Finding the overlap of data value label with canvas border of the first data. labelSpace = (labelWidth || 0) / 2 - (paddingPixel - startPixel) - (dimensions && dimensions.xPosOffset + dimensions.columnWidth / 2 || 0); if (labelSpace < 0) { labelSpace = 0; } } retrunDimension.paddingLeft = mathMax(anchorPadding, labelSpace); } anchorPadding = labelSpace = 0; if (lastData) { dataConf = lastData.config; showValue = dataConf.showValue; dataAnchorConf = dataConf && dataConf.anchorProps || {}; if (showValue && !rotateValues) { label = dataConf.displayValue; SmartLabel.setStyle(dataLabelStyle); labelDimEnd = SmartLabel.getOriSize(label); labelWidth = rotateValues ? labelDimEnd.height : labelDimEnd.width; } if (dataConf.setValue !== null) { paddingPixel = xAxis.getPixel(padding.right); // Check if anchor is enabled, if yes, use anchorradius anchorSpace = dataAnchorConf.enabled && (0, _lib.pluckNumber)(dataAnchorConf.radius, 0) + (0, _lib.pluckNumber)(dataAnchorConf.borderThickness, 0) / 2 || 0; // Finding the overlap of anchor with canvas border of the first data. anchorPadding = anchorSpace - (paddingPixel - startPixel); if (anchorPadding < 0) { anchorPadding = 0; } // Finding the overlap of data value label with canvas border of the last data. labelSpace = (labelWidth || 0) / 2 - (paddingPixel - startPixel) + (dimensions && dimensions.xPosOffset + dimensions.columnWidth / 2 || 0); if (labelSpace < 0) { labelSpace = 0; } } retrunDimension.paddingRight = mathMax(anchorPadding, labelSpace); } if (topMostData) { dataConf = topMostData.config; showValue = dataConf.showValue; dataAnchorConf = dataConf && dataConf.anchorProps || {}; if (dataConf.setValue !== null) { anchorSpace = (0, _lib.pluckNumber)(dataAnchorConf.radius, 0) + (0, _lib.pluckNumber)(dataAnchorConf.borderThickness, 0) / 2; labelSpace = Math.max(anchorSpace - (yAxis.getPixel(dataConf.setValue.y) - yAxis.getPixel(yAxis.getLimit().max)), 0); } retrunDimension.paddingTop = labelSpace; } if (bottomMostData) { dataConf = bottomMostData.config; dataAnchorConf = dataConf && dataConf.anchorProps || {}; if (dataConf.setValue !== null) { anchorSpace = (0, _lib.pluckNumber)(dataAnchorConf.radius, 0) + (0, _lib.pluckNumber)(dataAnchorConf.borderThickness, 0) / 2; labelSpace = Math.max(anchorSpace - (yAxis.getPixel(yAxis.getLimit().min) - yAxis.getPixel(dataConf.setValue.y)), 0); } retrunDimension.paddingBottom = labelSpace; } return retrunDimension; }; /** * function to get eventarg for this dataset * @return {Object} arguement object for event */ ColumnDataset.prototype.getEventArgs = function getEventArgs() { var dataset = this, config = dataset.config || {}, JSONData = dataset.config.JSONData || {}, eventArgs = { datasetName: JSONData.seriesname, datasetIndex: dataset.getJSONIndex(), id: config.userID, // @TODO this is temp fix, legendInteractivity handler is invoked after the legendClickEvent // is fired which is not correct. logically the legendInteractivity handler should be // invoked first so that event args gets updated properly visible: !dataset.getState('visible') }; return eventArgs; }; /** * return data in current datasets * @return {Object} [data of current dataset] */ ColumnDataset.prototype.getData = function getData() { return this.components.data; }; /** * function to set index for the dataset component * @param {number} index index according to the index JSON */ ColumnDataset.prototype.setJSONIndex = function setJSONIndex(index) { this.config.index = index; }; /** * function to return index for the dataset component * @return {number} index according to the index JSON */ ColumnDataset.prototype.getJSONIndex = function getJSONIndex() { return this.config.index || 0; }; /** * Marks this dataset for disposal during the next draw cycle * @param {Object} config Has a 'instant' member to indicate whether the component should be * immediately disposed or disposed later when animation completes */ ColumnDataset.prototype.remove = function remove(config) { var dataset = this, legendItemId = dataset.config.legendItemId, legends = dataset.getFromEnv('chart').getChildren('legend'), legend = dataset.getFromEnv('legend'); legends && legends.length && legend && legendItemId && legend.disposeItem(legendItemId); _ComponentInterface.prototype.remove.call(this, config); }; /** * Set the max and min of data during real time update. * @param {Object} dataObj data object for a specific plot that is chaged via some interaction * like dragging. */ ColumnDataset.prototype.setMaxMin = function setMaxMin(dataObj) { var dataSet = this, dataComponents = dataSet.components, dataStore = dataComponents.data, removeDataArr = dataComponents.removeDataArr, conf = dataSet.config, i, config, len = dataStore.length, setValue, maxValue = -Infinity, minValue = +Infinity, dataMax = conf.maxValue, dataMin = conf.minValue, removeLen = removeDataArr.length, proceedFlag = false, value; if (dataObj) { proceedFlag = dataMax === dataObj.startValue || dataMin === dataObj.startValue || dataMax < dataObj.config.setValue || dataMin > dataObj.config.setValue; } else if (removeLen) { // if the data removed affects the axis's limit then only we will check for the new limit of // the data present in the canvas and then set limit to config else we will not check the // limit of all data for (i = 0; i < removeLen; ++i) { value = removeDataArr[i] && removeDataArr[i].config && removeDataArr[i].config.setValue; if (dataMax === value || dataMin === value) { proceedFlag = true; break; } } } if (!proceedFlag) { return; } for (i = 0; i < len; i++) { if (!dataStore[i]) { continue; } config = dataStore[i].config; setValue = config.setValue; if (setValue !== UNDEF) { maxValue = mathMax(maxValue, setValue); minValue = mathMin(minValue, setValue); } } conf.maxValue = maxValue; conf.minValue = minValue; }; return ColumnDataset; }(_componentInterface.ComponentInterface); exports._removePlots = _removePlots; exports['default'] = ColumnDataset; /***/ }), /* 433 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); exports['default'] = { 'initial.dataset.column': function initialDatasetColumn() { var component = this, chart = component.getFromEnv('chart'), yDepth = chart.config.yDepth || 0, yAttrKey = 'y', hAttrKey = 'height', xAttrKey = 'x', wAttrKey = 'width', plot1SKey = '_plot_1Start', plot1EKey = '_plot_1End', plot2SKey = '_plot_2Start', yAxis = component.getFromEnv('yAxis'), xAxis = component.getFromEnv('xAxis'), _axisSync = function _axisSync(inputJSON, dataObj) { var conf = component.config, setElement = dataObj && dataObj.graphics && dataObj.graphics.element, finalAttr = inputJSON.attr, oldAttr, oldYVal, oldYPlusH, newZeroPos = yAxis.getPixel(yAxis.getAxisBase()) + (chart.isBar ? -yDepth : yDepth), axisEndAttr = {}, oldZeroAxisPos = conf.oldZeroAxisPos, // axis = options.anim.axis, hasWithAxisAnim, crispingGutter = 0.7; oldAttr = setElement.attr(); axisEndAttr[yAttrKey] = oldYVal = oldAttr[yAttrKey]; axisEndAttr[hAttrKey] = oldAttr[hAttrKey]; axisEndAttr[xAttrKey] = oldAttr[xAttrKey]; axisEndAttr[wAttrKey] = oldAttr[wAttrKey]; oldYPlusH = oldAttr[yAttrKey] + oldAttr[hAttrKey]; // ** yAxis Animation ** // if (newZeroPos !== oldZeroAxisPos) { // NOTE: (crispingGutter = 0.7) is a gutter to accomodate the displacement due to crisping if (oldZeroAxisPos - newZeroPos >= 0) { // Axis Base Moves Upword // If y stays in between if (oldYVal > newZeroPos && oldYVal <= oldZeroAxisPos + crispingGutter) { axisEndAttr[yAttrKey] = newZeroPos; if (oldYPlusH > oldZeroAxisPos) { axisEndAttr[hAttrKey] = oldYPlusH - axisEndAttr[yAttrKey]; } } // If y + h stays in between if (oldYPlusH > newZeroPos && oldYPlusH <= oldZeroAxisPos + crispingGutter) { axisEndAttr[hAttrKey] = newZeroPos - (axisEndAttr[yAttrKey] || axisEndAttr[yAttrKey] === 0 ? axisEndAttr[yAttrKey] : oldYVal); } } else { // Axis Base Moves Downwords // If y stays in between if (oldYVal < newZeroPos && oldYVal >= oldZeroAxisPos - crispingGutter) { axisEndAttr[yAttrKey] = newZeroPos; if (oldYPlusH > newZeroPos) { axisEndAttr[hAttrKey] = oldYPlusH - axisEndAttr[yAttrKey]; } } // If y + h stays in between if (oldYPlusH < newZeroPos && oldYPlusH >= oldZeroAxisPos - crispingGutter) { axisEndAttr[hAttrKey] = newZeroPos - (axisEndAttr[yAttrKey] || axisEndAttr[yAttrKey] === 0 ? axisEndAttr[yAttrKey] : oldYVal); } } hasWithAxisAnim = true; } // ** x-axis animation sync ** // if (component.config.catDiff) { // TODO: need to fix this. This will not be exactly the final attr // Because there might me cases where the no of column got reduced as well as cat decreased axisEndAttr[xAttrKey] = finalAttr[xAttrKey]; axisEndAttr[wAttrKey] = finalAttr[wAttrKey]; hasWithAxisAnim = true; } // Store intermideate states dataObj[plot1SKey] = axisEndAttr; if (hasWithAxisAnim) { return { finalAttr: axisEndAttr, slot: 'axis' }; } }, UNDEF; return { 'rect.appearing': function rectAppearing(inputJSON) { var zeroPos = yAxis.getPixel(yAxis.getAxisBase()) + (chart.isBar ? -yDepth : yDepth), index = inputJSON.props && inputJSON.props.originalIndex || inputJSON.index, dataObj = component.components.data[index], actualFinalAttr = inputJSON.attr, yAttrVal, hAttrVal, yBasePos, endPosWRT0; // To make it working for bar charts even just change the keys if (xAxis.config.isVertical) { yAttrKey = 'x'; hAttrKey = 'width'; xAttrKey = 'y'; wAttrKey = 'height'; } // Store final y and h for later use yAttrVal = actualFinalAttr[yAttrKey]; hAttrVal = actualFinalAttr[hAttrKey]; endPosWRT0 = Math.sign(yAttrVal + hAttrVal / 2 - zeroPos); // If the plot is below zero plain, the base will be the y + h of the previousone // if it is stackked plot else y of the plot if (endPosWRT0 === 1) { yBasePos = yAttrVal; } else { // the base will be the y of the previousone if it is stackked plot else y+h of itself yBasePos = yAttrVal + hAttrVal; } dataObj._posWRT0 = endPosWRT0; return [{ initialAttr: function initialAttr() { var initialAttr = {}; // Replace the y and h with initial positions initialAttr[yAttrKey] = yBasePos; initialAttr.opacity = 0; initialAttr[hAttrKey] = 0; return initialAttr; }, finalAttr: { opacity: 1 }, // slot: 'axis', startEnd: function startEnd() { var length = inputJSON.length; return _lib.animHelperFN.getTimeByValue(_lib.animHelperFN.animByWeight(inputJSON.index, length, 0.6), { startPx: zeroPos, endPx: endPosWRT0 === 1 ? component.config.yAxisMaxPixel : component.config.yAxisMinPixel }, { startPx: yBasePos, endPx: endPosWRT0 === 1 ? actualFinalAttr[yAttrKey] + actualFinalAttr[hAttrKey] : actualFinalAttr[yAttrKey] }); }, hookFn: function hookFn() { this.attr({ opacity: 1 }); }, effect: 'linear', slot: 'plot' }]; }, 'rect.updating': function rectUpdating(inputJSON) { var returnArr = [], dataObj = component.components.data[inputJSON.props && inputJSON.props.originalIndex || inputJSON.index], finalAttr = inputJSON.attr, setElement = dataObj && dataObj.graphics && dataObj.graphics.element, startY, startH, startYPlusH, startPlotCenter, endY, endH, endYPlusH, endPlotCenter, zeroPos = yAxis.getPixel(yAxis.getAxisBase()) + (chart.isBar ? -yDepth : yDepth), start = 0, numColDiff = component.getFromEnv('numColDiff'), step1Start = {}, hasPlot1Anim, step1End, // Stores the final attributes of plot's 1st step animation step2Start, // Stores the initial attributes of plot's 2nd step animation prevDataObj, base1StartAttr, base2StartAttr, oldPrevDataObj, oldBase1EndAttr, middleYplusH, hasTransitionDiff, base1EndAttr, startPosWRT0, endPosWRT0, step1EndBase, effectiveBasePos, step2HookFn, step1HookFn, preHookAttr, nonDimensionAttr, val; // To make it working for bar charts even just change the keys if (xAxis.config.isVertical) { yAttrKey = 'x'; hAttrKey = 'width'; xAttrKey = 'y'; wAttrKey = 'height'; } if (val = _axisSync(inputJSON, dataObj)) { returnArr.push(val); } prevDataObj = dataObj.prevDataObj; base1StartAttr = prevDataObj && prevDataObj[plot1SKey]; base1EndAttr = prevDataObj && prevDataObj[plot1EKey]; base2StartAttr = prevDataObj && prevDataObj[plot2SKey]; oldPrevDataObj = dataObj.oldPrevDataObj; oldBase1EndAttr = dataObj.oldPrevDataObj && dataObj.oldPrevDataObj[plot1EKey]; step1Start = dataObj[plot1SKey]; startY = step1Start[yAttrKey]; startH = step1Start[hAttrKey]; startYPlusH = startY + startH; startPlotCenter = startY + startH / 2; endY = finalAttr[yAttrKey]; endH = finalAttr[hAttrKey]; endYPlusH = endY + endH; endPlotCenter = endY + endH / 2; middleYplusH = (startYPlusH + endYPlusH) / 2; startPosWRT0 = Math.sign(startPlotCenter - zeroPos); endPosWRT0 = Math.sign(endPlotCenter - zeroPos); step1End = {}; step2Start = {}; // Calculate the value of step2Start and step2Start even if it is single step animation step2Start[yAttrKey] = step1End[yAttrKey] = (startY + endY) / 2; step2Start[hAttrKey] = step1End[hAttrKey] = (startH + endH) / 2; // ** Plot_1 [optional] animation step if (startH) { // if the plot is moving from one side of the zero plain to another if (startPosWRT0 !== endPosWRT0) { // Hight will decrease to 0 on the first half step2Start[hAttrKey] = step1End[hAttrKey] = 0; step1End[yAttrKey] = oldPrevDataObj && oldPrevDataObj._oldPosWRT0 === startPosWRT0 ? oldBase1EndAttr[yAttrKey] + (startPosWRT0 === 1 ? oldBase1EndAttr[hAttrKey] : 0) : zeroPos; // At the end of plot_1End it should jump to opposite direction [i.e plot_2Start] step2Start[yAttrKey] = base2StartAttr ? base2StartAttr[yAttrKey] + (endPosWRT0 === 1 ? base2StartAttr[hAttrKey] : 0) : zeroPos; // Set flags hasTransitionDiff = hasPlot1Anim = true; } else if (prevDataObj !== oldPrevDataObj) { step1EndBase = oldBase1EndAttr || (base1EndAttr && Math.sign(base1EndAttr[yAttrKey] + base1EndAttr[hAttrKey] / 2 - zeroPos) === startPosWRT0 ? base1EndAttr : false); effectiveBasePos = step1EndBase ? step1EndBase[yAttrKey] + (startPosWRT0 === 1 ? step1EndBase[hAttrKey] : 0) : zeroPos; if (startPosWRT0 === 1) { step2Start[yAttrKey] = step1End[yAttrKey] = effectiveBasePos; step2Start[hAttrKey] = step1End[hAttrKey] = middleYplusH - step1End[yAttrKey]; } else { step2Start[hAttrKey] = step1End[hAttrKey] = effectiveBasePos - step1End[yAttrKey]; } hasPlot1Anim = true; } } else { // If the plot is getting zero height after axis animation, then move it to new base // only if the base is already at the final side of the zero plane or it is the first // dataset of the stack if (prevDataObj && prevDataObj._oldPosWRT0 === endPosWRT0 || component.stackIndex === 0) { preHookAttr = {}; preHookAttr[hAttrKey] = 0; preHookAttr[yAttrKey] = base1StartAttr ? base1StartAttr[yAttrKey] + (prevDataObj._posWRT0 > 0 ? base1StartAttr[hAttrKey] : 0) : zeroPos; // Reset this so that plots on top of this will act lyke this was on the same side dataObj._posWRT0 = endPosWRT0; dataObj[plot1SKey] = preHookAttr; // Reset the middle steps attributes step2Start[yAttrKey] = step1End[yAttrKey] = (preHookAttr[yAttrKey] + endY) / 2; step2Start[hAttrKey] = step1End[hAttrKey] = endH / 2; } else if (startPlotCenter === zeroPos) { // Datasets those are not at the bottom of the stack should wait for the next half to // complete the remaining animations others of that side if (endPosWRT0 !== dataObj._posWRT0) { start = 0.5; } else { hasPlot1Anim = true; step1End[yAttrKey] = endPosWRT0 === 1 ? zeroPos : zeroPos - step1End[hAttrKey]; } } } // If no of column is getting increased then reduce the width in the first half if (numColDiff < 0) { step1End[xAttrKey] = finalAttr[xAttrKey]; step1End[wAttrKey] = finalAttr[wAttrKey]; hasPlot1Anim = true; } else if (numColDiff > 0) { // else Animate the visible plot at the 2nd half start = 0.5; } else if (step1Start[xAttrKey] !== finalAttr[xAttrKey] || step1Start[wAttrKey] != finalAttr[wAttrKey]) { if (start === 0.5) { preHookAttr = {}; preHookAttr[xAttrKey] = finalAttr[xAttrKey]; preHookAttr[wAttrKey] = finalAttr[wAttrKey]; step2HookFn = function step2HookFn() { if (hasTransitionDiff) { setElement.attr(step2Start); } setElement.attr(preHookAttr); }; } else { step1End[xAttrKey] = finalAttr[xAttrKey]; step1End[wAttrKey] = finalAttr[wAttrKey]; hasPlot1Anim = true; if (step2HookFn) { step1HookFn = function step1HookFn() { setElement.attr(preHookAttr); }; step2HookFn = UNDEF; } } } // If Plot_1Anim is their then set it if (hasPlot1Anim) { returnArr.push({ finalAttr: step1End, startEnd: { start: 0, end: 0.5 }, hookFn: step1HookFn, slot: 'plot' }); start = 0.5; } !step2HookFn && (step2HookFn = function step2HookFn() { if (hasTransitionDiff) { setElement.attr(step2Start); } }); returnArr.push({ effect: 'linear', startEnd: { start: start, end: 1 }, finalAttr: { x: finalAttr.x, y: finalAttr.y, width: finalAttr.width, height: finalAttr.height }, callback: function callback() { if (dataObj.config.setValue === null || dataObj.config.setValue === UNDEF) { this.hide(); } }, hookFn: step2HookFn, slot: 'plot' }); nonDimensionAttr = Object.assign({}, finalAttr); delete nonDimensionAttr.x; delete nonDimensionAttr.y; delete nonDimensionAttr.width; delete nonDimensionAttr.height; returnArr.push({ finalAttr: nonDimensionAttr, effect: 'linear', slot: 'plot' }); // Store intermideate states dataObj[plot1EKey] = step1End; dataObj[plot2SKey] = step2Start; dataObj._oldPosWRT0 = dataObj._posWRT0; dataObj._posWRT0 = endPosWRT0; return returnArr; }, 'rect._disappearing': function rect_disappearing(inputJSON) { var zeroPos = yAxis.getPixel(yAxis.getAxisBase()) + (chart.isBar ? -yDepth : yDepth), removeDataArr = component.components.removeDataArr, dataObj = removeDataArr && removeDataArr[inputJSON.props && inputJSON.props.originalIndex || inputJSON.index] || component.components.data[inputJSON.props && inputJSON.props.originalIndex || inputJSON.index], setElement = dataObj && dataObj.graphics && dataObj.graphics.element, oldBase1EndAttr = dataObj.oldPrevDataObj && dataObj.oldPrevDataObj[plot1EKey], yBasePos, yAttrVal, attr, val, plot1StartAtt, returnArr = []; if (!setElement) { return; } // Call the axis sync animation first if (val = _axisSync(inputJSON, dataObj)) { returnArr.push(val); } // To make it working for bar charts even just change the keys if (!yAxis.config.isVertical) { yAttrKey = 'x'; hAttrKey = 'width'; } plot1StartAtt = dataObj[plot1SKey]; // Store final y and h for later use yAttrVal = plot1StartAtt[yAttrKey]; // If the plot is below zero plain, the base will be the y + h of the previousone // if it is stackked plot else y of the plot if (yAttrVal + plot1StartAtt[hAttrKey] / 2 > zeroPos) { yBasePos = oldBase1EndAttr ? oldBase1EndAttr[yAttrKey] + oldBase1EndAttr[hAttrKey] : yAttrVal; } else { // the base will be the y of the previous one if it is stackked plot else y+h of itself yBasePos = oldBase1EndAttr ? oldBase1EndAttr[yAttrKey] : zeroPos; } attr = {}; // Replace the y and h with initial positions attr[yAttrKey] = yBasePos; attr[hAttrKey] = 0; attr.width = dataObj._width; attr.x = dataObj._xPos; returnArr.push({ startEnd: { start: 0, end: component.getFromEnv('numOfColumns') < 1 ? 1 : 0.5 }, finalAttr: attr, slot: 'plot' }); // Store the attributes at the end of 1st half plot animation dataObj[plot1EKey] = inputJSON.finalAttr; return returnArr; }, 'plotLabel.appearing': [{ initialAttr: { opacity: 0 }, slot: 'final' }], 'plotLabel._disappearing': [{ hookFn: function hookFn() { this.hide(); }, slot: 'initial' }], 'plotLabel.updating': [{ hookFn: function hookFn() { this.hide(); }, slot: 'initial' }, { hookFn: function hookFn() { this.show(); }, initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'group.appearing': function groupAppearing(inputJSON) { if (inputJSON.attr.name === 'label-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } else { return [{ initialAttr: { opacity: 1 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } }, '*': null }; } }; /***/ }), /* 434 */, /* 435 */, /* 436 */, /* 437 */, /* 438 */, /* 439 */, /* 440 */, /* 441 */, /* 442 */, /* 443 */, /* 444 */, /* 445 */, /* 446 */, /* 447 */, /* 448 */, /* 449 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _area = __webpack_require__(450); var _area2 = _interopRequireDefault(_area); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(452); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * @typedef {Object} Range * @property {number} min The minimum value in the dataset * @property {number} max The maximum value in the dataset */ var UNDEF, math = Math, // mathPow = math.pow, mathAbs = math.abs, MAX_MITER_LINEJOIN = 2; (0, _dependencyManager.addDep)({ name: 'lineAnimation', type: 'animationRule', extension: _index2['default'] }); /** * Creates the Line Dataset * @class */ var LineDataset = function (_AreaDataset) { _inherits(LineDataset, _AreaDataset); /** * Constructor class for instantiation */ function LineDataset() { _classCallCheck(this, LineDataset); var _this = _possibleConstructorReturn(this, _AreaDataset.call(this)); _this.updateYForStack = _lib.stubFN; _this.config.primitiveType = 'line'; return _this; } /** * Sets the type of the component * @return {string} type */ LineDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ LineDataset.prototype.getName = function getName() { return 'line'; }; /** * Creates Pinnable graphics of a dataset for Pin feature */ LineDataset.prototype.createPinElem = function createPinElem() { var dataset = this, chart = dataset.getFromEnv('chart'), group = arguments[1].group, lineOb = dataset.config.lineOb, element, pinElems = dataset.getGraphicalElement('pinElems') || dataset.addGraphicalElement('pinElems', []), paper = dataset.getFromEnv('paper'), lineGroup = dataset.getLinkedParent().getChildContainer('lineVcanvasGroup'), i, key; for (i = pinElems.length - 1; i >= 0; i--) { pinElems[i].remove(); pinElems.pop(); } if (dataset.getState('visible')) { for (key in lineOb) { element = lineOb[key].el; pinElems.push(paper.path(group).attr({ 'path': element.attrs.path, 'transform': ['T', -(chart.config._visx + mathAbs(lineGroup.transform()[0][1])), -chart.config.canvasBottom] }).attr(dataset.config.pin)); } } }; /** * Add legend items for each Dataset */ LineDataset.prototype._addLegend = function _addLegend() { var dataset = this, chart = dataset.getFromEnv('chart'), conf = dataset.config, legend = chart.getChildren('legend')[0], drawAnchors = (0, _lib.pluckNumber)(conf.drawanchors, 1), legendItem, config; if (conf.includeinlegend) { config = { enabled: conf.includeinlegend, type: dataset.getName(), /* In case of scatter (a child chartAPI of line), line is drawn in legend only when drawLine is set to true. */ drawLine: (0, _lib.pluck)(conf.drawLine, true), index: dataset.getJSONIndex(), anchorSide: drawAnchors ? conf.anchorsides : 0, label: (0, _lib.getFirstValue)(dataset.config.JSONData.seriesname) }; legendItem = legend.getItem(dataset.config.legendItemId); if (!legendItem) { dataset.config.legendItemId = legend.createItem(dataset); legendItem = legend.getItem(dataset.config.legendItemId); dataset.addExtEventListener('fc-click', function () { legendItem.itemClickFn(); }, legendItem); } legendItem.setStateCosmetics('default', { symbol: { fill: (0, _lib.toRaphaelColor)({ color: conf.anchorbgcolor, alpha: conf.anchorbgalpha }), rawFillColor: conf.anchorbgcolor, rawStrokeColor: conf.anchorbordercolor, stroke: (0, _lib.toRaphaelColor)({ color: conf.anchorbordercolor, alpha: '100' }), 'stroke-width': conf.anchorborderthickness, lineWidth: conf.linethickness } }); // check if dataset is initiallyhidden if (!dataset.getState('visible')) { legendItem.setLegendState('hidden'); } else { // remove hidden state of legend item is dataset is not hidden legendItem.removeLegendState('hidden'); } legendItem.configure(config); } else if (dataset.config.legendItemId) { legend.disposeItem(dataset.config.legendItemId); } }; /** * Calculates and returns the data limit range of a dataset * @return {Range} Value Range of a dataset */ LineDataset.prototype._getDataLimits = function _getDataLimits() { var dataset = this, conf = dataset.config, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, max = conf.maxValue, min = conf.minValue, infMin = -Infinity, infMax = +Infinity, transposeAxis = chartConfig.transposeAxis; if (dataset.getState('visible') === false && transposeAxis) { max = infMin; min = infMax; } return { max: max, min: min }; }; /** * draw the common elements,i.e., path of line * @param {Object} lineOb - Consists of the attributes of a path for a line */ LineDataset.prototype._drawCommonElementsHelper = function _drawCommonElementsHelper(lineOb) { var dataset = this, key = '', item = {}, animationManager = dataset.getFromEnv('animationManager'), dsConfig = dataset.config, shadow = dsConfig.shadow, lineThickness = dsConfig.linethickness, commonElemGroup = dataset.getContainer('commonElemsGroup'), fullPath, j, jj, callback = function callback() { if (dataset.getState('visible') === false) { this.hide(); } }; // Iterating over line storing Object for (key in lineOb) { item = lineOb[key]; // generate path and old path fullPath = ['M0,0']; for (j = 0, jj = item.path && item.path.length; j < jj; ++j) { fullPath = fullPath.concat(item.path[j].getPathArr()); } if (!dataset.config.drawLine) { item.el && (item.el = animationManager.setAnimation({ el: item.el, component: dataset, doNotRemove: true, callback: function callback() { this.hide(); } })); } else { item.el = animationManager.setAnimation({ el: item.el || 'path', container: commonElemGroup, component: dataset, attr: dataset.getState('visible') !== false && Object.assign({ path: fullPath }, item.attr), label: 'line', callback: callback }); dataset.getState('visible') && item.el && item.el.show(); } !item.used && delete lineOb[key]; if (item.el) { // Applying shadow if linethickness is present if (lineThickness) { item.el.shadow(shadow, commonElemGroup); } else { // else remove the previously applied shadow from the element item.el.shadow({ opacity: 0 }, commonElemGroup); } // Putting line element before shadow item.el.toFront(); } // Mark for next event that // this element was before item.old = true; item.used = false; item.prevPath = item.path; item.attrs = UNDEF; item.path = UNDEF; } }; /** * Calculate the shift of line plot for 2D, 3D charts * @param {string} type - Determines x axis or y axis * @return {number} Value of shift */ LineDataset.prototype.getLineShift = function getLineShift(type) { var dataset = this, chart = dataset.getFromEnv('chart'), is3D = chart.config.is3D, use3dlineshift = chart.config.use3dlineshift, xDepth = is3D ? 10 : 0, yDepth = is3D ? use3dlineshift ? 0 : -10 : 0; return type === 'y' ? yDepth : xDepth; }; /** * Function to draw line * @param {Object} anim The animation object which will be passed to animation manager. All * animation configuration should be pushed into this. * Line chart has a setLevel attribute 'color', thus line segments can have different colors, * but a line path can support only one color, so we are making multiple paths depending on the * color applied. lineOb is object having all line elements and key is the color and stroke combined, * thus all line segment having same color is grouped under one key. elements having different * line color is animated by fading in and out, on main color's line element transition is applied. */ LineDataset.prototype.drawCommonElements = function drawCommonElements() { var dataset = this, dataStore = dataset.components.data, dsConfig = dataset.config, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), // styles lineDashStyle = dsConfig.lineDashStyle, dashStyle, lineThickness = dsConfig.linethickness, colorObj, lineColorObj = { color: dsConfig.linecolor, alpha: dsConfig.alpha }, lscthash = [(0, _lib.toRaphaelColor)(lineColorObj), lineDashStyle].join(':'), dataHash = lscthash, lim = { x: xAxis.getLimit(), y: yAxis.getLimit() }, i, j, ii = dataStore.length, lineOb = dataset.config.lineOb || {}, dataObj, colorHash, config, startIndex = 0, endIndex, connectorPath, connectorPathWithNulls, nullPointsArr, lineBreak = false, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), skippingDrawArray = skippingInfo && skippingInfo.draw || [], plotDrawArrayLength = skippingDrawArray.length, skippingApplied = skippingInfo && skippingInfo.skippingApplied, // function to add new line element depending on color // to the lineOb createLine = function createLine(key, path, pathwithnull) { var item = lineOb[key]; if (!item) { item = lineOb[key] = {}; } // Mark this item was used in this draw // function call if (key !== dataHash) { // Mark this line element as with a different color item.hasDifferentColor = true; } item.used = true; item.pathWithNull = pathwithnull; item.path = item.path || []; item.stroke = key.split(':')[0]; item.dashStyle = key.split(':')[1]; item.path.push(path); item.dashStyle = item.dashStyle && item.dashStyle.split(','); item.attr = { 'stroke-dasharray': item.dashStyle, 'stroke-width': lineThickness, 'stroke': item.stroke, 'stroke-linecap': 'round', 'stroke-linejoin': lineThickness > MAX_MITER_LINEJOIN ? 'round' : 'miter' }; }, tempStore = []; // Setting min and max pixels lim.x.minPixel = xAxis.getPixel(lim.x.min); lim.x.maxPixel = xAxis.getPixel(lim.x.max); lim.y.minPixel = yAxis.getPixel(lim.y.min); lim.y.maxPixel = yAxis.getPixel(lim.y.max); lim.y.base = yAxis.getPixel(0); lim.x.base = xAxis.getPixel(0); if (skippingApplied) { ii = plotDrawArrayLength; } for (j = 0; j < ii; ++j) { i = skippingDrawArray[j] || j; dataObj = dataStore[i]; if (!dataObj) { continue; } config = dataObj.config || {}; config._Pbx = UNDEF; config._Pby = UNDEF; // Pushing configurations to save // reference for later tempStore[i] = { config: { _Px: config._Px, _Py: config._Py, setValue: config.setValue } }; // Storing the color Object of this dat colorObj = { color: config.setColor, alpha: config.setAlpha }; dashStyle = config.dashStyle; colorHash = [(0, _lib.toRaphaelColor)({ color: (0, _lib.pluck)(colorObj.color, lineColorObj.color), alpha: (0, _lib.pluck)(colorObj.alpha, lineColorObj.alpha) }), dashStyle || lineDashStyle].join(':'); /** * Consider there are 10 points. Point 4 have dashed='1' and point 5's value is not provided. * Since colorHash !== lscthash for point 4, line from point 0 to point 4 is drawn. * When 5th point is considered, again the condition 'colorHash !== lscthash' is satisfied. * But now point 5 do not have any value. So, line will be drawn from point 4 to 5 but since, point 5 do not have value, * it is not possible. Hence the blank path is produced. (RED-5968). * Fix: Provide a check if value is provided or not. So, getLinePath will not be executeded for points having no value. * In point 6, when value is present, both the condition are satisfied. So a new line is drawn from point 4 to 6. */ if (lscthash !== colorHash && dataObj._yVal) { lineBreak = true; endIndex = i; connectorPath = dataset.getLinePath(dataStore, { begin: startIndex, end: endIndex + 1 }); connectorPathWithNulls = dataset.getLinePath(dataStore, { begin: startIndex, end: endIndex + 1 }, nullPointsArr); config.connStartIndex = startIndex; config.connEndIndex = endIndex; createLine(lscthash, connectorPath, connectorPathWithNulls.getPathArr()); lscthash = colorHash; startIndex = i; endIndex = null; } // Do not update lscthash when value is not provided. if (dataObj._yVal) { lscthash = colorHash; } } if (!colorHash) { colorHash = ''; } dsConfig.pathStartIndex = startIndex; dsConfig.pathEndIndex = endIndex; connectorPath = dataset.getLinePath(dataStore, { begin: lineBreak ? startIndex : dsConfig.scrollMinVal, end: lineBreak ? endIndex : dsConfig.scrollMaxVal }); connectorPathWithNulls = dataset.getLinePath(dataStore, { begin: startIndex, end: endIndex }, nullPointsArr); createLine(colorHash, connectorPath, connectorPathWithNulls.getPathArr()); dataset._drawCommonElementsHelper(lineOb); // Saving for next dataset.config.lineOb = lineOb; dsConfig.prevLim = lim; // Storing current datastore dsConfig.prevDataStore = tempStore; }; /** * Function to show the dataset and raise an event */ LineDataset.prototype.show = function show() { _AreaDataset.prototype.show.call(this); this.fireEvent('datasetVisibilityChanged', { dataset: this, state: 'show' }); }; /** * Function to hide the dataset and raise an event */ LineDataset.prototype.hide = function hide() { _AreaDataset.prototype.hide.call(this); this.fireEvent('datasetVisibilityChanged', { dataset: this, state: 'hide' }); }; return LineDataset; }(_area2['default']); exports['default'] = LineDataset; /***/ }), /* 450 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _lib = __webpack_require__(125); var _schedular = __webpack_require__(136); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(451); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF, isVML = !_lib.hasSVG, NONE = 'none', ROLLOVER = 'DataPlotRollOver', ROLLOUT = 'DataPlotRollOut', MOUSEOVER = 'mouseOver', MOUSEOUT = 'mouseOut', // hot/tracker threshold in pixels HTP = _lib.hasTouch ? _lib.TOUCH_THRESHOLD_PIXELS : _lib.CLICK_THRESHOLD_PIXELS, // add the tools thats are requared PLOTBORDERCOLOR = 'plotBorderColor', PLOTGRADIENTCOLOR = 'plotGradientColor', SHOWSHADOW = 'showShadow', POINTER = 'pointer', EVENTARGS = 'eventArgs', DATAPLOTCLICK = 'dataplotclick', LABELUPDATEONIMAGELOADID = 'labelUpdateOnImageLoadID', DEFAULT_CURSOR = _lib.preDefStr.DEFAULT, SETROLLOVERATTR = _lib.preDefStr.setRolloverAttrStr, SETROLLOUTATTR = _lib.preDefStr.setRolloutAttrStr, getPathArr = function getPathArr() { var pathObj = this, pathArr = pathObj.pathArr, path2Arr = pathObj.path2Arr; if (pathArr.length || path2Arr.length) { return pathArr.concat(path2Arr); } else { return ['M0,0']; } }, defined = function defined(obj) { return obj !== UNDEF && obj !== null && obj !== ''; }, M = 'M', L = 'L', Z = 'Z', math = Math, mathMin = math.min, mathMax = math.max, mathCeil = math.ceil, MAX_MITER_LINEJOIN = 2, _imageDrawHelper = function _imageDrawHelper(dataset, dataObj) { var chart = dataset.getFromEnv('chart'), chartConf = chart.config, config = dataObj.config, graphics = dataObj.graphics, imageElement = graphics.image || graphics.element, eventArgs = config.eventArgs, imgRef = imageElement._.RefImg, x = dataObj._xPos, y = dataObj._yPos, anchorProps = config.anchorProps, anchorShadowGroup = dataset.getContainer('shadowGroup'), trackerRadius = 2, hoverEffects = config.hoverEffects, setLink = config.setLink, scale = anchorProps.imageScale, alpha = anchorProps.imageAlpha, hoverAlpha = hoverEffects.imageHoverAlpha, hoverScale = hoverEffects.imageHoverScale, imgH = imgRef.height * scale * 0.01, imgW = imgRef.width * scale * 0.01, hotW = imgRef.width * hoverScale * 0.01, hotH = imgRef.height * hoverScale * 0.01, symbol = void 0, dip = void 0, markerRadius = void 0, anchorShadow = void 0, imageRolloverPath = void 0, rolloverClipRadius = void 0, imageRolloutPath = void 0, rolloutClipRadius = void 0, imagePadding = void 0, relImageAlpha = void 0, relImageHoverAlpha = void 0, setRolloverAttr = void 0, setRolloutAttr = void 0, anchorBackground = void 0, isAnchorRadius = void 0, isAnchorHoverRadius = void 0, cosmeticAttrs = void 0; isAnchorRadius = anchorProps.isAnchorRadius; anchorProps.markerRadius = markerRadius = anchorProps.radius = isAnchorRadius ? anchorProps.radius : mathMin(imgW, imgH) / 2; // if not VML then clip the image according to the anchor properties if (!isVML) { symbol = anchorProps.symbol[1]; isAnchorHoverRadius = hoverEffects.isAnchorHoverRadius; anchorShadow = anchorProps.shadow; imagePadding = anchorProps.imagePadding; hoverEffects.radius = isAnchorHoverRadius ? hoverEffects.anchorRadius : markerRadius + 1; rolloverClipRadius = hoverEffects.radius - imagePadding - hoverEffects.anchorBorderThickness * 0.5; rolloutClipRadius = markerRadius - imagePadding - anchorProps.borderThickness * 0.5; setRolloverAttr = setRolloutAttr = {}; chartConf.dragTolerance = chartConf.dragTolerance < markerRadius ? markerRadius + 0.5 : chartConf.dragTolerance; cosmeticAttrs = { fill: (0, _lib.toRaphaelColor)({ color: anchorProps.bgColor, alpha: anchorProps.bgAlpha }), 'stroke-width': anchorProps.borderThickness, stroke: (0, _lib.toRaphaelColor)({ color: anchorProps.borderColor, alpha: anchorProps.borderAlpha }) }; // preparing rolloutattributes will be set while rolling out of anchor setRolloutAttr = (0, _lib.extend2)({ path: (0, _lib.polyPathToPath)([symbol || 2, x, y, markerRadius, anchorProps.startAngle, dip]) }, cosmeticAttrs); // Draw the background of the image with the border if (hoverEffects) { // Preparing the rolloverattributes which will be set while rolling over the anchor setRolloverAttr = { path: (0, _lib.polyPathToPath)([hoverEffects.anchorSides || 2, x, y, hoverEffects.radius, hoverEffects.startAngle, hoverEffects.dip]), fill: (0, _lib.toRaphaelColor)({ color: hoverEffects.anchorColor, alpha: hoverEffects.anchorBgAlpha }), 'stroke-width': hoverEffects.anchorBorderThickness, stroke: (0, _lib.toRaphaelColor)({ color: hoverEffects.anchorBorderColor, alpha: hoverEffects.anchorBorderAlpha }) }; // Setting the image hover alpha to maximum of anchor alpha and anchor border alpha relImageHoverAlpha = mathMax(hoverEffects.anchorAlpha, hoverEffects.anchorBorderAlpha); if (hoverAlpha > relImageHoverAlpha) { hoverAlpha = relImageHoverAlpha; } } if (anchorProps.bgAlpha && anchorProps.borderAlpha) { relImageAlpha = mathMax(anchorProps.bgAlpha, anchorProps.borderAlpha); if (alpha > relImageAlpha) { alpha = relImageAlpha; } } anchorBackground = graphics.element; anchorBackground.attr(Object.assign(cosmeticAttrs, { path: setRolloutAttr.path })); anchorBackground.attr({ 'cursor': setLink ? POINTER : '' }).data('alwaysInvisible', !markerRadius).data('setRolloverProperties', hoverEffects).data('hoverEnabled', hoverEffects.enabled).data(SETROLLOVERATTR, setRolloverAttr).data(SETROLLOUTATTR, setRolloutAttr).data('anchorRadius', markerRadius).data('anchorHoverRadius', hoverEffects && hoverEffects.radius).data(EVENTARGS, eventArgs).shadow(anchorShadow, anchorShadowGroup); // create the clip path for rollout and rollover on the image imageRolloutPath = (0, _lib.polyPathToPath)([symbol || 2, x, y, rolloutClipRadius > 0 ? rolloutClipRadius : 0, anchorProps.startAngle, dip]); imageRolloverPath = (0, _lib.polyPathToPath)([symbol || 2, x, y, rolloverClipRadius > 0 ? rolloverClipRadius : 0, hoverEffects.startAngle, hoverEffects.dip]); // end of clip path calculation anchorProps.imgRefWidth = imgRef.width; anchorProps.imgRefHeight = imgRef.height; anchorProps.imgRefScale = scale; anchorProps.rolloutClipRadius = rolloutClipRadius; // Draw the image with the clip path setRolloutAttr = { x: x - imgRef.width * scale * 0.005, y: y - imgRef.height * scale * 0.005, width: imgW, height: imgH, // alpha: alpha, 'clip-path': imageRolloutPath }; setRolloverAttr = { x: x - imgRef.width * hoverScale * 0.005, y: y - imgRef.height * hoverScale * 0.005, width: hotW, height: hotH, alpha: hoverAlpha, 'clip-path': imageRolloverPath }; imageElement.attr({ x: setRolloutAttr.x, y: setRolloutAttr.y, width: setRolloutAttr.width, height: setRolloutAttr.height, 'clip-path': setRolloutAttr['clip-path'] }).data('alwaysInvisible', !scale).data('setRolloverProperties', hoverEffects).data(SETROLLOVERATTR, setRolloverAttr).data(SETROLLOUTATTR, setRolloutAttr).data('anchorRadius', scale).data('imgRef', imgRef).data('anchorHoverRadius', hoverScale); config.isAnchorsDrawn = true; markerRadius = mathMax(markerRadius, hoverEffects && hoverEffects.anchorRadius || 0, trackerRadius); } else { // for VML drawing the browser will not support clipping only draw the image setRolloutAttr = { x: x - imgRef.width * scale * 0.005, y: y - imgRef.height * scale * 0.005, width: imgW, height: imgH // alpha: alpha }; setRolloverAttr = { x: x - imgRef.width * hoverScale * 0.005, y: y - imgRef.height * hoverScale * 0.005, width: hotW, height: imgRef.height * hoverScale * 0.01, alpha: hoverAlpha }; config.isAnchorsDrawn = true; chartConf.dragTolerance = chartConf.dragTolerance < imgH ? imgH + 0.5 : chartConf.dragTolerance; imageElement.data('alwaysInvisible', !scale).data('setRolloverProperties', hoverEffects).data('hoverEnabled', hoverEffects).data(SETROLLOVERATTR, setRolloverAttr).data(SETROLLOUTATTR, setRolloutAttr).data('imgRef', imgRef).data('anchorRadius', scale).data('anchorHoverRadius', hoverScale); imageElement.attr(setRolloutAttr); setRolloutAttr.alpha = alpha; } dataObj._xPos = x; dataObj._yPos = y; dataset.parseLabelAttributes(dataObj, dataObj._index); }; (0, _dependencyManager.addDep)({ name: 'areaAnimation', type: 'animationRule', extension: _index2['default'] }); /** * Creates the Area Dataset * @class */ var AreaDataset = function (_ColumnDataset) { _inherits(AreaDataset, _ColumnDataset); /** * constructor fn */ function AreaDataset() { _classCallCheck(this, AreaDataset); var _this = _possibleConstructorReturn(this, _ColumnDataset.call(this)); var ds = _this; ds.__removeElem = function (el, type) { ds._setRemoveAnim(el, type === 'element' || type === 'image' ? 'anchor' : 'label'); }; ds.config.primitiveType = 'area'; return _this; } /** * Sets the type of the component * @return {string} type */ AreaDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ AreaDataset.prototype.getName = function getName() { return 'area'; }; /** * Sets the default value of attributes */ AreaDataset.prototype.__setDefaultConfig = function __setDefaultConfig() { _ColumnDataset.prototype.__setDefaultConfig.call(this); var config = this.config; config.valueposition = UNDEF; config.plotborderdashlen = UNDEF; config.plotborderdashgap = UNDEF; config.plotborderdashstyle = UNDEF; config.plotborderthickness = UNDEF; config.linethickness = UNDEF; config.linedashlen = UNDEF; config.linedashgap = UNDEF; config.dashed = UNDEF; config.linedashstyle = UNDEF; config.linecolor = UNDEF; config.linealpha = UNDEF; config.anchorbgcolor = UNDEF; config.anchorbordercolor = UNDEF; config.anchorradius = UNDEF; config.anchoralpha = UNDEF; config.anchorimageurl = UNDEF; config.anchorsides = UNDEF; config.anchorbgalpha = UNDEF; config.anchorborderthickness = UNDEF; config.anchorshadow = UNDEF; config.anchorstartangle = UNDEF; config.anchorimagealpha = UNDEF; config.anchorimagescale = UNDEF; config.anchorimagepadding = UNDEF; config.alpha = UNDEF; config.parentyaxis = UNDEF; }; /** * Function that return the nearest plot details * @param {number} chartX x-axis position of the mouse cordinate * @param {number} chartY y-axis position of the mouse cordinate * @return {Object} return an object with details of nearest plot and whether it is * hovered or not */ AreaDataset.prototype._getHoveredPlot = function _getHoveredPlot(chartX, chartY) { var dataset = this, xAxis = dataset.getFromEnv('xAxis'), components = dataset.components, dataStore = components.data, pointObj, xMin, xMax, len = dataStore.length, returnValue, numBinMin, numBinMax, binStrtIndex, binStopIndex, conf = dataset.config, j, step = dataset.getFromEnv('chartConfig').viewPortConfig.step || 1, maxRadius = conf && conf.radius || 0, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotsPerBin = skippingInfo.plotsPerBin; // getting new chart XY accordint to Translation of axis chartX += xAxis.getTranslation(); xMin = Math.floor(Math.max(xAxis.getValue(chartX - maxRadius), 0)); xMax = Math.ceil(Math.min(xAxis.getValue(chartX + maxRadius), len - 1)); binStopIndex = binStrtIndex + plotsPerBin - 1; if (plotsPerBin > 1) { numBinMin = mathCeil(xMin / plotsPerBin); numBinMax = mathCeil(xMax / plotsPerBin); binStrtIndex = (numBinMin - 1) * plotsPerBin + 1; binStopIndex = numBinMax * plotsPerBin; xMin = binStrtIndex; xMax = binStopIndex; } for (j = xMax; j >= xMin; j--) { if ((pointObj = dataStore[j]) && !(j % step)) { returnValue = dataset.isWithinShape(pointObj, j, chartX, chartY); if (returnValue) { break; } } } return returnValue; }; /** * Determines the clip path needs to be applied on basis of argument type * @param {string} type type of clip applied * @return {Array} ClipPath array for clipping */ AreaDataset.prototype.getClip = function getClip(type) { var dataset = this, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), yAxisLimits = yAxis.getLimit(), xAxisLimits = xAxis.getLimit(), xMinPixel = xAxis.getPixel(xAxisLimits.min), yMinPixel = yAxis.getPixel(yAxisLimits.min), yMaxPixel = yAxis.getPixel(yAxisLimits.max), width = Math.abs(xAxis.getPixel(xAxisLimits.max) - xMinPixel), height = yMinPixel - yMaxPixel, resArr = []; resArr.push(xMinPixel); resArr.push(height < 0 ? yMinPixel : yMaxPixel); if (type === 'init') { resArr.push(0); } else if (type === 'canvas') { resArr.push(width); } resArr.push(Math.abs(height)); return resArr; }; AreaDataset.prototype.isWithinShape = function isWithinShape(pointObj, pX, x, y, setVal) { var anchorProps, config, radius, borderThickness, dataset, viewPortConfig, components, dataStore, dragTolerance, xPos, yPos, dx, dy, diff, hoverEffects, xShift; if (!pointObj || !(setVal = pointObj.config.setValue) && setVal !== 0) { return; } anchorProps = pointObj.config.anchorProps; config = pointObj.config; borderThickness = anchorProps && anchorProps.borderThickness; dataset = this; viewPortConfig = dataset.getFromEnv('chart').config.viewPortConfig; components = dataset.components; dataStore = components.data; dragTolerance = (0, _lib.pluckNumber)(config.dragTolerance, 0); xShift = viewPortConfig ? viewPortConfig.x * viewPortConfig.scaleX : 0; xPos = pointObj._xPos - xShift; yPos = pointObj._yPos; if (yPos !== null) { hoverEffects = pointObj.config.hoverEffects; radius = Math.max(anchorProps && anchorProps.radius, hoverEffects && hoverEffects.anchorRadius || 0, HTP) + borderThickness / 2; if (!radius) { radius = 3; } dx = x - xPos; dy = y - yPos; diff = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); if (diff <= radius || diff <= dragTolerance) { return { pointIndex: pX, hovered: true, pointObj: dataStore[pX] }; } else { return false; } } }; /** * Determines the opacity of shadow * @return {Object} Opacity value of shadow */ AreaDataset.prototype._parseShadowOptions = function _parseShadowOptions() { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, chartAttr = chart.getFromEnv('dataSource').chart, colorM = dataSet.getFromEnv('color-manager'), defaultShadow = (0, _lib.pluckNumber)(chart.defaultPlotShadow, colorM.getColor(SHOWSHADOW)); return { opacity: (0, _lib.pluckNumber)(chartAttr.showshadow, defaultShadow) ? conf.alpha / 100 : 0 }; }; /** * This method handles all mouse events of an dataset. * @param {string} eventType name of the event * @param {number} plotIndex index of the plot where this event has been occured * @param {Event} e reference of the original mouse event * @param {number} datasetIndex index of the dataSet on which the mouse is hovered */ AreaDataset.prototype._firePlotEvent = function _firePlotEvent(eventType, plotIndex, e) { var dataset = this, chart = dataset.getFromEnv('chart'), components = dataset.components, toolTipController = dataset.getFromEnv('toolTipController'), dataStore = components.data, data = dataStore[plotIndex] || {}, sharedAnchor = dataset.getGraphicalElement('sharedAnchor'), setElement = data.graphics && data.graphics.element || (data.config && data.config.setValue) !== UNDEF && sharedAnchor, toolTip = this.config.currentToolTip, // originalEvent = e.originalEvent, style = chart.getFromEnv('paper').canvas.style, config, eventArgs, setLink; if (setElement) { config = data.config; setLink = config.setLink; eventArgs = config.eventArgs; switch (eventType) { case 'fc-mouseover': dataset._decideTooltipType(plotIndex, e); dataset._rolloverResponseSetter(chart, data, e); setLink && (style.cursor = POINTER); break; case 'fc-mouseout': toolTipController.hide(toolTip); dataset._rolloutResponseSetter(chart, data, e); style.cursor = DEFAULT_CURSOR; break; case 'fc-click': chart.plotEventHandler(setElement, e, DATAPLOTCLICK, eventArgs); break; case 'fc-mousemove': dataset._decideTooltipType(plotIndex, e); } } }; AreaDataset.prototype._rolloverResponseSetter = function _rolloverResponseSetter(chart, data, event, onlyHoverEffect) { var dataset = this, dataGraphics = data.graphics, elem = dataGraphics && (dataGraphics.element || dataset.getAnchor(data)), draged = elem && elem.data('draged'), hoverEnabled = elem && elem.data('hoverEnabled'); if (draged !== true) { dataset._hoverFunc(data, ROLLOVER, hoverEnabled, chart.getFromEnv('dataSource').chart); !onlyHoverEffect && elem && chart.plotEventHandler(elem, event, ROLLOVER); } }; AreaDataset.prototype._rolloutResponseSetter = function _rolloutResponseSetter(chart, data, event, onlyHoverEffect) { var dataset = this, dataGraphics = data.graphics, elem = dataGraphics && (dataGraphics.element || dataset.getAnchor(data)), draged = elem && elem.data('draged'), hoverEnabled = elem && elem.data('hoverEnabled'), plotType = dataset.type, dataConf = data.config, anchorProps = dataConf.anchorProps, isVisibleAnchor = anchorProps.radius && anchorProps.anchorAlpha; if (draged !== true) { dataset._hoverFunc(data, ROLLOUT, hoverEnabled, chart.getFromEnv('dataSource').chart); !onlyHoverEffect && elem && chart.plotEventHandler(elem, event, ROLLOUT); } // for area hide anchors if anchors radius and alpha disabled dataConf.isAnchorsDrawn && !isVisibleAnchor && plotType === 'area' && elem && elem.hide(); }; // create a shared anchor or use existing one AreaDataset.prototype.getAnchor = function getAnchor() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dataset = this, animationManager = dataset.getFromEnv('animationManager'), sharedAnchor = dataset.getGraphicalElement('sharedAnchor'), config = data.config, anchorProps, eventArgs, setRolloutAttr, setRolloverAttr, hoverEffects, hoverEnabled, radius, anchorShadow, prevAnchorHovered; // if shared anchor is not created create one if (!sharedAnchor) { sharedAnchor = animationManager.setAnimation({ el: 'path', container: dataset.getContainer('plotGroup'), label: 'anchor', doNotRemove: true, component: dataset }); dataset.addGraphicalElement('sharedAnchor', sharedAnchor); return sharedAnchor; } anchorProps = config.anchorProps; eventArgs = config.eventArgs; hoverEffects = config.hoverEffects; hoverEnabled = hoverEffects.enabled; if (hoverEnabled) { setRolloutAttr = hoverEffects.attrs && hoverEffects.attrs.setRolloutAttr; setRolloverAttr = hoverEffects.attrs && hoverEffects.attrs.setRolloverAttr; } radius = anchorProps.radius; anchorShadow = anchorProps.shadow; prevAnchorHovered = dataset.getFromEnv('chartConfig').prevAnchorHovered; // PREVENT default animation for shared anchors hoverEffects.anchorAnimation = 0; // add properties to the shared anchor if (data._index !== prevAnchorHovered) { sharedAnchor.shadow(anchorShadow, dataset.getContainer('shadowGroup')).data('anchorRadius', radius).data('anchorHoverRadius', hoverEffects.anchorRadius).data('hoverEnabled', hoverEnabled).data(EVENTARGS, eventArgs); // Storing necessary attributes in the element for future reference if (hoverEnabled) { sharedAnchor.data(SETROLLOVERATTR, setRolloverAttr).data(SETROLLOUTATTR, setRolloutAttr); } } // save last hovered index dataset.getFromEnv('chartConfig').prevAnchorHovered = data._index; return sharedAnchor; }; /** * Parses all the attributes for dataset level and set level * Called from init function of area class and line class * Both line and area attributes configuration is done here * @param {Object} datasetJSON the data provided by user * @return {boolean} false if datasetJSON is undefined */ AreaDataset.prototype.configureAttributes = function configureAttributes(datasetJSON) { if (!datasetJSON) { return false; } this.trimData(datasetJSON); var dataSet = this, chart = dataSet.getFromEnv('chart'); dataSet.config.JSONData = datasetJSON; dataSet.parseAttributes(); dataSet._setConfigure(); dataSet._realTimeConfigure && dataSet._realTimeConfigure(); chart.config.hasLegend !== false && chart.config.showLegend && dataSet._addLegend(); dataSet.setState('dirty', true); }; AreaDataset.prototype.parseAttributes = function parseAttributes() { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, conf = dataSet.config, plotType = dataSet.getName(), JSONData = dataSet.config.JSONData, chartAttr = chart.getFromEnv('dataSource').chart, singleSeries = chart.config.singleseries, colorM = dataSet.getFromEnv('color-manager'), // for multiaxisline dataset index are stored as floating point numbers index = Math.floor(dataSet.getJSONIndex()), showplotborder = (0, _lib.pluckNumber)(JSONData.showplotborder, chartAttr.showplotborder || 1), plotFillColor = (0, _lib.getFirstColor)(!singleSeries || (0, _lib.getValidValue)(chartAttr.palettecolors) ? colorM.getPlotColor(index) : colorM.getColor('plotFillColor').split(/\s*\,\s*/)[0]), usePlotGradientColor = void 0, COMMASTRING = ',', BLANKSTRING = '', lineDashStyle = void 0, isDual = chartConfig.isdual, hasLineSet = chartConfig.haslineset, paddingValue = 0; conf.maxValue = -Infinity; conf.minValue = Infinity; (0, _lib.parseConfiguration)(JSONData, conf, chart.config, { data: true }); // @todo. Once chart's default configuration parsing is done, the next two lines will be removed conf.showValues = (0, _lib.pluckNumber)(JSONData.showvalues, chartAttr.showvalues, plotType === 'radar' ? 0 : 1); conf.anchorimageurl = (0, _lib.pluck)(JSONData.anchorimageurl, chartAttr.anchorimageurl, UNDEF); conf.plotColor = plotFillColor; // Functional attributes configuration if (isDual) { // ParentYAxis is always 1 for lineset if (hasLineSet) { conf.parentYAxis = 1; } else { conf.parentYAxis = (0, _lib.pluck)(JSONData.parentyaxis && JSONData.parentyaxis.toLowerCase(), 'p') === 's' ? 1 : 0; } } else { conf.parentYAxis = 0; } // dataSet.yAxis = chartComponents.yAxis[parentYAxis]; conf.valueposition = conf.valueposition.toLowerCase(); // Data Plot cosmetics attributes configuration parsing conf.plotfillcolor = (0, _lib.pluck)(JSONData.color, chartAttr.plotfillcolor, plotFillColor); conf.seriesname = (0, _lib.parseUnsafeString)(JSONData.seriesname); usePlotGradientColor = chartConfig.useplotgradientcolor; conf.plotgradientcolor = usePlotGradientColor !== 0 ? (0, _lib.getDefinedColor)(chartAttr.plotgradientcolor, colorM.getColor(PLOTGRADIENTCOLOR)) : ''; conf.plotfillalpha = (0, _lib.pluck)(JSONData.alpha, chartConfig.plotfillalpha); conf.fillColor = { color: conf.plotfillcolor + (conf.plotgradientcolor ? COMMASTRING + conf.plotgradientcolor : BLANKSTRING), alpha: conf.plotfillalpha, angle: conf.plotfillangle }; conf.plotborderalpha = showplotborder ? (0, _lib.pluck)(JSONData.plotborderalpha, chartAttr.plotborderalpha, JSONData.alpha, chartAttr.plotfillalpha, '95') : 0; conf.plotbordercolor = (0, _lib.pluck)(JSONData.plotbordercolor, chartAttr.plotbordercolor, chartAttr.areabordercolor, singleSeries ? (0, _lib.getValidValue)(chartAttr.palettecolors) ? colorM.getPlotColor(0) : colorM.getColor(PLOTBORDERCOLOR).split(/\s*\,\s*/)[0] : '666666'); // Line configuration attributes parsing conf.drawLine = (0, _lib.pluckNumber)(JSONData.drawline, chartAttr.drawlines, 1); conf.plotborderdashstyle = conf.dashed ? (0, _lib.getDashStyle)(conf.plotborderdashlen, conf.plotborderdashgap) : NONE; conf.linecolor = (0, _lib.pluck)(JSONData.color, chartAttr.linecolor, conf.plotColor); conf.legendSymbolColor = dataSet.type === 'line' ? conf.linecolor : conf.plotfillcolor; conf.includeinlegend = (0, _lib.pluckNumber)(JSONData.includeinlegend, conf.seriesname ? 1 : 0); lineDashStyle = (0, _lib.getDashStyle)(conf.linedashlen, conf.linedashgap); conf.lineDashStyle = conf.dashed ? lineDashStyle : NONE; conf.defaultPadding = { left: paddingValue, right: paddingValue }; // conf.showShadow = pluckNumber(chartAttr.showshadow, 1); conf.shadow = dataSet._parseShadowOptions(); // // Anchor cosmetics attributes in dataset level conf.drawanchors = (0, _lib.pluckNumber)(JSONData.drawanchors, JSONData.showanchors, chartAttr.showanchors, chartAttr.drawanchors); conf.anchorbgcolor = (0, _lib.getFirstColor)((0, _lib.pluck)(JSONData.anchorbgcolor, chartConfig.anchorbgcolor, colorM.getColor('anchorBgColor'))); conf.anchorbordercolor = (0, _lib.getFirstColor)((0, _lib.pluck)(JSONData.anchorbordercolor, chartConfig.anchorbordercolor, conf.linecolor, conf.plotColor)); // dataStore = dataSet.components.data = dataSet.components.data || (dataSet.components.data = []); dataSet.setState('visible', (0, _lib.pluckNumber)(JSONData.visible, !Number(JSONData.initiallyhidden), 1) === 1 && conf.drawLine); }; /** * Configure data level * @param {Object} newDataset new dataset added * @param {Object} newIndex new added dataset index */ AreaDataset.prototype._setConfigure = function _setConfigure(newDataset, newIndex) { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, chartConfig = chart.config, JSONData = dataSet.config.JSONData || [], setData, dataObj, xAxis = dataSet.getFromEnv('xAxis'), isRealTime = chart.isRealTime, numDisplaySets = chartConfig.realTimeConfig && chartConfig.realTimeConfig.numDisplaySets, categories = dataSet.getFromEnv('dataSource').categories && dataSet.getFromEnv('dataSource').categories[0] && dataSet.getFromEnv('dataSource').categories[0].category, catLen = conf.initCatLen = isRealTime ? categories && Array.isArray(categories) && categories.filter(function (data) { return !data.vline; }).length || 0 : xAxis.getTicksLen(), setDataArr = newDataset || JSONData.data, newDataSetLen = newDataset && newDataset.data.length, len, dataStore, isDrag = chartConfig.isDrag, i, j, plotIndex, // @todo please check this change done for multiaxisline also it may cause some problem there tempIndex, shiftIndex, skippingInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), plotDrawArray = skippingInfo && skippingInfo.draw || [], plotDrawArrayLength = plotDrawArray.length, skippingApplied = skippingInfo && skippingInfo.skippingApplied; // shiftIndex: how much index shift is needed in realtime column charts when numDisplaySets is lesser // than catLen. While on other cases shiftIndex should be 0. So, It will work as it is. shiftIndex = newDataSetLen === UNDEF && catLen > numDisplaySets ? catLen - numDisplaySets : 0; len = isRealTime ? (0, _lib.pluckNumber)(newDataSetLen, catLen) : Math.min(catLen, setDataArr && setDataArr.length); conf.imageCount = 0; dataStore = dataSet.components.data; if (!dataStore) { dataStore = dataSet.components.data = []; } conf.maxRadius = -Infinity; chartConfig.dragTolerance = chartConfig.dragTolerance || -Infinity; if (skippingApplied) { len = plotDrawArrayLength; } for (j = shiftIndex; j < len; j++) { i = plotDrawArray[j] || j; if (newDataset) { setData = newDataset && newDataset.data[i] || {}; if (newIndex !== UNDEF) { tempIndex = newIndex + i; dataObj = dataStore[tempIndex]; } else { tempIndex = dataStore.length - len + i; dataObj = dataStore[tempIndex]; } plotIndex = tempIndex; } else { setData = setDataArr && setDataArr[i] || {}; i = i - shiftIndex; dataObj = dataStore[i]; plotIndex = i; } if (!dataObj) { dataObj = dataStore[plotIndex] = {}; } if (!dataObj.config) { dataObj.config = {}; } if (!dataObj.graphics) { dataObj.graphics = {}; } dataSet._plotConfigure(plotIndex, setData, newDataSetLen); tempIndex && tempIndex++; } if (skippingApplied) { dataSet.addJob('configureRestID', dataSet._configureRestData.bind(dataSet), _schedular.priorityList.postRender); } chartConfig.dragTolerance = isDrag ? (chartConfig.dragTolerance > 5 ? chartConfig.dragTolerance : 5.5) + HTP : 0; dataSet.ErrorValueConfigure && dataSet.ErrorValueConfigure(); }; /** * method to configure the rest of data that have not been drawn during use of data skipping */ AreaDataset.prototype._configureRestData = function _configureRestData() { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, chartConfig = chart.config, JSONData = dataSet.config.JSONData, setDataArr = JSONData.data || [], setData, dataObj, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), drawOnlyMap = skipInfo.drawOnlyMap, xAxis = dataSet.getFromEnv('xAxis'), catLen = xAxis.getTicksLen(), len = catLen, dataStore, i, plotIndex, // @todo please check this change done for multiaxisline also it may cause some problem there tempIndex; conf.imageCount = 0; dataStore = dataSet.components.data; if (!dataStore) { dataStore = dataSet.components.data = []; } conf.maxRadius = -Infinity; chartConfig.dragTolerance = chartConfig.dragTolerance || -Infinity; conf.maxValue = -Infinity; conf.minValue = Infinity; for (i = 0; i < len; i++) { if (drawOnlyMap[i]) { continue; } dataObj = dataStore[i]; setData = setDataArr && setDataArr[i] || {}; plotIndex = i; if (!dataObj) { dataObj = dataStore[i] = {}; } if (!dataObj.config) { dataStore[i].config = {}; } if (!dataObj.graphics) { dataObj.graphics = {}; } dataSet._plotConfigure(plotIndex, setData); tempIndex && tempIndex++; } }; /** * method to configure a particular data plot object * @param {number} setIndex index of the data object to be configured * @param {Object} setData particular plot information in of i'th index in input json * @param {number} newDataSetLen new data set length for RT charts */ AreaDataset.prototype._plotConfigure = function _plotConfigure(setIndex, setData, newDataSetLen) { var dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, chartConfig = chart.config, JSONData = dataSet.config.JSONData, chartAttr = chart.getFromEnv('dataSource').chart, dataStore = dataSet.components.data, dataObj = dataStore[setIndex], xAxis = dataSet.getFromEnv('xAxis'), yAxis = dataSet.getFromEnv('yAxis'), isDrag = chartConfig.isDrag, config = dataObj && dataObj.config, toolText, toolTipValue, setValue, setDisplayValue, macroIndices, parserConfig, formatedVal, seriesname, catObj, yAxisName = (0, _lib.parseUnsafeString)(chartConfig.yaxisname), xAxisName = (0, _lib.parseUnsafeString)(chartConfig.xaxisname), tooltipSepChar = chartConfig.tooltipsepchar, // @todo please check this change done for multiaxisline also it may cause some problem there lineDashed = conf.dashed, // pluckNumber(JSONData.dashed, chartAttr.linedashed), numDisplaySets = chartConfig.realTimeConfig && chartConfig.realTimeConfig.numDisplaySets, diffLen = numDisplaySets - conf.initCatLen, additive = numDisplaySets && diffLen >= 0 ? diffLen : 0, radius; catObj = xAxis.getLabel(newDataSetLen ? setIndex - newDataSetLen : additive + setIndex); config.label = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(catObj.tooltext || catObj.label)); if (setData.tooltext !== UNDEF) { setData.tooltext = (0, _lib.parseTooltext)(setData.tooltext, [3], { label: catObj.label }, setData, chartAttr, JSONData); } config.setValue = setValue = yAxis.getCleanValue(setData.value, conf.stack100percent); config.setLink = (0, _lib.pluck)(setData.link); // Parsing the anchor properties for set level config.anchorProps = this._parseAnchorProperties(setIndex); conf.maxRadius = mathMax(config.anchorProps.radius + config.anchorProps.borderThickness / 2, conf.maxRadius); radius = config.anchorProps.radius + config.anchorProps.borderThickness / 2; config.dragTolerance = isDrag ? (radius < 6 ? 5.5 : radius + 0.5) + HTP : 0; config.label = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(catObj.tooltext || catObj.label)); config.showValue = (0, _lib.pluckNumber)(setData.showvalue, conf.showValues); // Dashed, color and alpha configuration in set level is only for line chart config.dashed = (0, _lib.pluckNumber)(setData.dashed, lineDashed); config.dashStyle = config.dashed ? (0, _lib.getDashStyle)(conf.linedashlen, conf.linedashgap) : 'none'; config.color = (0, _lib.pluck)(setData.color, conf.linecolor); config.setColor = setData.color; config.setAlpha = setData.alpha; config.setDashed = setData.dashed; config.alpha = (0, _lib.pluck)(setData.alpha, setData.linealpha, conf.linealpha); config.origLabel = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(catObj.label)); if (setValue !== null) { conf.maxValue = mathMax(conf.maxValue, setValue); conf.minValue = mathMin(conf.minValue, setValue); } config.setTooltext = (0, _lib.parseUnsafeString)(setData.toolText); config.toolTipValue = toolTipValue = yAxis.dataLabels(setValue); config.setDisplayValue = setDisplayValue = (0, _lib.parseUnsafeString)(setData.displayvalue); config.displayValue = (0, _lib.pluck)(setDisplayValue, toolTipValue); config.formatedVal = formatedVal = config.toolTipValue; config.setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(setData.tooltext, JSONData.plottooltext, chartAttr.plottooltext))); config.valuePosition = (0, _lib.pluck)(setData.valueposition, conf.valueposition); if (config.valuePosition) { config.valuePosition = config.valuePosition.toLowerCase(); } // Initial tooltext parsing if (!chartConfig.showtooltip) { toolText = false; } else { if (formatedVal === null) { toolText = false; } else if (config.setTooltext !== UNDEF) { macroIndices = [1, 2, 3, 4, 5, 6, 7]; parserConfig = { yaxisName: yAxisName, xaxisName: xAxisName, formattedValue: formatedVal, label: config.label }; toolText = (0, _lib.parseTooltext)(config.setTooltext, macroIndices, parserConfig, setData, chartAttr, JSONData); } else { if (chartConfig.seriesnameintooltip) { seriesname = (0, _lib.getFirstValue)(JSONData && JSONData.seriesname); } // Configure the tooltext using the tooltipvalue and label toolText = seriesname ? seriesname + tooltipSepChar : ''; toolText += config.label ? config.label + tooltipSepChar : ''; toolText += config.setTooltext ? '' : config.toolTipValue; } } config.toolText = toolText; config.setLevelTooltext = config.setTooltext; // Storing x and y values for pixel calculations config._x = setData.index === UNDEF ? setIndex : setData.index; config._y = setValue; // Storing the initial parsed tooltext which will be later used in stack100percent calculations // on legend click // finalToolText is being created in configure level so it will be set here config.finalTooltext = config.setTooltext = toolText; config.hoverEffects = this._parseHoverEffectOptions(dataObj, setData); config.anchorProps.isAnchorHoverRadius = config.hoverEffects.anchorRadius; chartConfig.dragTolerance = mathMax(chartConfig.dragTolerance, conf.maxRadius, config.hoverEffects.anchorRadius); }; /** * Function to draw line * @param {Object} anim The animation object which will be passed to animation manager. All * animation configuration should be pushed into this. * Line chart has a setLevel attribute 'color', thus line segments can have different colors, * but a line path can support only one color, so we are making multiple paths depending on the * color applied. lineOb is object having all line elements and key is the color and stroke combined, * thus all line segment having same color is grouped under one key. elements having different * line color is animated by fading in and out, on main color's line element transition is applied. */ AreaDataset.prototype.drawCommonElements = function drawCommonElements() { var dataset = this, dataStore = dataset.components.data, chart = dataset.getFromEnv('chart'), dsConfig = dataset.config, chartConfig = chart.config, // containers = dataset.getContainer('plotGroup'), lineElement, lineElementPrev, finalPath, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), scrollMinVal = dsConfig.scrollMinVal, scrollMaxVal = dsConfig.scrollMaxVal, // Cosmetics isOnlyLineBorder = !chartConfig.drawfullareaborder, plotBorderColor = dsConfig.plotbordercolor, plotBorderAlpha = dsConfig.plotborderalpha, plotBorderDashStyle = dsConfig.plotborderdashstyle, plotBorderThickness = dsConfig.plotborderthickness, colorArr = dsConfig.fillColor, animationManager = dataset.getFromEnv('animationManager'), // firstDraw = !dsConfig.drawn, lineProps, connector, lim = { x: xAxis.getLimit(), y: yAxis.getLimit() }, // legendInteractivity = dsConfig.legendInteractivity, tempStore = [], i, j, shadow = dsConfig.shadow, shadowContainer = dataset.getContainer('shadowGroup'), positionObj, scrolling = xAxis.getState('scrolling'), // firstRealTimeUpdate = chart.state === 'realTimeUpdate' && !dataset.realTimeUpdated, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotDrawArray = skippingInfo && skippingInfo.draw || [], plotDrawArrayLength = plotDrawArray.length, skippingApplied = skippingInfo && skippingInfo.skippingApplied; // Setting min and max pixels lim.x.minPixel = xAxis.getPixel(lim.x.min); lim.x.maxPixel = xAxis.getPixel(lim.x.max); lim.y.minPixel = yAxis.getPixel(lim.y.min); lim.y.maxPixel = yAxis.getPixel(lim.y.max); lim.y.base = yAxis.getPixel(0); lim.x.base = xAxis.getPixel(0); if (skippingApplied) { scrollMinVal = 0; scrollMaxVal = plotDrawArrayLength; } // Setting a tempdata store to save for next for (j = scrollMinVal; j < scrollMaxVal; j++) { i = plotDrawArray[j] || j; if (!dataStore[i] || !dataStore[i].config) { continue; } tempStore[i] = { config: { _Px: dataStore[i].config._Px, _Pbx: dataStore[i].config._Pbx, _Py: dataStore[i].config._Py, _Pby: dataStore[i].config._Pby, setValue: dataStore[i].config.setValue } }; } positionObj = { begin: scrollMinVal, end: scrollMaxVal }; // Getting final path for area // If dataset is not visible area will morph to base finalPath = this.getLinePath(dataStore, scrolling ? positionObj : null, !dataset.getState('visible') && 'base'); // Getting line properties lineProps = { path: finalPath.getPathArr(), stroke: (0, _lib.toRaphaelColor)({ color: plotBorderColor, alpha: plotBorderAlpha }), // Stroke width 0 when showing only upper line border 'stroke-width': isOnlyLineBorder ? 0 : plotBorderThickness, 'stroke-linecap': 'round', fill: (0, _lib.toRaphaelColor)(colorArr), 'stroke-linejoin': plotBorderThickness > MAX_MITER_LINEJOIN ? 'round' : 'miter', 'stroke-dasharray': plotBorderDashStyle }; // Creating Line Element lineElementPrev = dataset.getGraphicalElement('lineElement'); lineElement = animationManager.setAnimation({ el: lineElementPrev || 'path', container: dataset.getContainer('commonElemsGroup'), attr: dataset.getState('visible') && lineProps, component: dataset, doNotRemove: true, label: 'line', callback: function callback() { !dataset.getState('visible') && this.hide(); } }); if (!lineElementPrev && lineElement) { dataset.addGraphicalElement('lineElement', lineElement); } dataset.getState('visible') && lineElement && lineElement.show(); if (dataset.getState('visible')) { // Applying shadow !scrolling && lineElement.shadow(shadow, shadowContainer); } if (!scrolling) { // If drawfullareaborder is 0 only top border area is drawn connector = dataset.getGraphicalElement('connector'); // @todo have to find out when this block is needed(lack of information) if (isOnlyLineBorder) { connector = dataset.addGraphicalElement('connector', animationManager.setAnimation({ attr: { path: finalPath.getPathArr(), stroke: (0, _lib.toRaphaelColor)({ color: plotBorderColor, alpha: plotBorderAlpha }), 'stroke-width': plotBorderThickness, 'stroke-linecap': 'round', 'stroke-linejoin': plotBorderThickness > MAX_MITER_LINEJOIN ? 'round' : 'miter', 'stroke-dasharray': plotBorderDashStyle }, el: connector || 'path', container: dataset.getContainer('commonElemsGroup'), component: dataset, label: 'line', callback: !dataset.getState('visible') && function () { this.hide(); } })); } else { connector && animationManager.setAnimation({ attr: {}, el: connector, container: dataset.getContainer('commonElemsGroup'), component: dataset, label: 'line', callback: function callback() { this.hide(); } }); } } // Saving limits dsConfig.prevLim = lim; // Saving data store dsConfig.prevDataStore = tempStore; if (chart.state === 'realTimeUpdate') { dataset.realTimeUpdated = true; } // Saving connectnulldata attribute chartConfig.connectnulldataOld = chartConfig.connectnulldata; }; /** * Parses the plot attributes of anchors * * @memberof AreaDataset */ AreaDataset.prototype.parsePlotAttributes = function parsePlotAttributes(dataObj, index) { var dataset = this, datasetIndex = dataset.getJSONIndex(), visible = dataset.getState('visible'), dsConfig = dataset.config, JSONData = dataset.config.JSONData, i = index, anchorProps = {}, setRolloutAttr = {}, setRolloverAttr = {}, xVal, yVal, setValue, setLink, symbol, toolText, // anchorRadius, hoverEffects, xPos, yPos, displayValue, plotConfig; plotConfig = dataObj.config; // xPos and yPos are the pixel conversions of the values provided. xPos = plotConfig._Px; yPos = plotConfig._Py; xVal = plotConfig._x; yVal = plotConfig._y; setLink = plotConfig.setLink; setValue = plotConfig.setValue; // showValue = plotConfig.showValue; anchorProps = plotConfig.anchorProps; displayValue = plotConfig.displayValue; // trackerConfig = plotConfig.trackerConfig = {}; // Cache the hoverEffect configurations. hoverEffects = plotConfig.hoverEffects; // Get the tool text associated with the data plot toolText = plotConfig.finalTooltext = plotConfig.toolText; // Storing the event arguments plotConfig.eventArgs = { index: i, link: setLink, value: setValue, displayValue: displayValue, categoryLabel: plotConfig.origLabel, toolText: toolText, id: dsConfig.userID, datasetIndex: datasetIndex || 0, datasetName: JSONData.seriesname, visible: visible }; symbol = anchorProps.symbol; /** * Storing the x position and y position in dataObject for future reference * For example - when drawing labels we need this xPos and yPos */ dataObj._xPos = xPos; dataObj._yPos = yPos; dataObj._xVal = xVal; dataObj._yVal = yVal; dataObj._index = i; if (yVal !== null && xVal !== null) { plotConfig.eventArgs.x = xVal; plotConfig.eventArgs.y = yVal; if (hoverEffects.enabled) { // Set the rollOver and rollOut attributes configurations only if hoverEffects are enabled. setRolloverAttr = { path: (0, _lib.polyPathToPath)([hoverEffects.anchorSides || 2, xPos, yPos, hoverEffects.anchorRadius, hoverEffects.startAngle, hoverEffects.dip]), fill: (0, _lib.toRaphaelColor)({ color: hoverEffects.anchorColor, alpha: hoverEffects.anchorBgAlpha }), stroke: (0, _lib.toRaphaelColor)({ color: hoverEffects.anchorBorderColor, alpha: hoverEffects.anchorBorderAlpha }), 'stroke-width': hoverEffects.anchorBorderThickness }; setRolloutAttr = { // XXX: Is this validated yet??! // TODO: in the new architechture, instead of symbol it was anchorsides. Please validate. path: (0, _lib.polyPathToPath)([symbol[1] || 2, xPos, yPos, anchorProps.radius, anchorProps.startAngle, plotConfig.dip || 0]), fill: (0, _lib.toRaphaelColor)({ color: anchorProps.bgColor, alpha: anchorProps.bgAlpha }), stroke: (0, _lib.toRaphaelColor)({ color: anchorProps.borderColor, alpha: anchorProps.borderAlpha }), 'stroke-width': anchorProps.borderThickness }; hoverEffects.attrs = { 'hoverEnabled': hoverEffects.enabled, 'anchorRadius': anchorProps.radius, 'anchorHoverRadius': hoverEffects.anchorRadius }; hoverEffects.attrs[SETROLLOVERATTR] = setRolloverAttr; hoverEffects.attrs[SETROLLOUTATTR] = setRolloutAttr; anchorProps.isAnchorHoverRadius = hoverEffects.attrs.anchorRadius; } if (anchorProps.imageUrl) { // If imageurl is present, i.e. the data plot is an image plotConfig.anchorImageLoaded = false; } /** * The Raphael Element referring to the current data plot. * @type {Element} */ plotConfig.props = { element: { attr: { path: (0, _lib.polyPathToPath)([symbol[1] || 2, xPos, yPos, anchorProps.radius, anchorProps.startAngle, plotConfig.dip || 0]), fill: (0, _lib.toRaphaelColor)({ color: anchorProps.bgColor, alpha: anchorProps.bgAlpha }), stroke: (0, _lib.toRaphaelColor)({ color: anchorProps.borderColor, alpha: anchorProps.borderAlpha }), 'stroke-width': anchorProps.borderThickness } } }; } else { if (setValue) { setValue.isNull = true; } } }; /** * Parses label attributes * * @param {any} dataObj * @param {any} index * @memberof AreaDataset */ AreaDataset.prototype.parseLabelAttributes = function parseLabelAttributes(dataObj, index) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, SmartLabel = dataSet.getFromEnv('smartLabel'), style = chart.config.dataLabelStyle, dataStore = dataSet.components.data, stack100Percent = chartConfig.stack100percent, displayValue = '', rotateValues = chartConfig.rotatevalues ? 270 : 0, canvasTop = chartConfig.canvasTop, canvasHeight = chartConfig.canvasHeight, isStacked = chart.config.isstacked, GUTTER_4 = 4, GUTTER_2 = 2, valuePadding, bBoxObj, // graphic, textHeight, origTextHeight, textY, textX, yAdjust, anchorProps, valuePosition, placeValuesInside, topSpace, bottomSpace, config, xPos, yPos, prevConfig, prevValue, value, showValue, anchorRadius, i = index, setValue, attr; config = dataObj && dataObj.config; setValue = config && config.setValue; if (dataObj === UNDEF || setValue === UNDEF || setValue === null || config.labelSkip === true) { config && delete config.labelSkip; return; } anchorProps = config.anchorProps; // graphic = dataObj.graphics; yPos = dataObj._yPos || dataObj.config._Py; xPos = dataObj._xPos || dataObj.config._Px; // anchorRadius = graphic.element ? (graphic.image && // graphic.element.attr('height') * 0.5) || anchorProps.radius - 3 : 0; anchorRadius = anchorProps.markerRadius || anchorProps.radius - 3; valuePadding = chartConfig.valuepadding + GUTTER_2 + anchorRadius; valuePosition = config.valuePosition; // Deciding the value position switch (valuePosition) { case 'above': placeValuesInside = 0; break; case 'below': placeValuesInside = 1; break; // Calculating the value position default: prevConfig = dataStore[i - 1] && dataStore[i - 1].config || {}; // nextConfig = (dataStore[i + 1] && dataStore[i + 1].config) || {}; if (isStacked && stack100Percent) { prevValue = prevConfig.value; // nextValue = nextConfig.value; value = config.value; } else { prevValue = prevConfig.setValue; // nextValue = nextConfig.setValue; value = config.setValue; } // For first data the value is placed always above // For other data checking if placeValuesInside = !i ? 0 : prevValue > value ? 1 : 0; } displayValue = config.displayValue; showValue = config.showValue; // labelElement = graphic.label; // Drawing label only if displayvalue is defined and not blank and setValue is not null if (defined(displayValue) && displayValue !== '' && value !== null && showValue) { attr = { text: displayValue, fill: style.color, 'text-bound': [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash] }; bBoxObj = SmartLabel.getOriSize(displayValue); config._state = config._state || {}; if (rotateValues) { // If rotated values we use the width of // the text as height // If label is already rotated then we take the width as labelWidth config._state.labelWidth = bBoxObj.height; config._state.labelHeight = bBoxObj.width; config._rotated = true; } else { // If label is already rotated then we take the height as labelWidth config._state.labelWidth = bBoxObj.width; config._state.labelHeight = bBoxObj.height; config._rotated = false; } // Calculating the total text height textHeight = origTextHeight = config._state.labelHeight; textHeight += valuePadding; yAdjust = origTextHeight * 0.5 + valuePadding; topSpace = yPos - canvasTop; bottomSpace = canvasTop + canvasHeight - yPos; textY = yPos; textX = xPos; textHeight = textHeight + GUTTER_4; // Calculating the y position of text when drawing it below anchors if (placeValuesInside) { // If space is available below anchor if (bottomSpace > textHeight) { textY += yAdjust; config._valueBelowPoint = 1; } else if (topSpace > textHeight) { // If space available above anchor textY -= yAdjust; config._valueBelowPoint = 0; } } else { // Calculating the y position of text when drawing it above anchors // if space available for text above anchors if (topSpace > textHeight) { textY -= yAdjust; config._valueBelowPoint = 0; } else if (bottomSpace > textHeight) { // if space available below anchors textY += yAdjust; config._valueBelowPoint = 1; } } attr.x = textX; attr.y = textY; } config.props = config.props || {}; config.props.label = { attr: attr }; }; /** * Parse plot and label attributes during post space management * * @memberof AreaDataset */ AreaDataset.prototype.allocatePosition = function allocatePosition() { var dataset = this, dsConfig = dataset.config, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, showpercentvalues = chartConfig.showpercentvalues, showPercentInToolTip = chartConfig.showpercentintooltip, dsComponents = dataset.components, dataStore = dsComponents.data, xAxis = dataset.getFromEnv('xAxis'), i = 0, j = 0, dataObj, animAttrs, isStacked = chartConfig.isstacked, stack100Percent = Number(chartConfig.stack100percent), step = chartConfig.viewPortConfig.step || 1, visibleStart, visibleEnd, hasScroll = chart.hasScroll, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), labelDrawArray = skippingInfo && skippingInfo.labelDraw || [], plotDrawArray = skippingInfo && skippingInfo.draw || []; // Saving the anim attributes animAttrs = dsComponents.animAttrs = []; dataset.calculateScrollRange(); if (!xAxis.getState('scrolling')) { // For Stack charts recalculate the y pos isStacked && (stack100Percent || showpercentvalues || showPercentInToolTip) && dataset.updateYForStack(); } dataset.createCoordinates(); for (j = dsConfig.scrollMinVal; j < dsConfig.scrollMaxVal; j += step) { i = plotDrawArray[j] || j; if (hasScroll && !chartConfig.skipAttr && (i < visibleStart || i > visibleEnd)) { continue; } dataObj = dataStore[i]; if (!dataObj || !dataObj.config) { animAttrs[i] = UNDEF; continue; } dataset.parsePlotAttributes(dataObj, i); } // If there is no stepping, all plots have been drawn anyway. if (step > 1) { dsConfig.skipIgnorerIndices.map(function (skipIgnorerIdx) { return dataStore[skipIgnorerIdx]; }).filter(function (skipIgnorer) { return skipIgnorer || skipIgnorer.config; }).forEach(function (skipIgnorer) { return dataset.parsePlotAttributes(skipIgnorer, i); }); } for (j = dsConfig.scrollMinValForLabel; j < dsConfig.scrollMaxValForLabel; j += step) { i = labelDrawArray[j] || j; dataObj = dataStore[i]; dataset.parseLabelAttributes(dataObj, i); } }; AreaDataset.prototype.drawPlot = function drawPlot(dataObj, i) { var dataset = this, dsConfig = dataset.config, plotConfig = dataObj.config, graphics = dataObj.graphics, anchorProps = plotConfig.anchorProps, visible = dataset.getState('visible'), radius = anchorProps.radius, anchorShadow = anchorProps.shadow, anchorAlpha = anchorProps.anchorAlpha, isAnchorVisible = radius && anchorAlpha, anchorGroup = dataset.getContainer('plotGroup'), shadowGroup = dataset.getContainer('shadowGroup'), animationManager = dataset.getFromEnv('animationManager'), setElement = void 0, hoverEffects = void 0, imageElement = void 0; if (plotConfig._y !== null && plotConfig._x !== null) { if (anchorProps.imageUrl) { // If imageurl is present, i.e. the data plot is an image dataset.drawAnchorImage(dataObj); } else { // Else the data plot is not an image. /** * The Raphael Element referring to the current data plot. * @type {Element} */ setElement = graphics.element; // Hide the image element (in case it was present and visible) imageElement = graphics.image; imageElement && imageElement.remove(); delete graphics.image; if ((dsConfig.drawanchors || isAnchorVisible) && visible && dataObj.config.setValue !== null) { setElement = graphics.element = animationManager.setAnimation({ el: setElement || 'path', container: anchorGroup, attr: plotConfig.props.element.attr, index: i, length: length, callback: function callback() { this.show(); }, component: dataset, label: 'anchor' }); // Add the shadow of the eleemnt to the shadow container setElement.shadow(anchorShadow, shadowGroup); } else if (setElement) { dataset.__removeElem(graphics.element, 'element'); delete graphics.element; setElement = UNDEF; } } hoverEffects = plotConfig.hoverEffects; if (setElement) { if (hoverEffects.enabled) { setElement.data('hoverEnabled', hoverEffects.attrs.hoverEnabled).data('anchorRadius', hoverEffects.attrs.anchorRadius).data('anchorHoverRadius', hoverEffects.attrs.anchorHoverRadius).data(SETROLLOVERATTR, hoverEffects.attrs[SETROLLOVERATTR]) // .data('alwaysInvisible', hoverEffects.attrs.alwaysInvisible) // .data('setRolloverProperties', hoverEffects.attrs.setRolloverProperties) .data(SETROLLOUTATTR, hoverEffects.attrs[SETROLLOUTATTR]); } else { // hovereffect is disabled. setElement.data('hoverEnabled', false); } setElement.data(EVENTARGS, plotConfig && plotConfig.eventArgs); } } else { graphics.element && (graphics.element = animationManager.setAnimation({ el: graphics.element, component: dataset })); } }; /** * drawPlots: Function to draw anchor elements or columns in case of column chart */ AreaDataset.prototype.drawPlots = function drawPlots() { var dataset = this, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, dsComponents = dataset.components, dsConfig = dataset.config, dataStore = dsComponents.data, i = 0, j = 0, dataObj, animAttrs = dsComponents.animAttrs, scrollMinVal, scrollMaxVal, _oldStartIndex = dsConfig._oldStartIndex, _oldEndIndex = dsConfig._oldEndIndex, sharedElem = dataset.getGraphicalElement('sharedAnchor'), drwCnt = 0, step = chartConfig.viewPortConfig.step || 1, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotDrawArray = skippingInfo && skippingInfo.draw || []; // Saving the anim attributes animAttrs = dsComponents.animAttrs = []; scrollMinVal = dsConfig.scrollMinVal; scrollMaxVal = dsConfig.scrollMaxVal; if (scrollMinVal > _oldStartIndex) { dataset.flushOnScroll(_oldStartIndex, scrollMinVal > _oldEndIndex ? _oldEndIndex : scrollMinVal); } if (scrollMaxVal < _oldEndIndex) { dataset.flushOnScroll(scrollMaxVal < _oldStartIndex ? _oldStartIndex : scrollMaxVal, _oldEndIndex); } dsConfig._oldStartIndex = scrollMinVal; dsConfig._oldEndIndex = scrollMaxVal; dataset.hideAllAnchors && dataset.hideAllAnchors(); for (j = scrollMinVal; j < scrollMaxVal; j += step) { i = plotDrawArray[j] || j; // Contains configurations specific to the 'i'th plot. Also contains an initially empty // graphics object which has the Raphael element associated with this plot dataObj = dataStore[i]; if (!dataObj || !dataObj.config) { animAttrs[i] = UNDEF; continue; } dataset.drawPlot(dataObj, i); } // If there is no stepping, all plots have been drawn anyway. if (step > 1) { dsConfig.skipIgnorerIndices.map(function (skipIgnorerIdx) { return dataStore[skipIgnorerIdx]; }).filter(function (skipIgnorer) { return skipIgnorer || skipIgnorer.config; }).forEach(function (skipIgnorer) { return dataset.drawPlot(skipIgnorer, i); }); } // In a case when all the anchors and shared anchor both are drawn then hide // shared anchor and if chart is rendered without any anchors draw a single anchor. if (i === drwCnt || dsConfig.drawanchors) { sharedElem && sharedElem.hide(); } else { if (sharedElem) { sharedElem.hide(); } else { // create a shared anchor dataset.getAnchor(); } } }; /** * function to handle anchor image draw job */ AreaDataset.prototype.drawAnchorImage = function drawAnchorImage(dataObj) { var dataset = this, anchorGroup = dataset.getContainer('plotGroup'), graphics = dataObj.graphics, animationManager = dataset.getFromEnv('animationManager'), imageElement = void 0, imageElementDummy = isVML ? graphics.element : graphics.image, anchorProps = dataObj.config.anchorProps, isAnchorVisible = anchorProps.anchorAlpha && anchorProps.radius, alpha = anchorProps.imageAlpha, visible = dataset.getState('visible'); if (visible && isAnchorVisible) { if (!isVML) { graphics.element = animationManager.setAnimation({ el: graphics.element || 'path', container: anchorGroup, attr: dataObj.config.props.element.attr, label: 'anchor', component: dataset }).show(); } dataObj.config.props.element.attr.opacity = alpha * 0.01; imageElement = animationManager.setAnimation({ el: imageElementDummy || 'image', container: anchorGroup, component: dataset, label: 'anchor', attr: { opacity: alpha * 0.01 } }); if (isVML) { graphics.element = imageElement; } else { graphics.image = imageElement; } if (!imageElementDummy) { imageElement.on('load', dataset._onAnchorImageLoad(dataObj)); imageElement.attr('src', anchorProps.imageUrl); } else { if (imageElement.attrs.src !== anchorProps.imageUrl) { imageElement.attr('src', anchorProps.imageUrl); } else { imageElement._.RefImg && _imageDrawHelper(dataset, dataObj); } } imageElement.show(); } else { graphics.image && animationManager.setAnimation({ el: graphics.image, state: 'disappearing', component: dataset, doNotRemove: true, callback: function callback() { this.hide(); } }); graphics.element && animationManager.setAnimation({ el: graphics.element, state: 'disappearing', component: dataset, doNotRemove: true, callback: function callback() { this.hide(); } }); } }; AreaDataset.prototype.getLineSegment = function getLineSegment(path, config, type) { var dataset = this, xPos = config._Px, yPos = config._Py, baseXPos = config._Pbx, baseYPos = config._Pby, yAxis = dataset.getFromEnv('yAxis'), baseZero = yAxis.getPixel(0), setValue = config.setValue, connectNullData = dataset.getFromEnv('chart').config.connectnulldata; // take base or zero y value for animation if (type === 'zero') { yPos = baseZero; baseYPos = baseZero; } else if (type === 'base') { yPos = config._Pby; } // create the path array // If the last value is valid if (setValue === null || setValue.isNull) { // If null data points are also to be connected if (!connectNullData) { // Checking if any points are joined then closing the path if (path.pointsJoined > 0) { // Check if the last command of the path is not Z if (path.path2Arr[path.path2Arr.length - 1] !== Z && baseYPos !== UNDEF) { path.path2Arr.push(Z); } path.pathArr = path.pathArr.concat(path.path2Arr); path.path2Arr = []; } path.temp = []; path.temp2 = []; path.lastValidValue = false; } } else { if (path.lastValidValue) { if (path.temp.length) { path.pathArr = path.pathArr.concat(path.temp); if (baseXPos !== UNDEF) { path.path2Arr = path.temp2; path.temp2 = []; } path.temp = []; path.pointsJoined++; } // Push the upper x and y position to pathArr path.pathArr.push([L, xPos, yPos]); if (baseYPos !== UNDEF) { // Push the lower x y positions to the front of the array for joining the last // upper point and first lower point of the area plot path.path2Arr.unshift([L, xPos, baseYPos]); } } else { // Push the upper x and y positions of area plot to temp path.temp.push([M, xPos, yPos]); if (baseYPos !== UNDEF) { // Push the lower x and y position of area plot to temp2 path.temp2.push([L, baseXPos, baseYPos]); } // No points are joined when starting a new path path.pointsJoined = 0; path.lastValidValue = true; } } return path; }; AreaDataset.prototype.getLinePath = function getLinePath(data, positions, type) { var dataset = this, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, // Used for determining whether the last value was valid // Initially it is false i, j, config, baseYPos, length = data.length, dataObj, setValue, startPos = positions && positions.begin || 0, endPos = dataset.getState('visible') ? positions && positions.end || length : 0, step = chartConfig.viewPortConfig.step || 1, removeDataLen = dataset.removeDataLen || 0, dataWithRemovedPaths = [], skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotDrawArray = skippingInfo && skippingInfo.draw || [], plotDrawArrayLength = plotDrawArray.length, skippingApplied = skippingInfo && skippingInfo.skippingApplied, skipIgnorerIndices = dataset.config.skipIgnorerIndices, dataConfigs = [], pathObj = {}, latestSkipIgnorerIdx = 0, prevJ, interimData, interimConfig, interimSetValue; removeDataLen = 0; // Added current dataStore to arr dataWithRemovedPaths = dataWithRemovedPaths.concat(data); if (skippingApplied) { startPos = 0; endPos = plotDrawArrayLength; } for (j = startPos + removeDataLen; j < endPos + removeDataLen; j += step) { i = plotDrawArray[j] || j; dataObj = dataWithRemovedPaths[i]; if (!dataObj) { continue; } config = dataObj.config; setValue = config.setValue; // skip the data plot if isSkipped flag is set to false if (setValue === UNDEF || config && config.isSkipped === true) { config && delete config.isSkipped; continue; } if (step > 1) { while (skipIgnorerIndices[latestSkipIgnorerIdx] < j) { interimData = dataWithRemovedPaths[skipIgnorerIndices[latestSkipIgnorerIdx]]; if (!interimData) { continue; } interimConfig = interimData.config; interimSetValue = interimConfig.setValue; // skip the data plot if isSkipped flag is set to false if (interimSetValue === UNDEF || interimConfig && interimConfig.isSkipped === true) { interimConfig && delete interimConfig.isSkipped; continue; } dataConfigs = dataConfigs.concat(interimConfig); latestSkipIgnorerIdx++; } } dataConfigs = dataConfigs.concat(config); baseYPos = config._Pby; prevJ = j; } if (step > 1) { for (i = prevJ + 1; i <= j; i++) { dataObj = dataWithRemovedPaths[plotDrawArray[i] || i]; if (!dataObj) { continue; } config = dataObj.config; setValue = config.setValue; // skip the data plot if isSkipped flag is set to false if (setValue === UNDEF || config && config.isSkipped === true) { config && delete config.isSkipped; continue; } if (skipIgnorerIndices.includes(i)) { dataConfigs = dataConfigs.concat(config); baseYPos = config._Pby; } } } pathObj = dataConfigs.reduce(function (path, dataConfig) { return dataset.getLineSegment(path, dataConfig, type); }, { temp: [], temp2: [], pathArr: [], path2Arr: [], pointsJoined: 0, lastValidValue: false, getPathArr: getPathArr }); // If path is not closed and any points are joined then close the path if (pathObj.path2Arr[pathObj.path2Arr.length - 1] !== Z && pathObj.pointsJoined > 0 && baseYPos !== UNDEF) { pathObj.path2Arr.push(Z); } return pathObj; }; // Function to remove a data from a dataset during real time update. AreaDataset.prototype._removeDataVisuals = function _removeDataVisuals(dataObj) { var dataSet = this, pool = dataSet.components.pool || (dataSet.components.pool = {}), elementPool, ele, graphics, graphicsObj; if (!dataObj) { return; } graphics = dataObj.graphics; for (ele in graphics) { elementPool = pool[ele] || (pool[ele] = []); graphicsObj = graphics[ele]; if (graphicsObj.hide && typeof graphicsObj.hide === 'function') { graphicsObj.attr({ 'text-bound': [] }); graphicsObj.hide(); graphicsObj.shadow && graphicsObj.shadow(false); } elementPool.push(graphics[ele]); } }; /** * parse the anchor properties at set level * @param {number} i - set index * Called from configure function of area class for each set data of dataset */ AreaDataset.prototype._parseAnchorProperties = function _parseAnchorProperties(i, dataArr) { var dataSet = this, conf = dataSet.config, // get the name of the dataset plotType = dataSet.getName(), chart = dataSet.getFromEnv('chart'), anchorAlpha = chart.config.anchoralpha, // DefaultAnchorVisibility should be 0 for all area charts. defaultAnchorVisibility = !chart.config.anchoralpha && /area/ig.test(plotType) ? 0 : 1, JSONData = conf.JSONData, chartAttr = chart.getFromEnv('dataSource').chart, setDataArr = dataArr || JSONData.data || [], setData = setDataArr[i] || {}, anchorProps = {}, showAnchorShadow, anchorAttrsDefined, drawAnchors; // Check if anchor attributes are defined anchorAttrsDefined = (0, _lib.pluck)(setData.anchorstartangle, JSONData.anchorstartangle, chartAttr.anchorstartangle, setData.anchorimagealpha, JSONData.anchorimagealpha, chartAttr.anchorimagealpha, setData.anchorimagescale, JSONData.anchorimagescale, chartAttr.anchorimagescale, setData.anchorimagepadding, JSONData.anchorimagepadding, chartAttr.anchorimagepadding, setData.anchorimageurl, JSONData.anchorimageurl, chartAttr.anchorimageurl, setData.anchorradius, JSONData.anchorradius, chartAttr.anchorradius, setData.anchorbgcolor, JSONData.anchorbgcolor, chartAttr.anchorbgcolor, setData.anchorbordercolor, JSONData.anchorbordercolor, chartAttr.anchorbordercolor, setData.anchoralpha, JSONData.anchoralpha, chartAttr.anchoralpha, setData.anchorsides, JSONData.anchorsides, chartAttr.anchorsides, setData.anchorborderthickness, JSONData.anchorborderthickness, chartAttr.anchorborderthickness, UNDEF) !== UNDEF; drawAnchors = (0, _lib.pluckNumber)(setData.drawanchors, conf.drawanchors); /* If any anchor attribute is defined then we choose between draw anchors attribute and whether any anchor attributes are defined Otherwise we choose between default anchor visibility which is false for area and true for line and drawanchors attribute */ if (anchorAttrsDefined) { anchorProps.enabled = (0, _lib.pluckNumber)(drawAnchors, anchorAttrsDefined); } else { anchorProps.enabled = (0, _lib.pluckNumber)(drawAnchors, defaultAnchorVisibility); } anchorProps.startAngle = (0, _lib.pluckNumber)(setData.anchorstartangle, conf.anchorstartangle); anchorProps.imageAlpha = (0, _lib.pluckNumber)(setData.anchorimagealpha, conf.anchorimagealpha); anchorProps.imageScale = (0, _lib.pluckNumber)(setData.anchorimagescale, conf.anchorimagescale); anchorProps.imagePadding = (0, _lib.pluckNumber)(setData.anchorimagepadding, conf.anchorimagepadding); if (anchorProps.imagePadding < 0) { anchorProps.imagePadding = 0; } anchorProps.imageUrl = (0, _lib.pluck)(setData.anchorimageurl, conf.anchorimageurl); if (anchorProps.imageUrl) { conf.imageCount++; } anchorProps.radius = anchorProps.enabled ? (0, _lib.pluckNumber)(setData.anchorradius, conf.anchorradius) : 0; anchorProps.isAnchorRadius = (0, _lib.pluck)(setData.anchorradius, JSONData.anchorradius, chartAttr.anchorradius); anchorProps.bgColor = (0, _lib.pluck)(setData.anchorbgcolor, conf.anchorbgcolor); if (!anchorProps.enabled) { anchorAlpha = 0; } else { anchorAlpha = (0, _lib.getFirstAlpha)((0, _lib.pluck)(setData.anchoralpha, conf.anchoralpha, anchorProps.enabled ? _lib.HUNDREDSTRING : '0')); } anchorProps.anchorAlpha = anchorAlpha; anchorProps.bgAlpha = (0, _lib.getFirstAlpha)((0, _lib.pluck)(setData.anchorbgalpha, conf.anchorbgalpha, anchorAlpha)) * anchorAlpha / 100; anchorProps.imageAlpha = anchorProps.imageAlpha * anchorAlpha / 100; anchorProps.borderColor = (0, _lib.pluck)(setData.anchorbordercolor, conf.anchorbordercolor); anchorProps.borderAlpha = anchorAlpha; anchorProps.sides = (0, _lib.pluck)(setData.anchorsides, conf.anchorsides); anchorProps.borderThickness = (0, _lib.pluck)(setData.anchorborderthickness, conf.anchorborderthickness); anchorProps.symbol = (0, _lib.mapSymbolName)(anchorProps.sides).split('_'); showAnchorShadow = (0, _lib.pluckNumber)(setData.anchorshadow, conf.anchorshadow) && anchorProps.radius >= 1; anchorProps.shadow = { opacity: showAnchorShadow ? anchorAlpha / 100 : 0 }; return anchorProps; }; AreaDataset.prototype._hideGraphics = function _hideGraphics(graphics) { var dataset = this, graphicObj, prop; for (prop in graphics) { if (graphics.hasOwnProperty(prop)) { graphicObj = graphics[prop]; if (!graphicObj) { continue; } if (graphicObj.hide) { graphicObj.hide(); } else { dataset._hideGraphics(graphicObj); } } } }; /* * Parses the hover effect attributes for set level * @param {Object} setData * Called from configure function of area class */ AreaDataset.prototype._parseHoverEffectOptions = function _parseHoverEffectOptions(dataObj, setData) { var dataset = this, JSONData = dataset.config.JSONData, chart = dataset.getFromEnv('chart'), chartAttr = chart.getFromEnv('dataSource').chart, chartConfig = chart.config, config = dataObj.config, conf = dataset.config, anchorProps = config.anchorProps || {}, showHoverEffect = chartConfig.plothovereffect, drawAnchors = conf.drawanchors, hoverEffects = { enabled: false }; setData = setData || {}; if (showHoverEffect !== 0 && drawAnchors !== 0) { // Checking if any hover attributes are defined // If defined then set enabled true hoverEffects.enabled = (0, _lib.pluck)(setData.hovercolor, setData.anchorhovercolor, setData.hovercolor, JSONData.hovercolor, setData.anchorbghovercolor, JSONData.anchorbghovercolor, chartAttr.anchorbghovercolor, JSONData.anchorhovercolor, chartAttr.anchorhovercolor, setData.hoveralpha, setData.anchorhoveralpha, JSONData.anchorhoveralpha, chartAttr.anchorhoveralpha, setData.bghoveralpha, setData.anchorbghoveralpha, JSONData.anchorbghoveralpha, chartAttr.anchorbghoveralpha, setData.anchorborderhovercolor, setData.borderhovercolor, JSONData.anchorborderhovercolor, chartAttr.anchorborderhovercolor, setData.anchorborderhoverthickness, setData.borderhoverthickness, JSONData.anchorborderhoverthickness, chartAttr.anchorborderhoverthickness, setData.anchorborderhoveralpha, setData.borderhoveralpha, JSONData.anchorborderhoveralpha, chartAttr.anchorborderhoveralpha, setData.hoverdip, setData.anchorhoverdip, JSONData.anchorhoverdip, chartAttr.anchorhoverdip, setData.anchorhoverstartangle, JSONData.anchorhoverstartangle, chartAttr.anchorhoverstartangle, setData.hoversides, setData.anchorhoversides, JSONData.anchorhoversides, chartAttr.anchorhoversides, setData.hoverradius, setData.anchorhoverradius, JSONData.anchorhoverradius, chartAttr.anchorhoverradius, JSONData.plotfillhovercolor, chartAttr.plotfillhovercolor, chartConfig.plothovereffect, UNDEF) !== UNDEF; hoverEffects.startAngle = (0, _lib.pluckNumber)(setData.anchorhoverstartangle, JSONData.anchorhoverstartangle, chartAttr.anchorhoverstartangle, anchorProps.startAngle); hoverEffects.anchorSides = (0, _lib.pluckNumber)(setData.hoversides, setData.anchorhoversides, JSONData.anchorhoversides, chartAttr.anchorhoversides, anchorProps.sides); hoverEffects.anchorRadius = (0, _lib.pluckNumber)(setData.anchorhoverradius, JSONData.anchorhoverradius, chartAttr.anchorhoverradius); hoverEffects.isAnchorHoverRadius = hoverEffects.anchorRadius; hoverEffects.anchorRadius = (0, _lib.pluckNumber)(hoverEffects.anchorRadius, anchorProps.radius + (showHoverEffect ? 2 : 0)); hoverEffects.anchorScale = (0, _lib.pluck)(setData.hoverscale, JSONData.anchorscale, chartAttr.anchorscale); hoverEffects.imageHoverScale = (0, _lib.pluckNumber)(setData.anchorimagehoverScale, JSONData.anchorimagehoverscale, chartAttr.anchorimagehoverscale, 110); hoverEffects.imageHoverAlpha = (0, _lib.pluckNumber)(setData.anchorimagehoveralpha, JSONData.anchorimaghoverealpha, chartAttr.anchorimagehoveralpha); hoverEffects.anchorAlpha = (0, _lib.pluck)(setData.anchorhoveralpha, setData.hoveralpha, JSONData.anchorhoveralpha, chartAttr.anchorhoveralpha, anchorProps.anchorAlpha); hoverEffects.anchorColor = (0, _lib.getFirstColor)((0, _lib.pluck)(setData.hovercolor, setData.anchorhovercolor, setData.hoverColor, setData.anchorbghovercolor, JSONData.anchorbghovercolor, JSONData.anchorhovercolor, JSONData.hovercolor, chartAttr.anchorbghovercolor, chartAttr.anchorhovercolor, chartAttr.plotfillhovercolor, anchorProps.bgColor)); hoverEffects.anchorBgAlpha = (0, _lib.pluck)(setData.bghoveralpha, setData.anchorbghoveralpha, JSONData.anchorbghoveralpha, chartAttr.anchorbghoveralpha, chartAttr.plotfillhoveralpha, anchorProps.bgAlpha); hoverEffects.anchorBgAlpha = hoverEffects.anchorBgAlpha * hoverEffects.anchorAlpha / 100; hoverEffects.anchorBorderColor = (0, _lib.pluck)(setData.borderhovercolor, setData.anchorborderhovercolor, JSONData.anchorborderhovercolor, chartAttr.anchorborderhovercolor, anchorProps.borderColor); hoverEffects.anchorBorderAlpha = (0, _lib.pluck)(setData.borderhoveralpha, setData.anchorborderhoveralpha, JSONData.anchorborderhoveralpha, chartAttr.anchorborderhoveralpha, hoverEffects.anchorAlpha, anchorProps.borderAlpha); hoverEffects.anchorBorderThickness = (0, _lib.pluckNumber)(setData.borderhoverthickness, setData.anchorborderhoverthickness, JSONData.anchorborderhoverthickness, chartAttr.anchorborderhoverthickness, chartAttr.anchorBorderThickness, anchorProps.borderThickness); hoverEffects.dip = (0, _lib.pluck)(setData.hoverdip, setData.anchorhoverdip, JSONData.anchorhoverdip, chartAttr.anchorhoverdip, anchorProps.dip); hoverEffects.anchorAnimation = (0, _lib.pluckNumber)(setData.anchorhoveranimation, JSONData.anchorhoveranimation, chartAttr.anchorhoveranimation, 1); } return hoverEffects; }; /** * Sets the attributes of the anchor elements when hovering over anchor * @param {Object} plotItem - object of plotItem * @param {Object} eventType - type of event * @param {Object} chartAttr - attributes of chart * Called from rollOverResponseSetter and rolloutresponsesetter function of line and area */ AreaDataset.prototype._hoverPlotAnchor = function _hoverPlotAnchor(plotItem, eventType) { var dataset = this, smartLabel = dataset.getFromEnv('smartLabel'), canvas = dataset.getFromEnv('chart').getChildren('canvas')[0], canvasDimension = canvas.getEffectiveDimensions(), canvasTop = canvasDimension.top, canvasBottom = canvasTop + canvasDimension.height, plotY = plotItem.config._Py, labelHeight, labelDim, animationManager = dataset.getFromEnv('animationManager'), sharedAnchor = dataset.getGraphicalElement('sharedAnchor'), plotElem = plotItem.graphics.element || sharedAnchor, valElem = plotItem.graphics.label, config = plotItem.config || {}, anchorAlpha = config.anchorProps.anchorAlpha, anchorImageUrl = config && config.anchorProps.imageUrl, plotElemImage = isVML && anchorImageUrl ? plotItem.graphics.element : plotItem.graphics.image, isImg = plotElem.type === 'image', anchorRadius = plotElem.data('anchorRadius'), anchorHoverRadius = plotElem.data('anchorHoverRadius'), // hoverEffects = plotItem.config.hoverEffects, // Fetch the rollOver and rollOut configurations from the plot elements. elemHoverAttr = plotElem.data(SETROLLOVERATTR), elemUnHoverAttr = plotElem.data(SETROLLOUTATTR), // Radius diff is how much we have to shift the position of the value element // when animating it. If the value is above the anchor then we are // shifting the value upwards otherwise downwards radiusDiff = valElem && (valElem.data('isBelow') ? 1 : -1) * (isImg ? (elemHoverAttr.height - elemUnHoverAttr.height) * 0.5 : anchorHoverRadius - anchorRadius), selectedAttr = eventType === ROLLOVER ? elemHoverAttr : elemUnHoverAttr, animationImageAttr, elemImageHoverAttr, elemImageUnHoverAttr, isVisible = true, animationAttr = { path: selectedAttr.path }, shiftValues = 1, staticAttr = { fill: selectedAttr.fill, 'stroke-width': selectedAttr['stroke-width'], stroke: selectedAttr.stroke }, rotation = valElem && valElem.data('rotation') || '', valAnimation; labelDim = smartLabel.getOriSize(config.displayValue); labelHeight = labelDim.height; // Calculation to make sure that label do not translate out of canvas if (plotY - 3 * labelHeight / 2 + radiusDiff < canvasTop) { radiusDiff = canvasTop - plotY + 3 * labelHeight / 2; } else if (plotY + 3 * labelHeight / 2 + radiusDiff > canvasBottom) { radiusDiff = canvasBottom - plotY - 3 * labelHeight / 2; } valAnimation = { transform: 'T0,' + (eventType === ROLLOVER ? radiusDiff : 0) + rotation }; animationManager.setAnimationState(eventType === ROLLOVER ? MOUSEOVER : MOUSEOUT); if (plotElemImage) { elemImageHoverAttr = plotElemImage.data(SETROLLOVERATTR); elemImageUnHoverAttr = plotElemImage.data(SETROLLOUTATTR); animationImageAttr = eventType == ROLLOVER ? elemImageHoverAttr : elemImageUnHoverAttr; animationImageAttr.alpha *= 0.01; } if (isImg) { animationAttr.alpha *= 0.01; } else { Object.assign(animationAttr, staticAttr); } if (eventType === ROLLOVER && !anchorHoverRadius || eventType === ROLLOUT && !anchorRadius) { isVisible = false; } animationManager.setAnimation({ el: plotElem, label: 'anchor', component: dataset, doNotRemove: true, callback: function callback() { !isVisible && plotElem.hide(); }, attr: isVisible && animationAttr }); isVisible && plotElem.show(); // If image is present then animating the image too if (plotElemImage) { animationManager.setAnimation({ el: plotElemImage, label: 'anchor', component: dataset, attr: isVisible && animationImageAttr }); isVisible && plotElemImage.show(); } /** * Concept of shared Anchor: * 1. When the data is large, there is no point in drawing the anchor of all the points, * as that will increase the DOM count and is also not visually appealing. So shared anchor * will only be drawn over hovered point in such cases. * 2. When anchors are not drawn(radius = 0, or alpha = 0), the sharedAnchor is only drawn over the * hover points */ // Animating the values if (plotItem.graphics && plotItem.graphics.element || sharedAnchor && sharedAnchor.element) { anchorAlpha && shiftValues && valElem && animationManager.setAnimation({ el: valElem, label: 'label', component: dataset, doNotRemove: true, attr: valAnimation }); } }; /** * Draws a label * Called for each data value to be drawn from draw function of kagi * @param {number} i - index of data */ AreaDataset.prototype.drawLabel = function drawLabel(start, end) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, SmartLabel = dataSet.getFromEnv('smartLabel'), style = chart.config.dataLabelStyle, dataStore = dataSet.components.data, paper = dataSet.getFromEnv('paper'), animationManager = dataSet.getFromEnv('animationManager'), displayValue = '', rotateValues = chartConfig.rotatevalues ? 270 : 0, dataLabelContainer = dataSet.getContainer('labelGroup'), graphic, textY, textX, config, showValue, labelElement, labelStyle, dataObj, i, j, setValue, attr, tempGraphics, visible = dataSet.getState('visible'), len = dataStore.length, showLabel, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), skippingApplied = skipInfo && skipInfo.skippingApplied, plotDrawArray = skipInfo && skipInfo.labelDraw || [], plotDrawArrayLength = plotDrawArray.length, startIndex = (0, _lib.pluckNumber)(start, 0), endIndex = (0, _lib.pluckNumber)(end, skippingApplied ? plotDrawArrayLength : len), notParticularLabeDraw = plotDrawArrayLength === Math.abs(endIndex - (startIndex + 1)); labelStyle = { 'font-weight': style.fontWeight, 'font-style': style.fontStyle, 'font-family': style.fontFamily, 'font-size': style.fontSize, 'line-height': style.lineHeight }; SmartLabel.setStyle(labelStyle); for (j = startIndex; j < endIndex; j++) { i = skippingApplied && notParticularLabeDraw ? plotDrawArray[j] : j; dataObj = dataStore[i]; config = dataObj && dataObj.config; setValue = config && config.setValue; if (dataObj === UNDEF || setValue === UNDEF || setValue === null || config.labelSkip === true) { config && delete config.labelSkip; tempGraphics = dataObj && dataObj.graphics; if (tempGraphics && tempGraphics.label) { tempGraphics.label = animationManager.setAnimation({ el: tempGraphics.label, component: dataSet }); } continue; } graphic = dataObj.graphics; displayValue = config.displayValue; showValue = config.showValue; labelElement = graphic.label; attr = config.props.label.attr; // Drawing label only if displayvalue is defined and not blank and setValue is not null showLabel = defined(displayValue) && showValue && visible; if (showLabel) { // set textX textY textX = config.props.label.attr.x; textY = config.props.label.attr.y; attr.transform = paper.getSuggestiveRotation(rotateValues, textX, textY); graphic.label = labelElement = animationManager.setAnimation({ el: labelElement || 'text', container: dataLabelContainer, component: dataSet, attr: attr, label: 'label' }); labelElement.data('isBelow', config._valueBelowPoint); labelElement.data('rotation', attr.transform); } else if (labelElement) { graphic.label = animationManager.setAnimation({ el: labelElement, component: dataSet, label: 'label' }); } } }; /** * function to return defalut value padding * @return {Object} default padding value for axis */ AreaDataset.prototype.getAxisValuePadding = function getAxisValuePadding() { return this.config.defaultPadding; }; AreaDataset.prototype._hoverFunc = function _hoverFunc(dataObj, state, hoverEnabled, chartAttr) { if (hoverEnabled) { return this._hoverPlotAnchor(dataObj, state, chartAttr); } }; /** * Called when the image is loaded from draw function of line and area * Handles all the tasks needed to be done when the image is loaded * @param {number} i - data index * @param {object} eventArgs - event arguments of data object * @param {number} x - x position of anchor * @param {number} y - y position of anchor * @param {object} dataObject - plot */ AreaDataset.prototype._onAnchorImageLoad = function _onAnchorImageLoad(dataObject) { var dataset = this; return function () { var i = dataObject._index; _imageDrawHelper(dataset, dataObject); dataset.config.drawn ? dataset.drawLabel(i, i + 1) : dataset.addJob(LABELUPDATEONIMAGELOADID + i, function () { dataset.drawLabel(i, i + 1); }, _schedular.priorityList.label); }; }; return AreaDataset; }(_column2['default']); exports['default'] = AreaDataset; /***/ }), /* 451 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { '*.dataset.area': function datasetArea() { return { 'anchor.appearing': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, startEnd: { start: 0.5, end: 1 }, slot: 'plot' }], 'anchor.updating': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'anchor.disappearing': [{ finalAttr: { opacity: 0, 'fill-opacity': 0, 'stroke-opacity': 0 }, slot: 'final' }], 'line.appearing': function lineAppearing(inputJSON) { var dataset = inputJSON.component, dataStore = dataset.components.data, isStacked = dataset.getFromEnv('chartConfig').isstacked, is3D = dataset.getFromEnv('chartConfig').is3D, initialPath = dataset.getLinePath(dataStore, null, isStacked || is3D ? 'base' : 'zero'), finalAttr = inputJSON.attr, length = dataset.getState('_total'), i = dataset.config._childIndex; return [{ initialAttr: { opacity: 0, path: initialPath.getPathArr() }, finalAttr: { opacity: 1, path: finalAttr.path }, startEnd: { start: isStacked ? 0.5 / length * i : 0, end: isStacked ? 0.5 / length * (i + 1) : 0.5 }, slot: 'plot', hookFn: function hookFn() { this.attr({ opacity: 1 }); } }]; }, 'label.appearing': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'label.updating': function labelUpdating() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; }, 'group.appearing': function groupAppearing(inputJSON) { if (inputJSON.attr.name === 'label-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } else if (inputJSON.attr.name === 'plot-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, startEnd: { start: 0.5, end: 1 }, slot: 'plot' }]; } else { return [{ initialAttr: { opacity: 1 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } }, '*': null }; } }; /***/ }), /* 452 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { '*.dataset.line': function datasetLine() { var dataset = this, clipCanvas = dataset.getClip('canvas'), clipCanvasInit = dataset.getClip('init'); return { 'anchor.appearing': function anchorAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; }, 'anchor.updating': function anchorUpdating() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'plot' }]; }, 'anchor.disappearing': function anchorDisappearing() { return [{ finalAttr: { opacity: 0, 'fill-opacity': 0, 'stroke-opacity': 0 }, slot: 'plot' }]; }, 'line.appearing': function lineAppearing() { return [{ initialAttr: { 'clip-rect': clipCanvasInit }, finalAttr: { 'clip-rect': clipCanvas }, slot: 'middle', callback: function callback() { this.attr({ 'clip-rect': null }); } }]; }, 'line.updating': function lineUpdating() { return [{ initialAttr: { opacity: 1, 'clip-rect': clipCanvasInit }, finalAttr: { opacity: 1, 'clip-rect': clipCanvas }, slot: 'plot' }]; }, 'label.appearing': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'group.appearing': function groupAppearing(inputJSON) { if (inputJSON.attr.name === 'label-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } else if (inputJSON.attr.name === 'plot-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, startEnd: { start: 0.5, end: 1 }, slot: 'plot' }]; } else { return [{ initialAttr: { opacity: 1 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } }, '*': null }; } }; /***/ }), /* 453 */, /* 454 */, /* 455 */, /* 456 */, /* 457 */, /* 458 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.__postSpaceManagement = exports.__spaceManager = exports.__feedAxesRawData = undefined; var _mscartesian = __webpack_require__(459); var _mscartesian2 = _interopRequireDefault(_mscartesian); var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * This method parse all the attributes which are associated with axis compoenents. * So that axis compoenents can be configured. * @return { Object } contains axes config */ function __feedAxesRawData() { var iapi = this, chartConfig = iapi.config, colorM = iapi.getFromEnv('color-manager'), dataObj = iapi.getFromEnv('dataSource'), chartAttrs = dataObj.chart, xAxisConf, yAxisConf, is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D; xAxisConf = { isVertical: true, isReverse: false, isOpposit: false, outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisNamePadding: chartAttrs.xaxisnamepadding, maxLabelWidthPercent: chartAttrs.maxlabelwidthpercent, // Attribute minLabelWidthPercent is fetched minLabelWidthPercent: chartAttrs.minlabelwidthpercent, axisValuePadding: chartAttrs.labelpadding, axisNameFont: chartAttrs.xaxisnamefont, axisNameFontSize: chartAttrs.xaxisnamefontsize, axisNameFontColor: chartAttrs.xaxisnamefontcolor, axisNameFontBold: chartAttrs.xaxisnamefontbold, axisNameFontItalic: chartAttrs.xaxisnamefontitalic, axisNameBgColor: chartAttrs.xaxisnamebgcolor, axisNameBorderColor: chartAttrs.xaxisnamebordercolor, axisNameAlpha: chartAttrs.xaxisnamealpha, axisNameFontAlpha: chartAttrs.xaxisnamefontalpha, axisNameBgAlpha: chartAttrs.xaxisnamebgalpha, axisNameBorderAlpha: chartAttrs.xaxisnameborderalpha, axisNameBorderPadding: chartAttrs.xaxisnameborderpadding, axisNameBorderRadius: chartAttrs.xaxisnameborderradius, axisNameBorderThickness: chartAttrs.xaxisnameborderthickness, axisNameBorderDashed: chartAttrs.xaxisnameborderdashed, axisNameBorderDashLen: chartAttrs.xaxisnameborderdashlen, axisNameBorderDashGap: chartAttrs.xaxisnameborderdashgap, axisNameWidth: chartAttrs.xaxisnamewidth, useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, divLineColor: (0, _lib.pluck)(chartAttrs.vdivlinecolor, chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.vdivlinealpha, chartAttrs.divlinealpha, is3D ? colorM.getColor('divLineAlpha3D') : colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.vdivlinethickness, chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.vdivlinedashed, chartAttrs.vdivlineisdashed, chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.vdivlinedashlen, chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.vdivlinedashgap, chartAttrs.divlinedashgap, 2), // Alternate horizontal grid colors should not be applied in bar charts. showAlternateGridColor: 0, alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatehgridcolor, colorM.getColor('altHGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatehgridalpha, colorM.getColor('altHGridAlpha')), numDivLines: chartAttrs.numvdivlines, labelFont: chartAttrs.labelfont, labelFontSize: chartAttrs.labelfontsize, labelFontColor: chartAttrs.labelfontcolor, labelFontAlpha: chartAttrs.labelalpha, labelFontBold: chartAttrs.labelfontbold, labelFontItalic: chartAttrs.labelfontitalic, axisName: chartAttrs.xaxisname, axisMinValue: chartAttrs.xaxisminvalue, axisMaxValue: chartAttrs.xaxismaxvalue, setAdaptiveMin: chartAttrs.setadaptivexmin, adjustDiv: chartAttrs.adjustvdiv, labelDisplay: chartAttrs.labeldisplay, showLabels: chartAttrs.showlabels, rotateLabels: chartAttrs.rotatelabels, slantLabel: (0, _lib.pluckNumber)(chartAttrs.slantlabels, chartAttrs.slantlabel), labelStep: (0, _lib.pluckNumber)(chartAttrs.labelstep, chartAttrs.xaxisvaluesstep), showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showxaxisvalues, chartAttrs.showxaxisvalue), showLimits: chartAttrs.showvlimits, showDivLineValues: (0, _lib.pluckNumber)(chartAttrs.showvdivlinevalues, chartAttrs.showvdivlinevalues), zeroPlaneColor: chartAttrs.vzeroplanecolor, zeroPlaneThickness: (0, _lib.pluckNumber)(chartAttrs.vzeroplanethickness, chartAttrs.vdivlinethickness, 2), zeroPlaneAlpha: (0, _lib.pluckNumber)(chartAttrs.vzeroplanealpha, chartAttrs.vdivlinealpha, chartConfig.zeroplanealpha), showZeroPlaneValue: chartAttrs.showvzeroplanevalue, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, rotateAxisName: (0, _lib.pluckNumber)(chartAttrs.rotatexaxisname, 1), trendlineAlpha: chartAttrs.trendlinealpha, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, showAxisLine: is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showxaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, 0), axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.xaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.xaxislinealpha, chartAttrs.axislinealpha, 100), axisLineColor: (0, _lib.pluck)(chartAttrs.xaxislinecolor, chartAttrs.axislinecolor, '#000000') }; yAxisConf = { isVertical: false, isReverse: false, isOpposit: false, outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisNamePadding: chartAttrs.yaxisnamepadding, axisValuePadding: chartAttrs.yaxisvaluespadding, axisNameFont: chartAttrs.yaxisnamefont, axisNameFontSize: chartAttrs.yaxisnamefontsize, axisNameFontColor: chartAttrs.yaxisnamefontcolor, axisNameFontBold: chartAttrs.yaxisnamefontbold, axisNameFontItalic: chartAttrs.yaxisnamefontitalic, axisNameBgColor: chartAttrs.yaxisnamebgcolor, axisNameBorderColor: chartAttrs.yaxisnamebordercolor, axisNameAlpha: chartAttrs.yaxisnamealpha, axisNameFontAlpha: chartAttrs.yaxisnamefontalpha, axisNameBgAlpha: chartAttrs.yaxisnamebgalpha, axisNameBorderAlpha: chartAttrs.yaxisnameborderalpha, axisNameBorderPadding: chartAttrs.yaxisnameborderpadding, axisNameBorderRadius: chartAttrs.yaxisnameborderradius, axisNameBorderThickness: chartAttrs.yaxisnameborderthickness, axisNameBorderDashed: chartAttrs.yaxisnameborderdashed, axisNameBorderDashLen: chartAttrs.yaxisnameborderdashlen, axisNameBorderDashGap: chartAttrs.yaxisnameborderdashgap, axisNameWidth: chartAttrs.yaxisnamewidth, useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, axisName: chartAttrs.yaxisname, divLineColor: (0, _lib.pluck)(chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.divlinealpha, is3D ? colorM.getColor('divLineAlpha3D') : colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.divlinedashgap, 2), showAlternateGridColor: (0, _lib.pluckNumber)(chartAttrs.showalternatevgridcolor, 1), alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatevgridcolor, colorM.getColor('altVGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatevgridalpha, colorM.getColor('altVGridAlpha')), numDivLines: chartAttrs.numdivlines, axisMinValue: chartAttrs.yaxisminvalue, axisMaxValue: chartAttrs.yaxismaxvalue, setAdaptiveMin: chartAttrs.setadaptiveymin, adjustDiv: chartAttrs.adjustdiv, labelStep: chartAttrs.yaxisvaluesstep, showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showyaxisvalues, chartAttrs.showyaxisvalue), showLimits: (0, _lib.pluckNumber)(chartAttrs.showyaxislimits, chartAttrs.showlimits, iapi.showLimits), showDivLineValues: (0, _lib.pluckNumber)(chartAttrs.showdivlinevalues, chartAttrs.showdivlinevalue), // showZeroPlane: chartAttrs.showzeroplane, zeroPlaneColor: chartAttrs.zeroplanecolor, zeroPlaneThickness: (0, _lib.pluckNumber)(chartAttrs.zeroplanethickness, chartAttrs.divlinethickness, 2), zeroPlaneAlpha: (0, _lib.pluckNumber)(chartAttrs.zeroplanealpha, chartAttrs.divlinealpha, chartConfig.zeroplanealpha), showZeroPlaneValue: chartAttrs.showzeroplanevalue, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, trendlineAlpha: chartAttrs.trendlinealpha, // Applicable only for bar as to change the behavior of scatter charts isTrendZone: 0, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, showAxisLine: is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showyaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, 0), axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.yaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.yaxislinealpha, chartAttrs.axislinealpha, 100), axisLineColor: (0, _lib.pluck)(chartAttrs.yaxislinecolor, chartAttrs.axislinecolor, '#000000'), numberFormatterFn: 'yAxis', showZeroPlaneOnTop: chartConfig.showzeroplaneontop, forceTrendBelow: !!chartConfig.is3D }; yAxisConf.vtrendlines = dataObj.trendlines; xAxisConf.trendlines = dataObj.vtrendlines; if (chartConfig.isstacked) { yAxisConf.isPercent = (0, _lib.pluckNumber)(chartConfig.stack100percent, 0); } return { xAxisConf: [xAxisConf], yAxisConf: [yAxisConf] }; } /** * This method first assigns the entire area of the chart to canvas. Then every component (for example toolbox, * caption etc) is asked to allocate its own space. Once every compoenent has had its space allocated, the canvas is * assigned the remaining space. */ function __spaceManager() { // @TODO marge _allocateSpace and _spacemanager var availableWidth, availableHeight, iapi = this, config = iapi.config, children = iapi.getChildren(), xAxis = children.yAxis && children.yAxis[0], yAxisArr = children.xAxis && children.xAxis || [], yAxis, POSITION_BOTTOM = _lib.preDefStr.POSITION_BOTTOM, legendPosition = config.legendposition, xDepth = config.xDepth, yDepth = config.yDepth, canvas = children.canvas[0], canvasBgDepth = config.canvasBgDepth, canvasBaseDepth = config.canvasBaseDepth, canvasBasePadding = config.canvasBasePadding, canvasBorderWidth = children.canvas[0].config.canvasBorderWidth, showRTValue = config.realTimeConfig && config.realTimeConfig.showRTValue, chartBorderWidth = config.borderWidth, canvasMarginTop = config.canvasMarginTop, canvasMarginBottom = config.canvasMarginBottom, canvasMarginLeft = config.canvasMarginLeft, canvasMarginRight = config.canvasMarginRight, minCanvasHeight = config.minCanvasHeight, minCanvasWidth = config.minCanvasWidth, minChartWidth = config.minChartWidth, minChartHeight = config.minChartHeight, height = config.height, width = config.width, diff, heightAdjust = false, widthAdjust = false, top, bottom, left, right, currentCanvasHeight, currentCanvasWidth, origCanvasTopMargin = config.origCanvasTopMargin, origCanvasBottomMargin = config.origCanvasBottomMargin, origCanvasLeftMargin = config.origCanvasLeftMargin, origCanvasRightMargin = config.origCanvasRightMargin, chartBorderHorizontal, chartBorderVertical, canvasBorderHorizontal, actionBarSpace, spaceForActionBar, canvasBorderVertical, yAxisSpaceAllocation, xAxisSpaceAllocation, sum; if (config.canvasWidth - 2 * chartBorderWidth < minChartWidth) { chartBorderVertical = (config.canvasWidth - minChartWidth) / 2; } if (config.canvasHeight - 2 * chartBorderWidth < minChartHeight) { chartBorderHorizontal = (config.canvasHeight - minChartHeight) / 2; } iapi._allocateSpace({ top: chartBorderHorizontal || chartBorderWidth, bottom: chartBorderHorizontal || chartBorderWidth, left: chartBorderVertical || chartBorderWidth, right: chartBorderVertical || chartBorderWidth }); yAxis = yAxisArr[0]; //* ***** Manage space availableWidth = config.availableWidth * 0.7; config.yAxisSpaceAllocation = yAxisSpaceAllocation = yAxis && yAxis.placeAxis(availableWidth); yAxis && iapi._allocateSpace(yAxisSpaceAllocation); spaceForActionBar = config.availableHeight * 0.225; actionBarSpace = iapi._manageActionBarSpace && iapi._manageActionBarSpace(spaceForActionBar) || {}; iapi._allocateSpace(actionBarSpace); // No space is allocated for legend drawing in single series charts iapi._manageLegendSpace && iapi._manageLegendSpace(); availableHeight = legendPosition === POSITION_BOTTOM ? config.availableHeight * 0.6 : config.availableWidth * 0.6; // space management for 3d canvas if (yDepth) { iapi._allocateSpace({ left: yDepth }); config.shift = xDepth + canvasBasePadding + canvasBaseDepth; } if (canvasBgDepth) { iapi._allocateSpace({ top: canvasBgDepth }); } if (config.canvasWidth - 2 * canvasBorderWidth < minCanvasWidth) { canvasBorderVertical = (config.canvasWidth - minCanvasWidth) / 2; } iapi._allocateSpace({ left: canvasBorderVertical || canvasBorderWidth, right: canvasBorderVertical || canvasBorderWidth }); // Check for minimun canvas width for applying canvas left and right margin. if (minCanvasWidth > width - canvasMarginLeft - canvasMarginRight) { widthAdjust = true; diff = config.canvasWidth - minCanvasWidth; sum = canvasMarginLeft + canvasMarginRight; canvasMarginLeft = config.canvasMarginLeft = diff * canvasMarginLeft / sum; canvasMarginRight = config.canvasMarginRight = diff * canvasMarginRight / sum; } // Calculating the left and right canvas margin. left = canvasMarginLeft > config.canvasLeft ? canvasMarginLeft - config.canvasLeft : 0; right = canvasMarginRight > width - config.canvasRight ? canvasMarginRight + config.canvasRight - width : 0; iapi._allocateSpace({ left: left, right: right }); iapi._allocateSpace({ left: canvasBaseDepth }); // Forcing canvas width to its minimum if (widthAdjust) { sum = origCanvasLeftMargin + origCanvasRightMargin; currentCanvasWidth = config.canvasWidth; if (currentCanvasWidth > minCanvasWidth) { diff = currentCanvasWidth - minCanvasWidth; left = diff * origCanvasLeftMargin / sum; right = diff * origCanvasRightMargin / sum; } iapi._allocateSpace({ left: left, right: right }); } config.actualCanvasMarginRight = right; config.actualCanvasMarginBottom = bottom; // a space manager that manages the space for the tools as well as the captions. iapi._manageChartMenuBar(availableHeight); availableHeight = config.availableHeight * 0.2; iapi._allocateSpace(iapi._getSumValueSpace(availableHeight)); availableHeight = config.availableHeight * 0.3; if (config.realtimeEnabled) { if (showRTValue) { iapi._allocateSpace(iapi._realTimeValuePositioning(availableHeight)); } else { iapi._hideRealTimeValue(); } } availableHeight = config.availableHeight * 0.6; config.xAxisSpaceAllocation = xAxisSpaceAllocation = xAxis && xAxis.placeAxis(availableHeight); xAxis && iapi._allocateSpace(xAxisSpaceAllocation); // alocate the space for scroll. availableHeight = config.availableHeight * 0.3; iapi._manageScrollerPosition && iapi._manageScrollerPosition(availableHeight); if (config.canvasHeight - 2 * canvasBorderWidth < minCanvasHeight) { canvasBorderHorizontal = (config.canvasHeight - minCanvasHeight) / 2; } iapi._allocateSpace({ top: canvasBorderHorizontal || canvasBorderWidth, bottom: canvasBorderHorizontal || canvasBorderWidth }); // Check for minimum canvas height for applying top and bottom margin. if (minCanvasHeight > height - canvasMarginTop - canvasMarginBottom) { heightAdjust = true; diff = config.canvasHeight - minCanvasHeight; sum = canvasMarginTop + canvasMarginBottom; canvasMarginTop = config.canvasMarginTop = diff * canvasMarginTop / sum; canvasMarginBottom = config.canvasMarginBottom = diff * canvasMarginBottom / sum; } // Allocate space for canvas margin only if the margin is less than the margin entered by the user. top = canvasMarginTop > config.canvasTop ? canvasMarginTop - config.canvasTop : 0; bottom = canvasMarginBottom > height - config.canvasBottom ? canvasMarginBottom + config.canvasBottom - height : 0; iapi._allocateSpace({ top: top, bottom: bottom }); // Forcing canvas height to its minimum if (heightAdjust) { sum = origCanvasTopMargin + origCanvasBottomMargin; currentCanvasHeight = config.canvasHeight; if (currentCanvasHeight > minCanvasHeight) { diff = currentCanvasHeight - minCanvasHeight; top = diff * origCanvasTopMargin / sum; bottom = diff * origCanvasBottomMargin / sum; } iapi._allocateSpace({ top: top, bottom: bottom }); } config.actualCanvasMarginTop = top; config.actualCanvasMarginLeft = left; canvas.setDimension({ top: config.canvasTop, left: config.canvasLeft, width: config.canvasWidth, height: config.canvasHeight }); } /** * This function is adjusting value padding depending upon data and axis labels and set dimention to axis */ function __postSpaceManagement() { var iapi = this, config = iapi.config, children = iapi.getChildren(), xAxis = children.xAxis && children.xAxis[0], yAxis = children.yAxis && children.yAxis[0], legend = children.legend && children.legend[0], xDepth = config.xDepth, canvasConfig = children.canvas[0].config, canvasBorderWidth = canvasConfig.canvasBorderWidth, canvasPadding = canvasConfig.canvasPadding, canvasPaddingLeft, math = Math, mathMax = math.max, canvasPaddingRight, canvasPaddingTop, canvasPaddingBottom; // function for adjusting value padding depending upon data and axis labels. yAxis && iapi._allocateXAxisLabelSpace(yAxis); canvasPaddingLeft = canvasConfig.canvasPaddingLeft; canvasPaddingRight = canvasConfig.canvasPaddingRight; canvasPaddingTop = canvasConfig.canvasPaddingTop; canvasPaddingBottom = canvasConfig.canvasPaddingBottom; yAxis && yAxis.setAxisDimention({ x: canvasConfig.canvasLeft + canvasPaddingLeft, y: canvasConfig.canvasTop + canvasConfig.canvasHeight + canvasBorderWidth, opposite: canvasConfig.canvasTop - canvasBorderWidth, axisLength: canvasConfig.canvasWidth - canvasPaddingLeft - canvasPaddingRight }); xAxis && xAxis.setAxisDimention({ x: canvasConfig.canvasLeft - (config.shift || 0) - canvasBorderWidth, y: canvasConfig.canvasTop + (xDepth || 0) + mathMax(canvasPaddingTop, canvasPadding), opposite: canvasConfig.canvasRight + canvasBorderWidth, axisLength: canvasConfig.canvasHeight - (xDepth || 0) - mathMax(canvasPaddingTop, canvasPadding) - mathMax(canvasPaddingBottom, canvasPadding) }); legend && legend.postSpaceManager(); iapi.allocateDimensionOfChartMenuBar(); } /** * This class is base class for multi series bar charts. */ var MSBarCartesian = function (_MSCartesian) { _inherits(MSBarCartesian, _MSCartesian); function MSBarCartesian() { _classCallCheck(this, MSBarCartesian); return _possibleConstructorReturn(this, _MSCartesian.apply(this, arguments)); } /** * Sets the name of the component * @return {string} name */ MSBarCartesian.prototype.getName = function getName() { return 'MSBarCartesian'; }; /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSBarCartesian.getName = function getName() { return 'MSBarCartesian'; }; /** * parse defualt configuration of the chart */ MSBarCartesian.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSCartesian.prototype.__setDefaultConfig.call(this); this.config.enablemousetracking = true; }; /** * This method parse all the attributes which are associated with axis compoenents. * So that axis compoenents can be configured * @return { Object } contains axes config */ MSBarCartesian.prototype._feedAxesRawData = function _feedAxesRawData() { return __feedAxesRawData.call(this); }; /** * This method first assigns the entire area of the chart to canvas. Then every component (for example toolbox, * caption etc) is asked to allocate its own space. Once every compoenent has had its space allocated, the canvas is * assigned the remaining space. */ MSBarCartesian.prototype._spaceManager = function _spaceManager() { __spaceManager.call(this); }; /** * This function is adjusting value padding depending upon data and axis labels and set dimention to axis */ MSBarCartesian.prototype._postSpaceManagement = function _postSpaceManagement() { __postSpaceManagement.call(this); }; /** * This method return the dataset definations for this charts * @return {Object} dataset class for bar2d */ MSBarCartesian.prototype.getDSdef = function getDSdef() { return _column2['default']; }; /** * This method return the dataset-group definations for this charts. Here return value is undefined */ MSBarCartesian.prototype.getDSGroupdef = function getDSGroupdef() { // this fn overrides }; return MSBarCartesian; }(_mscartesian2['default']); exports.__feedAxesRawData = __feedAxesRawData; exports.__spaceManager = __spaceManager; exports.__postSpaceManagement = __postSpaceManagement; exports['default'] = MSBarCartesian; /***/ }), /* 459 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _cartesian = __webpack_require__(360); var _cartesian2 = _interopRequireDefault(_cartesian); var _legendSpacemanager = __webpack_require__(460); var _multiseriesDataset = __webpack_require__(461); var _multiseriesDataset2 = _interopRequireDefault(_multiseriesDataset); var _legend = __webpack_require__(462); var _legend2 = _interopRequireDefault(_legend); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * Base class for all cartesian charts and who depend on this class * Its not an standalone chart * @type {class} */ var MSCartesian = function (_Cartesian) { _inherits(MSCartesian, _Cartesian); /** * constructor fn */ function MSCartesian() { _classCallCheck(this, MSCartesian); var _this = _possibleConstructorReturn(this, _Cartesian.call(this)); _this.registerFactory('dataset', _multiseriesDataset2['default'], ['vCanvas']); _this.registerFactory('legend', _legend2['default']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSCartesian.getName = function getName() { return 'MSCartesian'; }; /** * Sets the name of the component * @return {string} name */ MSCartesian.prototype.getName = function getName() { return 'MSCartesian'; }; /** * Returns the type of the component * * @return {string} The type of the component */ MSCartesian.prototype.getType = function getType() { return 'chartAPI'; }; /** * function to create chart level containers */ MSCartesian.prototype._createLayers = function _createLayers() { _Cartesian.prototype._createLayers.call(this); var animationManager = this.getFromEnv('animationManager'); !this.getChildContainer('legendGroup') && this.addChildContainer('legendGroup', animationManager.setAnimation({ el: 'group', attr: { name: 'legend' }, component: this, container: this.getContainer('parentgroup'), label: 'group' })); }; /** * function to calculate and allote space for legend */ MSCartesian.prototype._manageLegendSpace = function _manageLegendSpace() { _legendSpacemanager._manageLegendSpace.call(this); }; /** * function to calculate and allote space for gradient legend * @param {number} allottedSpace alloted space for gradient legend * @return {Object} calculated dimension */ MSCartesian.prototype.manageGradientLegendSpace = function manageGradientLegendSpace(allottedSpace) { return _legendSpacemanager.manageGradientLegendSpace.call(this, allottedSpace); }; return MSCartesian; }(_cartesian2['default']); exports['default'] = MSCartesian; /***/ }), /* 460 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.manageGradientLegendSpace = exports._manageLegendSpace = undefined; var _lib = __webpack_require__(125); /** * function to calculate and allote space for legend */ function _manageLegendSpace() { var iapi = this, config = iapi.config, legend = iapi.getChildren('legend') && iapi.getChildren('legend')[0], gradientLegend = iapi.getChildren('gLegend') && iapi.getChildren('gLegend')[0], conf, colorRangeObj = iapi.getFromEnv('dataSource').colorrange, hasLegend = config.hasLegend, spaceTakenByLegend = {}, hasGradientLegend = iapi.hasGradientLegend, legendPosition, allottedSpace, factor, chartAttr = iapi.getFromEnv('dataSource').chart, mapByCategory = (0, _lib.pluckNumber)(chartAttr.mapbycategory, 0), isGradient = hasGradientLegend && colorRangeObj && (0, _lib.pluckNumber)(colorRangeObj.gradient); // Check if jsonData has colorrange if (isGradient && !mapByCategory) { conf = gradientLegend.conf; hasGradientLegend = true; config.gLegendEnabled = true; factor = 0.5; legendPosition = conf.legendPosition; } else { conf = legend && legend.config; hasGradientLegend = false; config.gLegendEnabled = false; legendPosition = conf && conf.legendPos; factor = legendPosition === _lib.POSITION_RIGHT ? 0.8 : 0.4; } if (legendPosition === _lib.POSITION_RIGHT) { allottedSpace = config.availableWidth * factor; } else { allottedSpace = config.availableHeight * factor; } if (hasGradientLegend) { spaceTakenByLegend = iapi.manageGradientLegendSpace(allottedSpace); } else { if (hasLegend !== false && legend && !legend.getState('removed')) { spaceTakenByLegend = legend && legend._manageLegendPosition(allottedSpace); } } iapi._allocateSpace({ bottom: spaceTakenByLegend && spaceTakenByLegend.bottom || 0, right: spaceTakenByLegend && spaceTakenByLegend.right || 0 }); } /** * Calculates the dimension required by gradient legend * @param {Object} allottedSpace Allowed space for Gradient legend component * @return {Object} Dimension of space taken (width, height) */ function manageGradientLegendSpace(allottedSpace) { var iapi = this, config = iapi.config, gradientLegend = iapi.getFromEnv('gLegend'), conf = gradientLegend && gradientLegend.conf, legendPosition, returnDimension, gLegendPadding, spaceUsed; config.gLegendPadding = (0, _lib.pluckNumber)(iapi.getFromEnv('chart-attrib').legendpadding, 10); gLegendPadding = Math.min(config.gLegendPadding, 0.5 * allottedSpace); if (conf) { legendPosition = conf.legendPosition; spaceUsed = gradientLegend.getLogicalSpace(allottedSpace); if (legendPosition === _lib.POSITION_BOTTOM) { returnDimension = { bottom: (spaceUsed.height || 0) + gLegendPadding }; } else { returnDimension = { right: (spaceUsed.width || 0) + gLegendPadding }; } } else { returnDimension = { bottom: 0, right: 0 }; } return returnDimension; } exports._manageLegendSpace = _manageLegendSpace; exports.manageGradientLegendSpace = manageGradientLegendSpace; /***/ }), /* 461 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var jsonData = chart.getFromEnv('dataSource'), datasetsJSON = jsonData.dataset, children = chart.getChildren(), canvas = children.canvas[0], vCanvas = void 0, datasetParent = vCanvas = canvas.getChildren('vCanvas')[0], DSClass = void 0, MultiSeriesManager = void 0, dsType = chart.config.defaultDatasetType || '', groupManager = void 0; if (!datasetsJSON) { chart.setChartMessage(); return; } MultiSeriesManager = chart.getDSGroupdef(); if (MultiSeriesManager) { (0, _lib.componentFactory)(vCanvas, MultiSeriesManager, 'datasetGroup_' + dsType, 1, [datasetsJSON]); groupManager = vCanvas.getChildren('datasetGroup_' + dsType); } groupManager && (datasetParent = groupManager[0]); DSClass = chart.getDSdef(); (0, _lib.datasetFactory)(datasetParent, DSClass, 'dataset', datasetsJSON.length, datasetsJSON); }; var _lib = __webpack_require__(125); /***/ }), /* 462 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var legend = void 0; (0, _lib.componentFactory)(chart, _discrete2['default'], 'legend'); legend = chart.getChildren('legend')[0]; legend.configure(); chart.addToEnv('legend', legend); if (!chart.config.showLegend) { legend.remove(); } }; var _lib = __webpack_require__(125); var _discrete = __webpack_require__(463); var _discrete2 = _interopRequireDefault(_discrete); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 463 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); var _legendItem = __webpack_require__(464); var _legendItem2 = _interopRequireDefault(_legendItem); var _dependencyManager = __webpack_require__(132); var _toolbox = __webpack_require__(228); var _index = __webpack_require__(466); var _index2 = _interopRequireDefault(_index); var _schedular = __webpack_require__(136); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, TEXT_ANCHOR_MAP = { left: _lib.POSITION_START, right: _lib.POSITION_END, center: _lib.POSITION_MIDDLE }, // preDefStr = lib.preDefStr, // R = lib.Raphael, math = Math, mathMin = math.min, mathMax = math.max, mathFloor = math.floor, mathCeil = math.ceil, COMMA = ',', NONE = 'none', NORMAL = _lib.preDefStr.NORMAL, BOLD = _lib.preDefStr.BOLD, noneStr = _lib.preDefStr.noneStr, styleValueMap = { fontWeight: { '1': BOLD, '0': NORMAL }, fontStyle: { '1': 'italic', '0': NORMAL }, textDecoration: { '1': 'underline', '0': noneStr } }, handlers = function handlers(legend) { var dragInitX = void 0, dragInitY = void 0; return { 'dragstart': function dragstart() { dragInitX = legend.config.xL || legend.config.xPos; dragInitY = legend.config.yL || legend.config.yPos; }, 'dragmove': function dragmove(e) { var dx = e.originalEvent.data[0], dy = e.originalEvent.data[1], config = legend.config, chartConfig = legend.getFromEnv('chartConfig'), translationLimit = (config.borderWidth || 0 * 0.5) + 2, dragOffsetX = void 0, dragOffsetY = void 0; dragOffsetX = mathMin(mathMax(dragInitX + dx, translationLimit), chartConfig.width - config.width - translationLimit); dragOffsetY = mathMin(mathMax(dragInitY + dy, translationLimit), chartConfig.height - config.height - translationLimit); config.xPos = config.xL = dragOffsetX; config.yPos = config.yL = dragOffsetY; legend.addJob('draw', legend.dragDraw, _schedular.priorityList && _schedular.priorityList.draw); } }; }; (0, _dependencyManager.addDep)({ name: 'legendAnimation', type: 'animationRule', extension: _index2['default'] }); /** * Legend class used for legend component of chart. */ var Legend = function (_ComponentInterface) { _inherits(Legend, _ComponentInterface); /** * Creates an instance of Legend. * @memberof Legend */ function Legend() { _classCallCheck(this, Legend); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); var legend = _this; legend._stateCosmetics = {}; legend._legendState = []; legend.dragDraw = function () { legend.draw(); }; legend.drawScroll = function () { legend.createItemGroup(); }; legend.config.handlers = handlers(legend); return _this; } /** * This function creates the legend-item * @param {Object} owner the owner(who is creating it) of the legend-item * @return {string} the legenditem id */ Legend.prototype.createItem = function createItem(owner) { var legend = this, legendItem; legendItem = new _legendItem2['default'](); legend.attachChild(legendItem, 'legendItem'); // Link the owner(who is creating the legend item) with the legend-item for easy access legendItem.setLinkedItem('owner', owner); // add the listeners for hovered effect. legendItem.addEventListener('mouseover', function () { legendItem.setLegendState('hover', true); }); legendItem.addEventListener('mouseout', function () { legendItem.removeLegendState('hover'); }); return legendItem.getId(); }; Legend.prototype.getItem = function getItem(id) { var legend = this, items = legend.getChildren().legendItem; if (id !== UNDEF) { if (items) { for (var i = 0; i < items.length; i++) { if (items[i].getId() === id) { return items[i]; } } } } else { return false; } }; /** * Method that sorts and returns the legend items according to their dataset index */ Legend.prototype.getSortedLegendItems = function getSortedLegendItems() { var legend = this, items = legend.getChildren('legendItem') || [], reverselegend = legend.config.reverselegend, map = {}, sortedItems = [], i = void 0, len = void 0; for (i = 0, len = items.length; i < len; i++) { // if index is not found then loop index is added to the length to make sure no two indices becomes same if (items[i].config.index === UNDEF) { map[len + i] = items[i]; } else { map[items[i].config.index] = items[i]; } } Object.keys(map).sort(function (index1, index2) { // sort in descending order if (reverselegend) { return index2 - index1; } // sort in ascending order return index1 - index2; }).forEach(function (index) { // after sorting and reversing(if needed) finally push the legend items linked with the indices to an array sortedItems.push(map[index]); }); return sortedItems; }; Legend.prototype.disposeItem = function disposeItem(id) { var legend = this, legendItem = legend.getItem(id); legendItem && legendItem.remove(); }; /** * Sets the name of the component * @return {string} name */ Legend.prototype.getName = function getName() { return 'legend'; }; /** * Sets the type of the component * @return {string} type */ Legend.prototype.getType = function getType() { return 'legend'; }; Legend.prototype.__setDefaultConfig = function __setDefaultConfig() { _ComponentInterface.prototype.__setDefaultConfig.call(this); var config = this.config; config.enabled = true; config.symbolWidth = 12; config.borderRadius = 1; config.lastScrollPos = 0; config.oriSymbolPadding = 3; config.textPadding = 4; config.scrollY = 0; config.backgroundColor = '#FFFFFF'; config.initialItemX = 0; config.title = { text: _lib.BLANKSTRING, x: 0, y: 0, padding: 2 }; config.scroll = {}; config.itemStyle = {}; }; Legend.prototype.createLegendGroup = function createLegendGroup() { var legend = this, config = legend.config, chart = legend.getFromEnv('chart'), chartConfig = chart.config, animationManager = legend.getFromEnv('animationManager'), translationLimit = (config.borderWidth || 0) * 0.5 + 2, legendGroup = void 0, legendGroupCheck = legend.getContainer('legendGroup'); config.xL && (config.xL = mathMin(mathMax(config.xL, translationLimit), chartConfig.width - config.width - translationLimit)); config.yL && (config.yL = mathMin(mathMax(config.yL, translationLimit), chartConfig.height - config.height - translationLimit)); legendGroup = animationManager.setAnimation({ el: legendGroupCheck || 'group', attr: { 'name': 'legendGroup', 'transform': ['T', config.xL || config.xPos, config.yL || config.yPos] }, container: chart.getChildContainer('legendGroup'), component: legend }); if (!legendGroupCheck) { legend.addContainer('legendGroup', legendGroup); } }; Legend.prototype.draw = function draw() { this.createLegendGroup(); this.drawLegendBox(); this.createItemGroup(); this.drawCaption(); this.createScrollGroup(); this.decideScroll(); }; // method that creates and hides legend scroll Legend.prototype.decideScroll = function decideScroll() { var legend = this, legendConf = legend.config, scrollEnabled = legendConf.scroll.enabled; if (scrollEnabled) { this.createScrollBar(); } else if (legendConf.hasScroll) { legend.getChildren('legendScrollBar')[0].remove(); legendConf.hasScroll = false; } }; Legend.prototype.createItemGroup = function createItemGroup() { var legend = this, animationManager = legend.getFromEnv('animationManager'), legendGroup = legend.getContainer('legendGroup'), itemGroup, itemGroupCheck = legend.getChildContainer('itemGroup'), padding = (0, _lib.pluckNumber)(legend.config.padding, 4), halfPad = padding * 0.5, clipSTR1 = '0,', clipH = Math.max(legend.config.height - padding, 0), clipSTR2 = COMMA + legend.config.width + COMMA + clipH; // create itemGroup itemGroup = animationManager.setAnimation({ el: itemGroupCheck || 'group', attr: { name: 'item', transform: ['T', 0, legend.config.scrollY || 0] }, container: legendGroup, component: legend }); if (!itemGroupCheck) { legend.addChildContainer('itemGroup', itemGroup); } if (legend.config.scroll.enabled) { itemGroup.attr({ 'clip-rect': clipSTR1 + halfPad + clipSTR2 }); } else { itemGroup.attr({ 'clip-rect': null }); } return itemGroup; }; /** * creates group for scroll */ Legend.prototype.createScrollGroup = function createScrollGroup() { var legend = this, animationManager = legend.getFromEnv('animationManager'), // scrollGroup, scrollGroupCheck = legend.getChildContainer('scrollGroup'), legendGroup = legend.getContainer('legendGroup'); if (legend.config.scroll.enabled && !legend.getGraphicalElement('scrollerContainer')) { // scrollGroup = animationManager.setAnimation({ // el: scrollGroupCheck || 'group', // attr: { // 'name': 'scrollGroup' // }, // container: legendGroup, // component: legend, // label: 'scroller' // }); // if (!scrollGroupCheck) { // legend.addChildContainer('scrollGroup', scrollGroup); // legend.config.scrollerContainer = scrollGroup; // } legend.addGraphicalElement('scrollerContainer', animationManager.setAnimation({ el: scrollGroupCheck || 'group', attr: { 'name': 'scrollGroup' }, container: legendGroup, component: legend, label: 'scroller' })); } }; // method that creates legend scroll Legend.prototype.createScrollBar = function createScrollBar() { var legend = this, config = legend.config, scrollItem, chartAttr = legend.getFromEnv('chart-attrib'), legendScrollBar = legend.getChildren('legendScrollBar') && legend.getChildren('legendScrollBar')[0], // tb = legend.getFromEnv('toolbox'), // toolBoxApi = legend.getFromEnv('toolBoxAPI'), // Scroller = toolBoxApi && toolBoxApi.Scroller, borderWidth = config.borderWidth || 0, semiBorder = borderWidth * 0.5, padding = (0, _lib.pluckNumber)(config.padding, 4), halfPad = padding * 0.5, scrollConfig, scrollerWidth = 10, clipH, width = config.width, height = config.height, x, y, h; scrollItem = { conf: { isHorizontal: false }, handler: { 'scroll': function scroll(pos) { config.lastScrollPos = pos; config.scrollY = (clipH - config.totalHeight) * pos; // add job for scroll draw legend.addJob('scrollDraw', legend.drawScroll, _schedular.priorityList && _schedular.priorityList.draw); }, 'mousedown': function mousedown(e) { e.preventDefault(); e.stopPropagation(); } } }; if (chartAttr.legendscrollbgcolor) { scrollItem.conf.color = (0, _lib.convertColor)(chartAttr.legendscrollbgcolor); } if (!legendScrollBar) { legendScrollBar = legend.attachChild(new _toolbox.Scroller(), 'legendScrollBar'); this.config.hasScroll = true; } legendScrollBar.configure(scrollItem.conf); legendScrollBar.attachEventHandlers(scrollItem.handler); scrollConfig = legendScrollBar.config; clipH = Math.max(height - padding, 0); x = width - scrollerWidth + halfPad - borderWidth; y = semiBorder; h = Math.max(height - borderWidth, 0); scrollConfig.scrollRatio = (clipH + padding) / config.totalHeight; scrollConfig.startPercent = 0; scrollConfig.scrollPosition = config.lastScrollPos; scrollConfig.parentLayer = legend.getChildContainer('scrollGroup'); legendScrollBar.setDimension({ x: x, y: y, height: h }); }; Legend.prototype.drawCaption = function drawCaption() { var legend = this, itemGroup = legend.getChildContainer('itemGroup'), caption = legend.getGraphicalElement('caption'), animationManager = this.getFromEnv('animationManager'), config = this.config, attrObj, titleStyle, captionX, padding = (0, _lib.pluckNumber)(config.padding, 4), captionCss, scrollEnabled = config.scroll.enabled, scrollerWidth = 10, width = config.width; if (config.title && config.title.text !== _lib.BLANKSTRING && config.validLegendItem) { switch (config.title.align) { case _lib.POSITION_START: captionX = padding; break; case _lib.POSITION_END: captionX = width - padding - (scrollEnabled ? scrollerWidth : 0); break; default: captionX = width * 0.5; } titleStyle = config.title.style; attrObj = { text: config.title.text, title: config.title.originalText || _lib.BLANKSTRING, x: captionX, y: padding, fill: config.title.style.color, direction: config.textDirection, 'line-height': titleStyle.lineHeight, 'vertical-align': _lib.POSITION_TOP, 'text-anchor': config.title.align, opacity: 1 }; captionCss = { 'font-weight': titleStyle.fontWeight, 'font-style': titleStyle.fontStyle, 'font-family': titleStyle.fontFamily, 'font-size': titleStyle.fontSize }; caption && caption.show(); if (!caption) { caption = animationManager.setAnimation({ el: 'text', attr: attrObj, component: legend, container: itemGroup }); caption = this.addGraphicalElement('caption', caption); caption.css(captionCss); } else { animationManager.setAnimation({ el: caption, attr: attrObj, component: legend }); } legend.getFromEnv('toolTipController').enableToolTip(caption, config.title.originalText); } else { if (caption) { animationManager.setAnimation({ el: caption, component: legend, doNotRemove: true, callback: function callback() { caption.hide(); } }); } } }; Legend.prototype.drawLegendBox = function drawLegendBox() { var legend = this, animationManager = this.getFromEnv('animationManager'), config = legend.config, box, legendGroup = legend.getContainer('legendGroup'), width = config.width, boxCheck = legend.getGraphicalElement('box'), height = config.height, r = config.borderRadius, backgroundColor = config.backgroundColor, borderColor = config.borderColor, borderAlpha = config.borderAlpha, backgroundAlpha = config.backgroundAlpha, borderWidth = config.borderWidth || 0; box = animationManager.setAnimation({ el: boxCheck || 'rect', attr: { x: 0, y: 0, width: width, height: height, r: r, stroke: borderColor, 'stroke-width': borderWidth, fill: backgroundColor || NONE, 'stroke-opacity': borderAlpha / 100, 'fill-opacity': backgroundAlpha / 100, cursor: config.legendAllowDrag ? 'move' : 'default' }, container: legendGroup, component: legend, label: 'legendGroup' }); if (!boxCheck) { legend.addGraphicalElement('box', box); box.shadow(config.shadow); } return box; }; // returns the dimensions of the legend box Legend.prototype.getPosition = function getPosition() { var legend = this, chart = legend.getFromEnv('chart'), chartConfig = chart.config, xPos, yPos, config = legend.config, canvasBottom = chartConfig.height - chartConfig.canvasBottom, canvasLeft = chartConfig.canvasLeft, canvasWidth = chartConfig.canvasWidth, marginLeft = config.chartMarginLeft || 0, marginRight = config.chartMarginRight || 0, marginBottom = config.chartMarginBottom || 0, actionBarHeight = chartConfig.actionBarHeight || 0, canvasMarginLeft = config.actualCanvasMarginLeft || 0, canvasMarginBottom = chartConfig.actualCanvasMarginBottom || 0, canvasMarginRight = chartConfig.actualCanvasMarginRight || 0, alignLegendWithCanvas = config.alignLegendWithCanvas, chartHeight = chartConfig.height, canvasTop = chartConfig.canvasTop, width = config.width || 0, height = config.height || 0, chartBorderWidth = chartConfig.borderWidth, oriCanvasLeft = chartConfig.oriCanvasLeft, oriCanvasTop = chartConfig.oriTopSpace, oriCanvasBottom = chartConfig.oriBottomSpace, topSpace = 0, bottomSpace = 0, xLeft, spaceLeftByChart, spaceRightLeft, borderWidth = config.borderWidth || 0, isVertical, legendPos = config.legendPos; if (legendPos === _lib.POSITION_RIGHT) { config.align = _lib.POSITION_RIGHT; config.verticalAlign = _lib.POSITION_MIDDLE; isVertical = config.layout = 'vertical'; } if (isVertical) { xPos = chartConfig.width - marginRight - canvasMarginRight - width - chartBorderWidth; topSpace = (0, _lib.pluckNumber)(oriCanvasTop, canvasTop); bottomSpace = (0, _lib.pluckNumber)(oriCanvasBottom, canvasBottom); yPos = topSpace + (chartHeight - bottomSpace - topSpace - height) * 0.5 + (config.y || 0); } else { spaceLeftByChart = chartConfig.width - (marginLeft + canvasMarginLeft + (marginRight + canvasMarginRight)); spaceRightLeft = alignLegendWithCanvas ? canvasWidth - width : spaceLeftByChart - width; xLeft = !alignLegendWithCanvas ? marginLeft + canvasMarginLeft : (0, _lib.pluckNumber)(oriCanvasLeft, canvasLeft); xPos = xLeft + spaceRightLeft / 2; yPos = chartHeight - height - canvasMarginBottom - marginBottom - actionBarHeight; } return (0, _lib.crispBound)(xPos, yPos, width, height, borderWidth); }; Legend.prototype.setTranslation = function setTranslation(x, y) { var legend = this, config = legend.config; config._translateX = x; config._translateY = y; config.translate = 't' + x + ',' + y; }; /** * Allocates position to legend for drawing macros * * @memberof Legend */ Legend.prototype.allocatePosition = function allocatePosition() { var legend = this, legendConfig = legend.config, dim; // if translation is already available then use those values. if (legendConfig.translate) { // get crisped values. dim = (0, _lib.crispBound)(legendConfig._translateX, legendConfig._translateY, legendConfig.width, legendConfig.height, legendConfig.borderWidth); } else { dim = legend.getPosition(); } legendConfig.xPos = dim.x; legendConfig.yPos = dim.y; legendConfig.width = dim.width; legendConfig.height = dim.height; }; Legend.prototype._manageLegendPosition = function _manageLegendPosition(allottedSpace) { var legend = this, config = legend.config, legendPosition = config.legendPos, dimensions; // set the default paddings of legend before space management as on resize it doesn't go through // its configuration cycle to set its default paddings. config.padding = 4; config.textPadding = 4; if (legendPosition === _lib.POSITION_RIGHT) { dimensions = legend._placeLegendBlockRight(allottedSpace); } else { dimensions = legend._placeLegendBlockBottom(allottedSpace); } return dimensions; }; Legend.prototype.setDimension = function setDimension(dim) { var legend = this, config = this.config, itemArr = legend.getSortedLegendItems(), len = itemArr.length, availableWidth = dim.width, availableHeight = dim.height, allowedMaxHeight = availableHeight * 2, itemConfig = void 0, userConfig = void 0, name = void 0, item = void 0, maxWidth = 0, totalWidth = 0, totalNumber = 0, averageWidth = 0, perItemWidth = 0, maxHeight = 0, legendCaptionHeight = 0, maxMarkerGutter = 0, tempTableStructure = [], singleRowLegend = false, padding = config.padding, textPadding = config.textPadding, SmartLabel = legend.getFromEnv('smartLabel'), itemStyle = legend.getStateCosmetics('default'), itemFontSize = parseInt(itemStyle.text['font-size'], 10) || 10, legendX = 0, current = 0, nonItemWidth = void 0, rowHeight = void 0, usedHeight = void 0, textWidth = void 0, numberOfCell = void 0, tempCurrent = void 0, legendCaption = config.title, captionPadding = legendCaption.padding, captionWidth = void 0, minimiseWrappingInLegend = config.minimiseWrappingInLegend, legendPadding = config.legendPadding, legendScale = config.legendScale, alignLegendWithCanvas = config.alignLegendWithCanvas, legendnumcolumns = config.numColumns, symbolPadding = config.oriSymbolPadding, legendHeight = void 0, symbolWidthSpace = void 0, dimensions = void 0, legendLineHeight = void 0, i = void 0, j = void 0, colIndex = void 0, rowIndex = void 0, numRows = void 0, validLegendItem = void 0, smartText = void 0, scroll = void 0, originalAvailableWidth = availableWidth, nonTextElemWidth = void 0; dimensions = { width: 2 * padding, height: 2 * padding }; symbolWidthSpace = itemFontSize + 1; if (symbolWidthSpace <= 0) { symbolWidthSpace = 1; } availableWidth -= 2 * padding; symbolWidthSpace *= legendScale; symbolPadding *= legendScale; symbolWidthSpace = mathMin(symbolWidthSpace, availableWidth); if (symbolWidthSpace <= 0) { symbolPadding = symbolWidthSpace = 0; } config.symbolWidth = symbolWidthSpace; config.textPadding = 4; config.legendHeight = legendHeight = symbolWidthSpace + 2 * symbolPadding; config.rowHeight = rowHeight = mathMax(parseInt(itemStyle.text['line-height'], 10) || 12, legendHeight); nonItemWidth = textPadding + symbolPadding + padding; SmartLabel.setStyle((0, _lib.extend2)({}, itemStyle.text)); legendLineHeight = SmartLabel.getOriSize(_lib.TESTSTR).height; usedHeight = legendPadding + config.borderWidth / 2 + 1; usedHeight = mathMin(usedHeight, availableHeight - legendLineHeight - 8); legendPadding = rowHeight * 0.05; config.initialItemY = 0; config.initialItemX = 0; for (i = 0; i < len; i += 1) { item = itemArr[i]; itemConfig = item.config || (item.config = {}); userConfig = itemConfig; name = itemConfig.name = (0, _lib.parseUnsafeString)(userConfig.label); if (name === _lib.BLANKSTRING || userConfig.enabled === 0 || userConfig.enabled === false || item.getState('removed')) { itemConfig.enabled = 0; continue; } else { itemConfig.enabled = 1; } totalNumber += 1; validLegendItem = true; smartText = SmartLabel.getOriSize(name); maxWidth = mathMax(maxWidth, smartText.width); /* * We also need to get the maximum height required for rendering all the * legend items. This will be helpful to vertically align all the legend * items in case of single row legend. * In case of { br } or
in series name the row height * can increase and that need to be accommodated */ maxHeight = mathMax(maxHeight, mathMin(smartText.height, allowedMaxHeight)); totalWidth += smartText.width; } config.validLegendItem = validLegendItem; averageWidth = totalWidth / totalNumber; nonTextElemWidth = legendHeight + legendPadding + textPadding + symbolPadding + 2 * padding; totalWidth += nonTextElemWidth * totalNumber; config.x = !alignLegendWithCanvas && totalWidth > originalAvailableWidth ? 0 : config.x; if (validLegendItem) { averageWidth += nonTextElemWidth; maxWidth += nonTextElemWidth; if (legendnumcolumns > 0 && totalNumber < legendnumcolumns) { legendnumcolumns = totalNumber; } // if there has space to show all legends in one column if (totalWidth <= availableWidth && (legendnumcolumns <= 0 || legendnumcolumns === totalNumber)) { legendnumcolumns = totalNumber; perItemWidth = averageWidth = totalWidth / totalNumber; singleRowLegend = true; // Here we need to check whether row height need to accomodate a any large texts if (maxHeight > rowHeight) { // gutter for marker has to be uniform and should not depend // on different text heights. maxMarkerGutter = (maxHeight - rowHeight) / 2; rowHeight = maxHeight; } } else if (legendnumcolumns > 0 && (perItemWidth = availableWidth / legendnumcolumns) > averageWidth) { // if valid numcolumn[there has enough item for legendNumColumns, every item getting minimum space] if (perItemWidth > maxWidth) { perItemWidth = maxWidth; } } else if (availableWidth > maxWidth && (minimiseWrappingInLegend || averageWidth * 1.5 > maxWidth)) { // try to minimize wrapping legendnumcolumns = mathFloor(availableWidth / maxWidth); if (totalNumber < legendnumcolumns) { legendnumcolumns = totalNumber; } perItemWidth = maxWidth; } else if (availableWidth >= 2 * averageWidth) { // there has space for atlest 2 column // The number of columns each of width as the averageWidth legendnumcolumns = mathFloor(availableWidth / averageWidth); if (totalNumber < legendnumcolumns) { legendnumcolumns = totalNumber; } // Provide best width space, which is greater than average width, generally // (for numColumns is found above via mathFloor ()) perItemWidth = mathFloor(availableWidth / legendnumcolumns); if (perItemWidth > maxWidth) { perItemWidth = maxWidth; } } else { // else only 1 column per row legendnumcolumns = 1; perItemWidth = availableWidth; } config.itemWidth = perItemWidth; /* * Its always best to round off to the next whole number in case of * widths used for text wrapping. As there are padding available. It will * correctly wraps the text only if more than 1 px of space is required */ textWidth = mathCeil(perItemWidth - nonTextElemWidth); if (textWidth < 0) { symbolPadding = textWidth = textPadding = 0; } config.symbolPadding = symbolPadding; config.textPadding = textPadding; config.width = perItemWidth * legendnumcolumns - legendPadding; // Legend Caption space management if (legendCaption.oriText !== _lib.BLANKSTRING) { SmartLabel.setStyle(legendCaption.style); smartText = SmartLabel.getSmartText(legendCaption.oriText, availableWidth, allowedMaxHeight); legendCaption.text = smartText.text; smartText.tooltext && (legendCaption.originalText = smartText.tooltext); captionWidth = smartText.width + 2 * padding; // if the caption width has gretter width if (config.width < captionWidth) { config.initialItemX = (captionWidth - config.width) / 2; config.width = captionWidth; } config.initialItemY = legendCaptionHeight = smartText.height + captionPadding; } SmartLabel.setStyle((0, _lib.extend2)({}, itemStyle.text)); for (i = 0; i < len; i += 1) { item = itemArr[i]; itemConfig = item.config; if (itemConfig.enabled !== 0) { if (textWidth === 0) { tempTableStructure[current] = true; itemConfig.name = _lib.BLANKSTRING; j = 1; rowIndex = parseInt(current / legendnumcolumns, 10); colIndex = current % legendnumcolumns; itemConfig._legendX = colIndex * perItemWidth; itemConfig._legendY = rowIndex * rowHeight + 2 * padding; itemConfig._legendH = j * rowHeight; itemConfig._totalWidth = symbolWidthSpace + symbolPadding; } if (singleRowLegend) { smartText = SmartLabel.getOriSize(itemConfig.name); if (smartText.height < rowHeight) { itemConfig._legendTestY = (rowHeight - smartText.height) / 2; } itemConfig._markerYGutter = maxMarkerGutter; itemConfig._legendX = legendX; itemConfig._legendY = 2 * padding; itemConfig._legendH = rowHeight; itemConfig._totalWidth = symbolWidthSpace + nonItemWidth + smartText.width; legendX += smartText.width + nonTextElemWidth; } else { smartText = SmartLabel.getSmartText(itemConfig.name, textWidth, allowedMaxHeight); itemConfig.name = smartText.text; smartText.tooltext && (itemConfig.originalText = smartText.tooltext); while (tempTableStructure[current] === true) { current += 1; } numberOfCell = smartText.height / rowHeight; tempCurrent = current; for (j = 0; j < numberOfCell; j += 1, tempCurrent += legendnumcolumns) { tempTableStructure[tempCurrent] = true; } if (smartText.height < rowHeight) { itemConfig._legendTestY = (rowHeight - smartText.height) / 2; } rowIndex = parseInt(current / legendnumcolumns, 10); colIndex = current % legendnumcolumns; itemConfig._legendX = colIndex * perItemWidth; itemConfig._legendY = rowIndex * rowHeight + 2 * padding; itemConfig._legendH = j * rowHeight; itemConfig._totalWidth = symbolWidthSpace + nonItemWidth + smartText.width; } current++; } } numRows = singleRowLegend ? 1 : mathCeil(tempTableStructure.length / legendnumcolumns); dimensions.height += numRows * rowHeight + legendCaptionHeight; config.height = config.totalHeight = dimensions.height; config.rowHeight = rowHeight; config.legendNumColumns = legendnumcolumns; if (config.height - 2 * symbolPadding > availableHeight) { config.height = availableHeight; scroll = config.scroll || (config.scroll = {}); scroll.enabled = true; scroll.flatScrollBars = config.flatScrollBars; scroll.scrollBar3DLighting = config.scrollBar3DLighting; config.width = config.width + 12 > availableWidth ? config.width : config.width + 12; } else { config.scroll.enabled = false; } usedHeight += config.height; config.isActive = true; config.enabled = true; } else { config.enabled = false; config.width = 0; usedHeight = 0; } return { width: availableWidth, height: usedHeight }; }; Legend.prototype._placeLegendBlockBottom = function _placeLegendBlockBottom(availableHeight) { var legend = this, chart = legend.getFromEnv('chart'), chartConfig = chart.config, origRenderWidth = chart.getFromEnv('chartWidth'), origRenderHeight = chart.getFromEnv('chartHeight'), spacingLeft = chartConfig.canvasLeft, spacingRight = chartConfig.width - (chartConfig.canvasRight || 0), SmartLabel = chart.getFromEnv('smartLabel'), config = legend.config, marginLeft = config.chartMarginLeft, marginRight = config.chartMarginRight, marginTop = config.chartMarginTop, alignLegendWithCanvas = config.alignLegendWithCanvas, itemArr = legend.getSortedLegendItems(), len = itemArr.length, legendPadding = config.legendPadding, canvasMarginRight = chartConfig.canvasMarginRight, canvasMarginLeft = chartConfig.canvasMarginLeft, yAxis = chart.getChildren('yAxis'), verticalAxis = yAxis && yAxis[0].config.isVertical ? yAxis : chart.getChildren('xAxis'), axis1Obj = verticalAxis && verticalAxis[0], axis2Obj = verticalAxis && verticalAxis[1], axis1 = axis1Obj && axis1Obj.config || {}, axis2 = axis2Obj && axis2Obj.config || {}, title1Width = axis1.nameMaxW, title2Width = axis2.nameMaxW, axis1NameStyle = axis1.name && axis1.name.style || {}, axis2NameStyle = axis2.name && axis2.name.style || {}, axis1Title = axis1.axisName || _lib.BLANKSTRING, axis2Title = axis2.axisName || _lib.BLANKSTRING, usedHeight, availableWidth = chartConfig.canvasWidth - chartConfig.canvasMarginLeft - chartConfig.canvasMarginRight, yAxisTitleHeight, yAxisTitleWidth, title1, title2; config.paddingBottom = chartConfig.height - chartConfig.canvasBottom; SmartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); SmartLabel.setStyle(axis1NameStyle); title1 = SmartLabel.getOriSize(axis1Title); SmartLabel.setStyle(axis2NameStyle); title2 = SmartLabel.getOriSize(axis2Title); // after subtracting the padding from availableWidth if it is seen that the availableWidth is // 0px or negative then set all the paddings and the availableWidth to 0px so that no further // negative dimensions are derived. // // @scenario: If the chart is resized to a very smaller dimension(eg: 20 X 20), such that the available width is 0, and then // the static padding (which is 4px in this case) is subtracted from it, then negative width gets set to the legend box. if (availableWidth < legendPadding) { config.padding = legendPadding = availableWidth = 0; } if (title1 || title2) { yAxisTitleHeight = (0, _lib.pluckNumber)(title1.height, 0) > (0, _lib.pluckNumber)(title2.height, 0) ? (yAxisTitleWidth = title1Width) && title1.width : (yAxisTitleWidth = title2Width) && title2.width; } // When alignlegendwithcanvas is 0 we are checking if yAxisTitle is overlapping with legend or not // If it is overlapping then we are also taking yAxisTitleWidth into account // todo availableWidth = alignLegendWithCanvas ? availableWidth : origRenderWidth - (yAxisTitleHeight + marginTop > origRenderHeight - availableHeight ? 2 * yAxisTitleWidth + marginRight + marginLeft + canvasMarginRight + canvasMarginLeft : marginRight + marginLeft + canvasMarginLeft + canvasMarginRight); if (!config.showLegend || len === 0) { usedHeight = 0; config.height = 0; config.width = 0; } else { config.x = (spacingLeft - marginLeft - spacingRight + marginRight) / 2; usedHeight = legend.setDimension({ width: availableWidth, height: availableHeight }).height; } return { bottom: usedHeight, right: 0 }; }; Legend.prototype._placeLegendBlockRight = function _placeLegendBlockRight(availableWidth) { var legend = this, legendConf = legend.config, chart = legend.getFromEnv('chart'), chartConf = chart.config, SmartLabel = chart.getFromEnv('smartLabel'), canvasBorderThickness = chart.getChildren('canvas')[0].config.canvasBorderThickness || 0, textPadding = legendConf.textPadding, captionPadding = legendConf.title.padding, symbolPadding = legendConf.oriSymbolPadding, legendPadding = legendConf.legendPadding, legendScale = legendConf.legendScale, itemStyle = legend.getStateCosmetics('default'), itemFontSize = parseInt(itemStyle.text['font-size'], 10), availableHeight = chartConf.canvasHeight, allowedMaxHeight = availableHeight * 2, textWidthUsed = 0, padding = legendConf.padding, padding2 = 2 * padding, blockDimensions = { width: padding2, height: padding2 }, dimensions = {}, validLegendItem = false, itemArr = legend.getSortedLegendItems(), len = itemArr.length, usedWidth, smartText, textWidth, symbolWidthSpace, // rowHeight, legendHeight, itemConfig, name, captionWidth, userConfig, i = 0, item; legendConf.initialItemY = 0; legendConf.initialItemX = 0; availableWidth -= padding2 + legendPadding; // 5 pixel padding from canvas border // after subtracting the padding from availableWidth if it is seen that the availableWidth is // 0px or negative then set all the paddings and the availableWidth to 0px so that no further // negative dimensions are derived. // // @scenario: If the chart is resized to a very smaller dimension(eg: 20 X 20), such that the available width is 0, and then // the static padding (which is 4px in this case) is subtracted from it, then negative width gets set to the legend box. if (availableWidth < legendPadding) { legendConf.padding = legendPadding = availableWidth = 0; } symbolWidthSpace = itemFontSize + 1; if (symbolWidthSpace <= 0) { symbolWidthSpace = 1; } symbolWidthSpace *= legendScale; symbolPadding *= legendScale; symbolWidthSpace = mathMin(symbolWidthSpace, availableWidth); if (symbolWidthSpace <= 0) { symbolPadding = symbolWidthSpace = 0; } legendConf.symbolPadding = symbolPadding; legendConf.symbolWidth = symbolWidthSpace; legendConf.legendHeight = legendHeight = symbolWidthSpace + 2 * symbolPadding; legendConf.rowHeight = mathMax(parseInt(itemStyle.text['line-height'], 10) || 12, legendHeight); usedWidth = legendPadding + legendConf.borderWidth / 2 + canvasBorderThickness; textWidth = availableWidth - legendHeight - legendPadding - textPadding; if (textWidth < 0) { textWidth = 0; } // blockDimensions.width = mathMax (legendHeight, blockDimensions.width); SmartLabel.useEllipsesOnOverflow(chartConf.useEllipsesWhenOverflow); SmartLabel.setStyle((0, _lib.extend2)({}, itemStyle.text)); // If show legend is false and there are no items if (!legendConf.showLegend || len === 0) { dimensions.right = 0; legendConf.height = 0; legendConf.width = 0; } else { for (i = 0; i < len; i += 1) { item = itemArr[i]; itemConfig = item.config || (item.config = {}); userConfig = itemConfig; name = itemConfig.name = (0, _lib.parseUnsafeString)(userConfig.label); itemConfig._legendX = 0; itemConfig._legendY = blockDimensions.height; if (userConfig.enabled === 0 || userConfig.enabled === false || name === _lib.BLANKSTRING) { itemConfig.enabled = 0; continue; } else { itemConfig.enabled = 1; } validLegendItem = true; if (textWidth === 0) { blockDimensions.height += itemConfig._legendH = legendHeight; itemConfig.name = _lib.BLANKSTRING; itemConfig._totalWidth = symbolWidthSpace + symbolPadding; } else { smartText = SmartLabel.getSmartText(name, textWidth, allowedMaxHeight); itemConfig.name = smartText.text; smartText.tooltext && (itemConfig.originalText = smartText.tooltext); if (smartText.height < legendHeight) { itemConfig._legendTestY = (legendHeight - smartText.height) / 2; } itemConfig._totalWidth = symbolWidthSpace + symbolPadding + textPadding + smartText.width + legendPadding; blockDimensions.height += itemConfig._legendH = mathMax(smartText.height, legendHeight); textWidthUsed = mathMax(smartText.width, textWidthUsed); } } legendConf.validLegendItem = validLegendItem; if (validLegendItem) { legendConf.itemWidth = textWidthUsed + legendHeight + legendPadding + textPadding; legendConf.width = legendConf.itemWidth + padding2; if (legendConf.title.oriText !== _lib.BLANKSTRING) { SmartLabel.setStyle(legendConf.title.style); smartText = SmartLabel.getSmartText(legendConf.title.oriText, availableWidth, allowedMaxHeight); legendConf.title.text = smartText.text; smartText.tooltext && (legendConf.title.originalText = smartText.tooltext); captionWidth = smartText.width + padding2; // if the caption width has gretter width if (legendConf.width < captionWidth) { legendConf.initialItemX = (captionWidth - legendConf.width) / 2; legendConf.width = captionWidth; } legendConf.initialItemY = smartText.height + captionPadding; blockDimensions.height += legendConf.initialItemY; } legendConf.height = legendConf.totalHeight = blockDimensions.height; usedWidth = mathMin(legendConf.width + usedWidth, availableWidth); dimensions.right = usedWidth + legendPadding; legendConf.isActive = true; legendConf.enabled = true; } else { legendConf.enabled = false; legendConf.width = 0; dimensions.right = 0; } } return dimensions; }; Legend.prototype.postSpaceManager = function postSpaceManager() { var legend = this, legendConf = legend.config, legendPosition = legendConf.legendPos, chart = legend.getFromEnv('chart'), availableHeight = chart.config.canvasHeight; if (legendPosition === _lib.POSITION_RIGHT) { if (legendConf.height > availableHeight) { legendConf.height = availableHeight; legendConf.scroll.enabled = true; legendConf.scroll.flatScrollBars = legendConf.flatScrollBars; legendConf.scroll.scrollBar3DLighting = legendConf.scrollBar3DLighting; legendConf.width += (legendConf.scroll.scrollBarWidth = 10) + (legendConf.scroll.scrollBarPadding = 2); } else { legendConf.scroll.enabled = false; } } }; Legend.prototype.configureAttributes = function configureAttributes() { var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _ComponentInterface.prototype.configureAttributes.call(this, obj); var legend = this, config = legend.config, chart = legend.getFromEnv('chart'), chartConfig = chart.config, legendLineHeight, style = legend.getFromEnv('style'), chartAttr = chart.getFromEnv('chart-attrib'), is3D = chart.config.is3D, PXSTRING = 'px', colorM = legend.getFromEnv('color-manager'), borderColor, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, interactiveLegend = config.interactiveLegend = chart.hasInteractiveLegend !== false && Boolean((0, _lib.pluckNumber)(chartAttr.interactivelegend, 1)), borderAlpha, backgroundAlpha, roundEdges = (0, _lib.pluckNumber)(chartAttr.useroundedges, 0), padding = 4, outCancolor = style.outCancolor, textStyle = obj.style && obj.style.text, legendItemFont = (0, _lib.pluck)(chartAttr.legenditemfont, textStyle && textStyle['font-family'], style.outCanfontFamily), legendScale = (0, _lib.pluckNumber)(chartAttr.legendiconscale, 1), legendFontSize = (0, _lib.pluckFontSize)(chartAttr.legenditemfontsize, textStyle && textStyle['font-size'], style.fontSize) + PXSTRING, legendFontColor = (0, _lib.pluck)(chartAttr.legenditemfontcolor, textStyle && textStyle.color, outCancolor).replace(/^#?([a-f0-9]+)/ig, '#$1'), legendItemHoverFontColor = (0, _lib.getFirstColor)((0, _lib.pluck)(chartAttr.legenditemhoverfontcolor, legendFontColor)), anchorMap; config.isActive = false; config.chartMarginTop = chartConfig.origMarginTop; config.chartMarginRight = chartConfig.origMarginRight; config.chartMarginBottom = chartConfig.origMarginBottom; config.chartMarginLeft = chartConfig.origMarginLeft; config.reverselegend = (0, _lib.pluckNumber)(chartAttr.reverselegend, 0); config.showLegend = (0, _lib.pluckNumber)(chartAttr.showlegend, !chart.dontShowLegendByDefault, 1); legendLineHeight = (0, _lib.setLineHeight)({ fontSize: legendFontSize }); config.legendPos = (0, _lib.pluck)(chartAttr.legendposition, chart.legendposition, obj.legendPosition, _lib.POSITION_BOTTOM).toLowerCase(); config.numColumns = (0, _lib.pluckNumber)(chartAttr.legendnumcolumns, 0); config.xL = config.yL = 0; if (legendScale <= 0 || legendScale > 5) { legendScale = 1; } config.drawCustomLegendIcon = (0, _lib.pluckNumber)(chartAttr.drawcustomlegendicon, obj.drawcustomlegendicon, 0); config.legendScale = legendScale; config.legendPadding = (0, _lib.pluckNumber)(chartAttr.legendpadding, 7); config.alignLegendWithCanvas = (0, _lib.pluckNumber)(obj.alignlegendwithcanvas, chartConfig.alignLegendWithCanvas); config.title.style = { fontFamily: (0, _lib.pluck)(chartAttr.legendcaptionfont, legendItemFont), fontSize: (0, _lib.pluckFontSize)(chartAttr.legendcaptionfontsize, style.fontSize) + PXSTRING, color: (0, _lib.pluck)(chartAttr.legendcaptionfontcolor, outCancolor).replace(/^#?([a-f0-9]+)/ig, '#$1'), fontWeight: styleValueMap.fontWeight[(0, _lib.pluckNumber)(chartAttr.legendcaptionfontbold, 1)] || _lib.BLANKSTRING }; anchorMap = chartAttr.legendcaptionalignment ? chartAttr.legendcaptionalignment.toLowerCase() : TEXT_ANCHOR_MAP.center; config.title.align = TEXT_ANCHOR_MAP[anchorMap] || TEXT_ANCHOR_MAP.center; config.title.style['text-anchor'] = config.title.align; config.padding = padding; // parse legend border properties borderColor = (0, _lib.pluck)(chartAttr.legendbordercolor, colorM.getColor(palleteString.legendBorderColor)); borderAlpha = config.borderAlpha = (0, _lib.pluckNumber)(chartAttr.legendborderalpha, 100); config.borderColor = (0, _lib.convertColor)(borderColor, borderAlpha); config.borderWidth = (0, _lib.pluckNumber)(chartAttr.legendborderthickness, obj.legendborderthickness, !roundEdges || chartAttr.legendbordercolor ? 1 : 0); config.borderRadius = (0, _lib.pluckNumber)(roundEdges, 0); // parse legend border properties config.backgroundAlpha = backgroundAlpha = (0, _lib.pluckNumber)(chartAttr.legendbgalpha, obj.legendbgalpha, 100); config.backgroundColor = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.legendbgcolor, colorM.getColor(palleteString.legendBgColor)), backgroundAlpha); config.symbol3DLighting = Boolean((0, _lib.pluckNumber)(chartAttr.use3dlighting, chartAttr.useplotgradientcolor, 1)); config.shadow = Boolean((0, _lib.pluckNumber)(chartAttr.legendshadow, 1)); if (config.shadow) { config.shadow = { enabled: config.shadow, opacity: mathMax(borderAlpha, backgroundAlpha) / 100 }; } config.prevReversed = Boolean((0, _lib.pluckNumber)(config.reversed, 0)); config.reversed = Boolean((0, _lib.pluckNumber)(chartAttr.reverselegend, 0)); config.lineWidth = (0, _lib.pluckNumber)(chartAttr.linethickness, 2); config.borderRadius = (0, _lib.pluckNumber)(chartAttr.legendborderradius, roundEdges ? 3 : 0); // extra attr on hc JSON added for fc attr support config.legendAllowDrag = Boolean((0, _lib.pluckNumber)(chartAttr.legendallowdrag, 0)); config.title.oriText = (0, _lib.parseUnsafeString)((0, _lib.getFirstValue)(chartAttr.legendcaption, _lib.BLANKSTRING)); config.legendScrollBgColor = (0, _lib.getFirstColor)((0, _lib.pluck)(chartAttr.legendscrollbgcolor, chartAttr.scrollcolor, colorM.getColor('altHGridColor'))); config.legendScrollBarColor = (0, _lib.pluck)(chartAttr.legendscrollbarcolor, borderColor); config.legendScrollBtnColor = (0, _lib.pluck)(chartAttr.legendscrollbtncolor, borderColor); config.minimiseWrappingInLegend = (0, _lib.pluckNumber)(chartAttr.minimisewrappinginlegend, 0); config.flatScrollBars = (0, _lib.pluckNumber)(chartAttr.flatscrollbars, 0); config.scrollBar3DLighting = (0, _lib.pluckNumber)(chartAttr.scrollbar3dlighting, 1); config.orderReversed = false; legend.setStateCosmetics('hidden', { symbol: { fill: (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.legenditemhiddencolor, 'cccccc').replace(/^#?([a-f0-9]+)/ig, '#$1')), stroke: (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.legenditemhiddencolor, 'cccccc').replace(/^#?([a-f0-9]+)/ig, '#$1')) }, text: { fill: (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.legenditemhiddencolor, 'cccccc').replace(/^#?([a-f0-9]+)/ig, '#$1')) } }); legend.setStateCosmetics('default', { text: { fill: (0, _lib.convertColor)(legendFontColor), 'font-family': legendItemFont, cursor: interactiveLegend ? _lib.preDefStr.POINTER : 'default', 'font-size': legendFontSize, 'line-height': legendLineHeight, 'vertical-align': _lib.POSITION_TOP, 'text-anchor': _lib.POSITION_START, direction: chartConfig.textDirection === 'rtl' ? 'rtl' : 'initial', 'font-weight': styleValueMap.fontWeight[(0, _lib.pluckNumber)(chartAttr.legenditemfontbold, 0)] || _lib.BLANKSTRING }, symbol: { bgColor: (0, _lib.pluck)(chartAttr.legendiconbgcolor), cursor: interactiveLegend ? _lib.preDefStr.POINTER : 'default', borderColor: (0, _lib.pluck)(chartAttr.legendiconbordercolor), bgAlpha: (0, _lib.pluck)(chartAttr.legendiconbgalpha, chartAttr.legendiconalpha, 100), borderAlpha: (0, _lib.pluck)(chartAttr.legendiconborderalpha, chartAttr.legendiconalpha, 100), borderThickness: (0, _lib.pluckNumber)(chartAttr.legendiconborderthickness), startAngle: (0, _lib.pluckNumber)(chartAttr.legendiconstartangle, 45), sides: (0, _lib.pluckNumber)(chartAttr.legendiconsides, obj.legendiconsides, 4) } }); legend.setStateCosmetics('hover', function (cosmetics, legenditem) { // only applied the text hovered color only if text is not hidden. if (!legenditem.hasState('hidden')) { if (!cosmetics.text) { cosmetics.text = {}; } // set the text color and cursor. cosmetics.text.fill = (0, _lib.convertColor)(legendItemHoverFontColor.replace(/^#?([a-f0-9]+)/ig, '#$1')); cosmetics.text.cursor = 'inherit'; } return cosmetics; }); // add/remove drag events on legend if (config.legendAllowDrag && !config._dragEvtListenerBinded) { legend.addEventListener('fc-dragstart', config.handlers.dragstart); legend.addEventListener('fc-dragmove', config.handlers.dragmove); config._dragEvtListenerBinded = true; } else { legend.removeEventListener('fc-dragstart', config.handlers.dragstart); legend.removeEventListener('fc-dragmove', config.handlers.dragmove); config._dragEvtListenerBinded = false; } }; /** * Gets all present states of legend */ Legend.prototype.getLegendState = function getLegendState() { return this._legendState; }; /** * Checks whether a particular state is present * @param {String} state the state to be checked */ Legend.prototype.hasState = function hasState(state) { var states = this.getLegendState(), i, len; for (i = 0, len = states.length; i < len; i++) { if (states[i] === state) { return true; } } return false; }; /** * @param {state} state State to be added * @param {Boolean} pushAtEnd Flag to decide whether to push the state at the end of legend item states array */ Legend.prototype.setLegendState = function setLegendState(state, pushAtEnd) { if (!this.hasState(state)) { if (pushAtEnd) { this._legendState.push(state); } else { this._legendState.unshift(state); } } this.asyncDraw(); }; /** * Method that removes a particular state from the state array * @param {String} state state that needs to be removed from the legend item state array */ Legend.prototype.removeLegendState = function removeLegendState(state) { var i, len, notFound = 1; if (state) { for (i = 0, len = this._legendState.length; i < len && notFound; i++) { if (state === this._legendState[i]) { this._legendState.splice(i, 1); notFound = 0; } } } else { this._legendState.length = 0; } this.asyncDraw(); }; /** * @param {String} state State whose cosmetics needs to be added * @param {Object} cosmetics Cosmetics of that particular state */ Legend.prototype.setStateCosmetics = function setStateCosmetics(state, cosmetics) { this._stateCosmetics[state] = cosmetics; }; /** * Method that removes the cosmetics of a particular legend state * @param {String} state State whose cosmetics needs to be removed */ Legend.prototype.removeStateCosmetics = function removeStateCosmetics(state) { delete this._stateCosmetics[state]; }; /** * Method that returns the cosmetics of the provided state * @param {String} state name of the state */ Legend.prototype.getStateCosmetics = function getStateCosmetics(state) { return this._stateCosmetics[state]; }; Legend.prototype.hide = function hide() { var legend = this, chart = legend.getFromEnv('chart'), legendGroup = chart.getChildContainer('legendGroup'); legendGroup && legendGroup.hide(); }; return Legend; }(_componentInterface.ComponentInterface); exports['default'] = Legend; /***/ }), /* 464 */ /***/ (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 _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); var _dependencyManager = __webpack_require__(132); var _legendItem = __webpack_require__(465); var _legendItem2 = _interopRequireDefault(_legendItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var POINTER = _lib.preDefStr.POINTER, NONE = 'none', M = 'M', L = 'L', // function that will create a symbol path for a legend icon. _getSymbolPath = function _getSymbolPath(x, y, w, h, seriesType) { // TODO: have to add group and group style so that we can replivate the safme as fc var path = [M], w1, w2, h1, h2, height3, cx1, cx2, cy1, cy2, d1, d2, Z = 'Z', A = 'A'; switch (seriesType) { case 'column': case 'dragColumn': case 'column3D': case 'realtimeColumn': case 'errorBar2D': w1 = w * 0.25; w2 = w1 * 0.5; h1 = h * 0.7; h2 = h * 0.4; path = path.concat([x, y + h, 'l', 0, -h1, w1, 0, 0, h1, 'z', 'm', w1 + w2, 0, 'l', 0, -h, w1, 0, 0, h, 'z', 'm', w1 + w2, 0, 'l', 0, -h2, w1, 0, 0, h2, 'z']); break; case 'bar2D': case 'bar3D': w1 = w * 0.3; w2 = w * 0.6; h1 = h / 4; h2 = h1 / 2; path = path.concat([x, y, L, x + w2, y, x + w2, y + h1, x, y + h1, Z, M, x, y + h1 + h2, L, x + w, y + h1 + h2, x + w, y + h1 + h2 + h1, x, y + 2 * h1 + h2, Z, M, x, y + 2 * (h1 + h2), L, x + w1, y + 2 * (h1 + h2), x + w1, y + h, x, y + h, Z]); break; case 'area': case 'area3d': case 'areaspline': case 'dragArea': case 'realTimeArea': case 'splinearea': w1 = w * 0.3; w2 = w * 0.6; h1 = h * 0.6; h2 = h * 0.2; height3 = h * 0.8; path = path.concat([x, y + height3, L, x, y + h1, x + w1, y + h2, x + w2, y + h1, x + w, y + h2, x + w, y + height3, Z]); break; case 'pie2D': case 'pie3d': case 'doughnut2D': case 'doughnut3D': w1 = w * 0.5; // Radius w2 = w1 * 0.9; d1 = 1; d2 = 1; cx1 = x + w1 + d1; cy1 = y + w1 - d1; cx2 = x + w1 - d2; cy2 = y + w1 + d2; path = path.concat([cx1, cy1, L, cx1, cy1 - w2 + d1, A, w2 - d1, w2 - d1, 0, 0, 1, cx1 + w2 - d1, cy1, Z, M, cx2, cy2, L, cx2, cy2 - w2, A, w2, w2, 0, 1, 0, cx2 + w2, cy2, Z]); break; case 'boxandwhisker2d': path = path.concat([x, y, L, x + w, y, x + w, y + h, x, y + h, Z]); break; // A square line for every other request. default: path = path.concat([x, y, L, x + w, y, x + w, y + h, x, y + h, Z]); } return { path: path }; }, // method that calculates anchor properties when achorside is given getAnchorProps = function getAnchorProps(legendItem, symbolStyle) { var legendItemConfig = legendItem.config, legendConfig = legendItem.getLinkedParent().config, symbolWidth = legendConfig.symbolWidth, padding = (0, _lib.pluckNumber)(legendConfig.padding, 4), radius = symbolWidth * 0.5, itemX = (legendConfig.initialItemX || 0) + legendItemConfig._legendX + padding, itemY = (legendConfig.initialItemY || 0) + legendItemConfig._legendY - padding, cx = itemX + legendConfig.symbolPadding + radius, cy = itemY + (legendItemConfig._markerYGutter || 0) + legendConfig.symbolPadding + radius, symbolStr = (0, _lib.mapSymbolName)(legendItemConfig.anchorSide), symbol = legendItemConfig.symbol = symbolStr && symbolStr.split('_') || [], dip = symbol[0] === 'spoke' ? 1 : 0; if (legendItemConfig.type === 'line' || legendItemConfig.drawLine) { radius *= 0.6; } return { path: (0, _lib.polyPathToPath)([symbol[1] || 2, cx, cy, radius, legendItemConfig.startAngle, legendItemConfig.spoke || dip]), cursor: symbolStyle.cursor || POINTER, stroke: symbolStyle.stroke, fill: symbolStyle.fill, 'stroke-width': symbolStyle['stroke-width'] || 0.5 }; }; (0, _dependencyManager.addDep)({ name: 'legendItemAnimation', type: 'animationRule', extension: _legendItem2['default'] }); var LegendItem = function (_ComponentInterface) { _inherits(LegendItem, _ComponentInterface); /** * Creates an instance of LegendItem. * @memberof LegendItem */ function LegendItem() { _classCallCheck(this, LegendItem); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this._stateCosmetics = {}; _this._legendState = []; return _this; } /** * return the name of the component. * @return {string} name of component. */ LegendItem.prototype.getName = function getName() { return 'legendItem'; }; // method that parses both legend and legend-item state cosmetics and returns merged cosmetics for each state LegendItem.prototype.parseLegendCosmetics = function parseLegendCosmetics() { var legendItem = this, legend = this.getLinkedParent(), legendStates = legend.getLegendState(), legendItemStates = legendItem.getLegendState(), legendCosmetic = void 0, itemCosmetic = void 0, allStates = ['default'], finalCosmetics = {}, i = void 0; allStates = allStates.concat(legendStates, legendItemStates); for (i = 0; i < allStates.length; i++) { legendCosmetic = legend.getStateCosmetics(allStates[i]); itemCosmetic = legendItem.getStateCosmetics(allStates[i]); if (legendCosmetic) { if (typeof legendCosmetic === 'function') { finalCosmetics = legendCosmetic(finalCosmetics, legendItem); } else { (0, _lib.extend2)(finalCosmetics, legendCosmetic); } } if (itemCosmetic) { if (typeof itemCosmetic === 'function') { finalCosmetics = itemCosmetic(finalCosmetics, legendItem); } else { (0, _lib.extend2)(finalCosmetics, itemCosmetic); } } } return finalCosmetics; }; /** * return the type of component. * @return {string} type of component. */ LegendItem.prototype.getType = function getType() { return 'legendItem'; }; /** * Does the configuration for legend item. * @param {Object} config object. */ LegendItem.prototype.configure = function configure(configObj) { var legendItem = this, config = legendItem.config, prop, value; for (prop in configObj) { if (configObj.hasOwnProperty(prop)) { if (_typeof(configObj[prop]) !== 'object') { config[prop] = configObj[prop]; } else { var obj = config[prop] ? config[prop] : {}; for (value in configObj[prop]) { obj[value] = configObj[prop][value]; } config[prop] = obj; } } } }; /** * Method that decides whether to call legend interactivity based on whether the legend is interactive or not */ LegendItem.prototype.itemClickFn = function itemClickFn() { var legendItem = this, chartAttr = legendItem.getFromEnv('chart-attrib'), interactivelegend = (0, _lib.pluckNumber)(chartAttr.interactivelegend, 1), dataset = legendItem.getLinkedItem('owner'); if (interactivelegend) { dataset.legendInteractivity(legendItem); } }; LegendItem.prototype.dispose = function dispose() { this.removeEventListener('fc-click', this.click); this.removeEventListener('fc-mouseover', this.mouseover); this._dispose(); }; /** * Gets all present states of legend item */ LegendItem.prototype.getLegendState = function getLegendState() { return this._legendState; }; /** * Checks whether a particular state is present * @param {String} state the state to be checked */ LegendItem.prototype.hasState = function hasState(state) { var states = this.getLegendState(), i, len; for (i = 0, len = states.length; i < len; i++) { if (states[i] === state) { return true; } } return false; }; /** * @param {state} state State to be added * @param {Boolean} pushAtEnd Flag to decide whether to push the state at the end of legend item states array */ LegendItem.prototype.setLegendState = function setLegendState(state, pushAtEnd) { if (!this.hasState(state)) { if (pushAtEnd) { this._legendState.push(state); } else { this._legendState.unshift(state); } } this.asyncDraw(); }; /** * Method that removes a particular state from the state array * @param {String} state state that needs to be removed from the legend item state array */ LegendItem.prototype.removeLegendState = function removeLegendState(state) { var i, len, notFound = 1; if (state) { for (i = 0, len = this._legendState.length; i < len && notFound; i++) { if (state === this._legendState[i]) { this._legendState.splice(i, 1); notFound = 0; } } } else { this._legendState.length = 0; } this.asyncDraw(); }; /** * Method that removes the cosmetics of a particular legend state * @param {String} state State whose cosmetics needs to be removed */ LegendItem.prototype.removeStateCosmetics = function removeStateCosmetics(state) { delete this._stateCosmetics[state]; }; /** * @param {String} state State whose cosmetics needs to be added * @param {Object} cosmetics Cosmetics of that particular state */ LegendItem.prototype.setStateCosmetics = function setStateCosmetics(state, cosmetics) { this._stateCosmetics[state] = cosmetics; }; /** * Method that returns the cosmetics of the provided state * @param {String} state name of the state */ LegendItem.prototype.getStateCosmetics = function getStateCosmetics(state) { return this._stateCosmetics[state]; }; /** * Draw the legend item. */ LegendItem.prototype.draw = function draw() { var legend = this.getLinkedParent(), chart = legend.getFromEnv('chart'), chartConfig = chart.config, legendItem = this, animationManager = legendItem.getFromEnv('animationManager'), legendItemConfig = legendItem.config, config = legend.config, symbolBoxW = config.legendHeight, symbolPadding = config.symbolPadding, symbolWidth = config.symbolWidth, interactiveLegend = config.interactiveLegend, textPadding = config.textPadding || 2, padding = (0, _lib.pluckNumber)(config.padding, 4), itemStyle, itemHoverStyle = config.itemHoverStyle, lineWidth, itemGroup = legend.getChildContainer('itemGroup'), drawCustomLegendIcon = config.drawCustomLegendIcon, hidden = legendItem.hasState('hidden'), customLegendConfig, initialItemX, initialItemY, cy, legendItemText, legendItemTextCheck, type, itemX, itemY, legendItemLine, symbolConfig, legendItemSymbol, legendItemSymbolCheck, cx, radius, dip, symbol, strokeColor, fillColor, bgFill, anchorSide, drawLine, symbolStr, customBgColor, customBgAlpha, customBorderColor, customBorderAlpha, fillcolor, strokecolor, legendItemBackground, legendItemBackgroundCheck, textCosmetics, drawItemLine, symbolAttr, backgroundAttr, backgroundCosmetics, lineAttr, lineCosmetics = {}, xPos, yPos; itemStyle = legendItem.parseLegendCosmetics(); customLegendConfig = itemStyle.symbol; initialItemX = config.initialItemX || 0; initialItemY = config.initialItemY || 0; type = legendItemConfig.type; strokeColor = itemStyle.symbol.stroke || '000000'; fillColor = itemStyle.symbol.fill; lineWidth = itemStyle.symbol.lineWidth || config.lineWidth; anchorSide = legendItemConfig.anchorSide; drawLine = legendItemConfig.drawLine; itemX = initialItemX + legendItemConfig._legendX + padding; itemY = initialItemY + legendItemConfig._legendY - padding; legendItemBackgroundCheck = legendItem.getGraphicalElement('legendItemBackground'); legendItemTextCheck = legendItem.getGraphicalElement('legendItemText'); legendItemLine = legendItem.getGraphicalElement('legendItemLine'); legendItemSymbolCheck = legendItem.getGraphicalElement('legendItemSymbol'); interactiveLegend = (0, _lib.pluck)(legendItemConfig.interactiveLegend, interactiveLegend); !interactiveLegend && (itemStyle.cursor = 'default'); textCosmetics = itemStyle.text; xPos = itemX + symbolBoxW + textPadding - 2; yPos = itemY + (legendItemConfig._legendTestY || 0); textCosmetics.text = legendItemConfig.name; textCosmetics.x = xPos; textCosmetics.y = yPos; legendItemText = animationManager.setAnimation({ el: legendItemTextCheck || 'text', attr: textCosmetics, component: legendItem, container: itemGroup, label: 'icon' }); if (!legendItemTextCheck) { legendItemText = legendItem.addGraphicalElement('legendItemText', legendItemText); } legendItemText.data('legendItem', legendItemConfig); drawItemLine = false; if (drawCustomLegendIcon && legendItemConfig.customLegendIcon !== false) { customBorderColor = !hidden && customLegendConfig.borderColor; customBorderAlpha = (0, _lib.pluck)(customLegendConfig.borderAlpha); customBgColor = !hidden && customLegendConfig.bgColor; customBgAlpha = (0, _lib.pluck)(customLegendConfig.bgAlpha, '100'); fillcolor = itemStyle.symbol.rawFillColor; fillColor = !hidden ? customBgColor || fillcolor : itemStyle.symbol.fill; fillColor = (0, _lib.convertColor)(fillColor, customBgAlpha); strokecolor = itemStyle.symbol.rawStrokeColor; strokeColor = !hidden ? customBorderColor || strokecolor || fillcolor : itemStyle.symbol.stroke; strokeColor = (0, _lib.convertColor)(strokeColor, customBorderAlpha); radius = symbolWidth * 0.5; cx = itemX + symbolPadding + radius; cy = itemY + (legendItemConfig._markerYGutter || 0) + symbolPadding + radius; symbolStr = (0, _lib.mapSymbolName)(customLegendConfig.sides); symbol = symbolStr && (0, _lib.mapSymbolName)(customLegendConfig.sides).split('_') || []; dip = symbol[0] === 'spoke' ? 1 : 0; symbolAttr = { path: (0, _lib.polyPathToPath)([symbol[1] || 2, cx, cy, radius, customLegendConfig.startAngle || 0, dip]), cursor: itemStyle.symbol.cursor || POINTER, stroke: strokeColor, fill: fillColor, 'stroke-width': (0, _lib.pluckNumber)(customLegendConfig.borderThickness, 1) }; } else if (type === 'line' || drawLine) { // drawing line legend or when other legends have line in it cy = itemY + (legendItemConfig._markerYGutter || 0) + symbolPadding + symbolWidth * 0.5; lineAttr = { path: [M, itemX + symbolPadding, cy, L, itemX + symbolPadding + symbolWidth, cy] }; drawItemLine = true; lineCosmetics = { 'opacity': chartConfig.legendiconalpha || 1, 'stroke-width': lineWidth, stroke: strokeColor, cursor: itemStyle.cursor || POINTER }; if (anchorSide) { symbolAttr = getAnchorProps(legendItem, itemStyle.symbol); } } else if (anchorSide) { // draw polypath legend symbolAttr = getAnchorProps(legendItem, itemStyle.symbol); } else if (type !== 'line') { // drawing the remaining legends strokeColor = legendItemConfig.symbolStroke || strokeColor; symbolConfig = _getSymbolPath(itemX + symbolPadding, itemY + (legendItemConfig._markerYGutter || 0) + symbolPadding, symbolWidth, symbolWidth, type); symbolAttr = { path: symbolConfig.path, 'stroke-width': 0.5, stroke: strokeColor, fill: fillColor, cursor: itemStyle.cursor || POINTER }; } if (lineAttr && drawItemLine) { Object.assign(lineAttr, lineCosmetics); legendItemLine = animationManager.setAnimation({ el: legendItemLine || 'path', attr: lineAttr, component: legendItem, callback: function callback() { this.show(); }, container: itemGroup }); if (!legendItem.getGraphicalElement('legendItemLine')) { legendItemLine = legendItem.addGraphicalElement('legendItemLine', legendItemLine); } } else { if (legendItemLine) { legendItemLine.hide(); } } if (symbolAttr) { symbolAttr.opacity = (0, _lib.pluckNumber)(itemStyle.symbol.opacity, 1); legendItemSymbol = animationManager.setAnimation({ el: legendItemSymbolCheck || 'path', attr: symbolAttr, component: legendItem, callback: function callback() { this.show(); }, container: itemGroup, label: 'icon' }); if (!legendItemSymbolCheck || !legendItemSymbolCheck.node) { legendItemSymbol = legendItem.addGraphicalElement('legendItemSymbol', legendItemSymbol); } legendItemSymbol.data('legendItem', legendItemConfig); } else { legendItemSymbolCheck && legendItemSymbolCheck.hide(); } if (itemStyle.background && itemStyle.background.legendBackgroundColor) { bgFill = (0, _lib.convertColor)(itemStyle.background.legendBackgroundColor, itemStyle.background.alpha); } else { bgFill = _lib.TRACKER_FILL; } // draw background backgroundAttr = { x: itemX, y: itemY, width: legendItemConfig._totalWidth, height: legendItemConfig._legendH, r: 0, fill: bgFill, opacity: 1, 'stroke-width': 1, stroke: NONE, cursor: itemStyle.symbol.cursor || POINTER }; legendItemBackground = animationManager.setAnimation({ el: legendItemBackgroundCheck || 'rect', attr: backgroundAttr, css: backgroundCosmetics, component: legendItem, label: 'background', container: itemGroup }); if (!legendItemBackgroundCheck) { legendItem.addGraphicalElement('legendItemBackground', legendItemBackground); } legendItemBackground.data('legendItem', legendItem).data('interactive', interactiveLegend).data('itemHoverStyle', itemHoverStyle).data('itemStyle', itemStyle); }; return LegendItem; }(_componentInterface.ComponentInterface); exports['default'] = LegendItem; /***/ }), /* 465 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { '*.legendItem.legendItem': function legendItemLegendItem() { return { 'icon.appearing': function iconAppearing() { return [{ initialAttr: { opacity: 0 }, slot: 'plot', startEnd: { start: 0.5, end: 1 }, finalAttr: { opacity: 1 } }]; }, 'background.appearing': function backgroundAppearing(inputJSON) { return [{ initialAttr: { opacity: 0 }, slot: 'plot', startEnd: { start: 0.5, end: 1 }, finalAttr: { opacity: inputJSON.attr.opacity } }]; }, 'icon.disappearing': function iconDisappearing() { return [{ finalAttr: { opacity: 0 }, slot: 'initial' }]; } }; } }; /***/ }), /* 466 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var appearing = [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'plot' }], updating = [{ slot: 'plot', startEnd: { start: 0, end: 0.5 } }], disappearing = [{ slot: 'intial' }]; exports['default'] = { '*.legend.legend': function legendLegend() { return { 'legendGroup.appearing': appearing, 'legendGroup.updating': updating, 'legendGroup.disappearing': disappearing, 'scroller.appearing': appearing, 'scroller.updating': updating, 'scroller.disappearing': disappearing }; } }; /***/ }), /* 467 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.drawLabel = undefined; var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(468); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var UNDEF = void 0, visibleStr = _lib.preDefStr.visibleStr, hiddenStr = _lib.preDefStr.hiddenStr, POSITION_MIDDLE = _lib.preDefStr.POSITION_MIDDLE, POSITION_START = _lib.preDefStr.POSITION_START, POSITION_END = _lib.preDefStr.POSITION_END, math = Math, mathMin = math.min, mathMax = math.max, defined = function defined(obj) { return obj !== UNDEF && obj !== null; }, _drawLabel = function _drawLabel() { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConf = chart.config, JSONData = dataSet.config.JSONData, animationManager = dataSet.getFromEnv('animationManager'), canvasConf = chart.getChildren('canvas')[0].config, style = chart.config.dataLabelStyle, setDataArr = JSONData.data, categories = chart.config.categories, is3D = chart.config.is3D, isStacked = chart.config.isstacked, catLen = categories && categories.length, dataSetLen = setDataArr && setDataArr.length, len, dataStore = dataSet.getData(), SmartLabel = chart.getFromEnv('smartLabel'), dataObj, attr, yDepth = canvasConf.yDepth, xDepth = canvasConf.xDepth, numberFormatter = chart.getFromEnv('number-formatter'), i, j, displayValue = '', setData, placeValuesInside = chartConf.placevaluesinside, canvasWidth = chartConf.canvasWidth, canvasLeft = chartConf.canvasLeft, graphic, height, gutter = 2, valuePadding = chartConf.valuepadding + gutter, textY, textX, outsideColSpace, isNegative, yPos, xPos, width, setValue, dataLabelContainer = dataSet.getContainer('labelGroup'), textAnchor, textWidth, xAdjust, GUTTER_4 = 4, skipInfo = dataSet.getSkippingInfo && dataSet.getSkippingInfo(), skippingApplied = skipInfo && skipInfo.skippingApplied, plotDrawArray = skipInfo && skipInfo.labelDraw || [], plotDrawArrayLength = plotDrawArray.length, config, plotLabel, plotLabelCheck, dim, tempGraphics, visible = dataSet.getState('visible'), callback = function callback() { this.hide(); }; visible && dataLabelContainer.show(); SmartLabel.setStyle(style); len = skippingApplied ? plotDrawArrayLength : catLen < dataSetLen ? catLen : dataSetLen; for (j = 0; j < len; j++) { i = skippingApplied ? plotDrawArray[j] : j; dataObj = dataStore[i]; config = dataObj && dataObj.config; setValue = config && config.setValue; // Condition arises when user has removed data in real time update if (dataObj === UNDEF || setValue === UNDEF || setValue === null || config.labelSkip === true) { tempGraphics = dataObj && dataObj.graphics; if (tempGraphics) { tempGraphics.label && tempGraphics.label.hide(); } config && delete config.labelSkip; continue; } graphic = dataObj.graphics; // Condition arises when feedData enters less number of data in a dataset compared to the other. if (!graphic) { continue; } setData = setDataArr[i]; yPos = dataObj._yPos; xPos = dataObj._xPos; setValue = numberFormatter.getCleanValue(setData.value); isNegative = (0, _lib.pluckNumber)(setValue) < 0; height = dataObj._height; width = dataObj._width; textAnchor = isStacked ? POSITION_MIDDLE : isNegative ? /** @todo this boolean check needs optimisation */ placeValuesInside ? POSITION_START : POSITION_END : placeValuesInside ? POSITION_END : POSITION_START; displayValue = config.displayValue; plotLabelCheck = graphic.label; // Dont draw values if the respective conditions are not satisfied if (config.showValue && defined(displayValue) && displayValue !== _lib.BLANKSTRING && setValue !== null) { // Preparing the attributes of the text attr = { text: displayValue, fill: style.color, 'text-bound': [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash], 'line-height': style.lineHeight, // todo-text direction missing visibility: dataSet.getState('visible') ? visibleStr : hiddenStr }; dim = SmartLabel.getOriSize(displayValue); textWidth = dim.width; textWidth += valuePadding; xAdjust = valuePadding; textY = yPos + height * 0.5; textX = xPos + (isNegative ? 0 : width); if (isNegative) { outsideColSpace = xPos - canvasLeft; } else { outsideColSpace = canvasLeft + canvasWidth - (xPos + width); } // For stacked charts values are always placed at middle if (isStacked) { textX += (isNegative ? width : -width) * 0.5; textX = mathMax(canvasLeft + textWidth * 0.5, textX); textX = mathMin(canvasLeft + canvasWidth - textWidth * 0.5, textX); // If 3D chart then xDepth and yDepth is also to be considered for // calculating x y position textX -= is3D ? xDepth : 0; textY += is3D ? yDepth : 0; } else { if (placeValuesInside) { // If label fits inside the data plot if (width >= textWidth) { textX += isNegative ? xAdjust : -xAdjust; if (is3D) { textY += yDepth; textX -= xDepth; } } else { // If label fits outside the data plot if (textWidth < outsideColSpace) { textX += isNegative ? -xAdjust : xAdjust; textAnchor = isNegative ? POSITION_END : POSITION_START; if (is3D && isNegative) { textX -= xDepth; } } else { // Label management for negative values if (isNegative) { textX = xPos + width + mathMax(textWidth - xPos - width + canvasLeft, 0) - xAdjust; // If negative value then drawing text from end textAnchor = POSITION_END; } else { textX = xPos - mathMax(textWidth - (canvasLeft + canvasWidth - xPos), 0) + xAdjust; textAnchor = POSITION_START; } // Taking xDepth yDepth into consideration for 3d charts if (is3D) { textX -= xDepth; textY += yDepth; } } } } else { // If space is available inside plot if (outsideColSpace >= textWidth) { textX += isNegative ? -xAdjust : xAdjust; if (is3D && isNegative) { textX -= xDepth; textY += xDepth; } } else { // If space not available inside plot textX += isNegative ? xAdjust + textWidth : -(xAdjust + textWidth); if (is3D) { textX -= xDepth; textY += yDepth; } } } } // If value gets out of canvas if (textX > canvasLeft + canvasWidth || textX < canvasLeft) { textX = canvasLeft + GUTTER_4; textAnchor = POSITION_START; } attr['text-anchor'] = textAnchor; // If label is not created then create it attr.x = textX; attr.y = textY; attr['text-bound'] = [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash]; attr.opacity = visible ? 1 : 0; plotLabel = animationManager.setAnimation({ el: plotLabelCheck || 'text', container: dataLabelContainer, component: dataSet, attr: attr, callback: !visible && callback, label: 'plotLabel' }); if (!plotLabelCheck) { graphic.label = plotLabel; } } else if (graphic.label) { graphic.label = animationManager.setAnimation({ el: graphic.label, component: dataSet }); } } dataSet.config.labelDrawn = true; }; (0, _dependencyManager.addDep)({ name: 'barAnimation', type: 'animationRule', extension: _index2['default'] }); /** * Representing bar2d dataset */ var Bar2DDataset = function (_ColumnDataset) { _inherits(Bar2DDataset, _ColumnDataset); function Bar2DDataset() { _classCallCheck(this, Bar2DDataset); return _possibleConstructorReturn(this, _ColumnDataset.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ Bar2DDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ Bar2DDataset.prototype.getName = function getName() { return 'bar2D'; }; /** * Function to draw label for every data plot. * It calculates where to draw the label for data plot. */ Bar2DDataset.prototype.drawLabel = function drawLabel() { _drawLabel.call(this); }; return Bar2DDataset; }(_column2['default']); exports.drawLabel = _drawLabel; exports['default'] = Bar2DDataset; /***/ }), /* 468 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); exports['default'] = { 'initial.dataset.bar2D': function initialDatasetBar2D() { var component = this, chart = component.getFromEnv('chart'), yDepth = chart.config.yDepth || 0, yAttrKey = 'x', hAttrKey = 'width', yAxis = component.getFromEnv('yAxis'); return { 'rect.appearing': function rectAppearing(inputJSON) { var zeroPos = yAxis.getPixel(yAxis.getAxisBase()) + (chart.isBar ? -yDepth : yDepth), index = inputJSON.index, dataObj = component.components.data[index], actualFinalAttr = inputJSON.attr, yAttrVal, hAttrVal, yBasePos, endPosWRT0; // Store final y and h for later use yAttrVal = actualFinalAttr[yAttrKey]; hAttrVal = actualFinalAttr[hAttrKey]; endPosWRT0 = Math.sign(yAttrVal + hAttrVal / 2 - zeroPos); // If the plot is below zero plain, the base will be the y + h of the previousone // if it is stackked plot else y of the plot if (endPosWRT0 === 1) { yBasePos = yAttrVal; } else { // the base will be the y of the previousone if it is stackked plot else y+h of itself yBasePos = yAttrVal + hAttrVal; } dataObj._posWRT0 = endPosWRT0; return [{ initialAttr: function initialAttr() { var initialAttr = {}; // Replace the y and h with initial positions initialAttr[yAttrKey] = yBasePos; initialAttr[hAttrKey] = 0; initialAttr.opacity = 0; return initialAttr; }, finalAttr: { opacity: 1 }, startEnd: function startEnd() { var length = inputJSON.length; return _lib.animHelperFN.getTimeByValue(_lib.animHelperFN.animByWeight(index, length, 0.6), { startPx: zeroPos, endPx: endPosWRT0 === 1 ? component.config.yAxisMaxPixel : component.config.yAxisMinPixel }, { startPx: yBasePos, endPx: endPosWRT0 === 1 ? actualFinalAttr[yAttrKey] + actualFinalAttr[hAttrKey] : actualFinalAttr[yAttrKey] }); }, hookFn: function hookFn() { this.attr({ opacity: 1 }); }, effect: 'linear', slot: 'plot' }]; }, 'plotLabel.appearing': function plotLabelAppearing() { return [{ initialAttr: { opacity: 0 }, slot: 'final' }]; }, '*': null }; } }; /***/ }), /* 469 */, /* 470 */, /* 471 */, /* 472 */, /* 473 */, /* 474 */, /* 475 */, /* 476 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.hideFn = exports.plotClickHandler = exports.labelClickFn = exports.trimData = exports.plotGraphicClick = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var _area = __webpack_require__(450); var _area2 = _interopRequireDefault(_area); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(477); var _index2 = _interopRequireDefault(_index); var _redraphaelShapes = __webpack_require__(216); var _redraphaelShapes2 = _interopRequireDefault(_redraphaelShapes); var _schedular = __webpack_require__(136); var _printColor = __webpack_require__(182); var _printColor2 = _interopRequireDefault(_printColor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var Raphael = (0, _dependencyManager.getDep)('redraphael', 'plugin'), UNDEF = void 0, win = window, doc = win.document, isVML = !_lib.hasSVG, supportsTouch = 'createTouch' in doc, // The devices which both touch and pointer. supportsOnlyTouch = supportsTouch && !(win.navigator.maxTouchPoints || win.navigator.msMaxTouchPoints), ROLLOVER = 'DataPlotRollOver', ROLLOUT = 'DataPlotRollOut', EVENTARGS = 'eventArgs', TRANSFORMSTR = 't', DASH_DEF = 'none', POINTER = 'pointer', // SETROLLOVERATTR = 'setRolloverAttr', // SETROLLOUTATTR = 'setRolloutAttr', visibleStr = _lib.preDefStr.visibleStr, docMode8 = doc.documentMode === 8, VISIBLE = docMode8 ? visibleStr : '', HIDDEN = 'hidden', M = 'M', L = 'L', math = Math, mathATan2 = math.atan2, mathSin = math.sin, mathCos = math.cos, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCeil = math.ceil, mathFloor = math.floor, pi = math.PI, piBy2 = pi / 2, rad2deg = 180 / math.PI, pi2 = 2 * pi, pi3By2 = pi + piBy2, /** * Helper function to create a RedRaphael group. * @param {string} groupName Name of the group to be created. * @param {Element} parentContainer The parent container in which the group will be appended. * @param {Object} dataset The concerned dataset * @return {Element} The group that was created. */ createGroup = function createGroup(groupName, parentContainer, dataset) { var animationManager = dataset.getFromEnv('animationManager'); return animationManager.setAnimation({ el: 'group', attr: { name: groupName }, container: parentContainer, component: dataset, label: 'group' }); }, /* * Gets the single Fill color. */ singleFillColorFn = function singleFillColorFn(color, defaultRadius) { var value = defaultRadius ? 1 : UNDEF; return (0, _lib.toRaphaelColor)({ color: (0, _lib.getFirstColor)(color.color, value), alpha: (0, _lib.getFirstAlpha)(color.alpha, value) }); }, /* * Function to get the exact visual position (top, left) of a element */ getContainerPosition = function getContainerPosition(el, noscroll) { var p = { left: 0, top: 0 }, clientRect; // for newer browsers if (el.getBoundingClientRect) { clientRect = el.getBoundingClientRect(); p.top = clientRect.top + (win.pageYOffset || doc.scrollTop || 0) - (doc.clientTop || 0); p.left = clientRect.left + (win.pageXOffset || doc.scrollLeft || 0) - (doc.clientLeft || 0); } else { // for very older browsers // iterate till the root element of the DOM to get the exact position of the element while (el) { p.left += el.offsetLeft || 0; p.top += el.offsetTop || 0; if (el !== doc.body && el !== doc.documentElement && !noscroll) { p.left -= el.scrollLeft || 0; p.top -= el.scrollTop || 0; } el = el.offsetParent; } } return p; }, getClickArcTangent = function getClickArcTangent(x, y, center, ref, pieYScale) { return mathATan2((y - center[1] - ref.top) / pieYScale, x - center[0] - ref.left); }, plotClickHandler = function plotClickHandler(dataSet, ele) { return function (e) { var plotItem = ele.data('plotItem'), seriesData = plotItem.seriesData; !seriesData.isRotating && dataSet.plotGraphicClick.call(ele, e); }; }, plotGraphicClick = function plotGraphicClick(dataset) { return function (evt) { var prevTextPos, o = this.element || this, plotItem = o.plotItem || o.data('plotItem'), elData = o.data('eventArgs') || {}, chart = plotItem.chart, animationManager = dataset.getFromEnv('animationManager'), index = plotItem.index, seriesData = dataset.config, enableMultiSlicing = seriesData.enableMultiSlicing, set = dataset.components.data[index], setGraphics = set.graphics, setConfig = set.config, doNotSlice = setConfig.doNotSlice, atleastOneOtherSliced, graphic, dataLabel, sliced, slicedTranslation = setConfig.slicedTranslation, transX, transY, connector, connectorPath, lastSliceTimeStamp, minTimeForNextSlice = 400, eventArgs, path; // call plotEvtHandler only when evt is defined.this is to prevent plotEventHandler // getting called when a plot is sliced in from sliceInOtherPies method. !seriesData.isRotating && evt && chart.plotEventHandler(o, evt); if (seriesData.isRotating || seriesData.singletonCase || doNotSlice) { return; } // If 'enableMultiSlicing' is false, sliceInOtherPies is called only once // for the clicked pie. From within sliceInOtherPies, 'enableMultiSlicing' // is set to true, method plotGraphicClick is called once for each // sliced pie and finally, value of 'enableMultiSlicing' is reset to false. // Value of multiSliced is always false for plotGraphicClick call from // sliceInOtherPies. However, its value may be true or false, by the // return value of the sliceInOtherPies. atleastOneOtherSliced = !enableMultiSlicing && dataset.sliceInOtherPies(index); if ((sliced = setConfig.sliced) && atleastOneOtherSliced) { return; } // // In chrome of hybrid touch devices (touch + mouse), slice is getting fired twice for single touch // To prevent this cancle slice event within very sort period // if (supportsTouch && !supportsOnlyTouch) { lastSliceTimeStamp = new Date().getTime(); if (plotItem.lastSliceTimeStamp && lastSliceTimeStamp - plotItem.lastSliceTimeStamp < minTimeForNextSlice) { return; } // store current time stamp plotItem.lastSliceTimeStamp = lastSliceTimeStamp; } graphic = setGraphics.element; connector = setGraphics.connector; dataLabel = setGraphics.label || setGraphics.dataLabel; slicedTranslation = (typeof slicedTranslation === 'undefined' ? 'undefined' : _typeof(slicedTranslation)) === 'object' ? 't' + slicedTranslation : slicedTranslation; connectorPath = setConfig.connectorPath; transX = (sliced ? -1 : 1) * setConfig.transX; transY = (sliced ? -1 : 1) * setConfig.transY; eventArgs = graphic.data(EVENTARGS) || graphic.data(EVENTARGS, {}); /** * This event is fired when a pieSlice in pie-chart starts slicing transition. * * @event FusionCharts#slicingStart * @group chart:pie-slice * * @param { object} data - Contains the values for the following * attributes borderColor, borderWidth, * categoryLabel, dashStyle, displayValue, * hoverEffects (boolean), label, link, * rolloverProperties (boolean), sliced (boolean), * toolText, value (value of the sliced object) * @param { boolean} slicedState - Tells the state of the slice before * transition begins. The value is true for * sliced-out state and false for sliced-in state. */ chart.fireChartInstanceEvent('slicingStart', { slicedState: sliced, dataIndex: 'index' in elData && elData.index, data: dataset.getPlotData(index, sliced) }); animationManager.setAnimationState('slicing'); animationManager.setAnimation({ el: graphic, attr: { transform: sliced ? 't0,0' : slicedTranslation }, component: dataset, label: 'slice', callback: function callback() { /** * This event is fired when a pieSlice in pie-chart ends slicing transition. * * @event FusionCharts#slicingEnd * @group chart:pie-slice * * @param { object} data - Contains the values for the following * attributes borderColor, borderWidth, * categoryLabel, dashStyle, displayValue, * hoverEffects (boolean), label, link, * rolloverProperties (boolean), sliced (boolean), * toolText, value (value of the sliced object) * @param { boolean} slicedState - Tells the state of the slice * before transition begins. The value is true * for sliced-out state and false for * sliced-in state. */ chart.fireChartInstanceEvent('slicingEnd', { slicedState: sliced, dataIndex: 'index' in elData && elData.index, data: dataset.getPlotData(index, !sliced) }); } }); if (dataLabel && dataLabel.x) { if (!(prevTextPos = dataLabel.data('textPos'))) { prevTextPos = dataLabel.data('textPos', { x: dataLabel.x, y: dataLabel.y }); } animationManager.setAnimation({ el: dataLabel, attr: { x: dataLabel.x + (sliced ? 0 : transX), y: dataLabel.y + (sliced ? 0 : transY) }, label: 'label-sliced', component: dataset }); prevTextPos.x = dataLabel.x + (sliced ? 0 : transX); } if (connectorPath) { path = connectorPath.slice(0); path[1] += transX; path[2] += transY; path[4] += transX; path[5] += transY; path[6] += transX; path[7] += transY; animationManager.setAnimation({ el: connector, attr: { path: path }, label: 'connector-sliced', component: dataset }); setConfig.connectorPath = path; } // updating the slicing information. eventArgs.isSliced = sliced = setConfig.sliced = !sliced; // TODO: Enable center label feature related to enableMultiSlicing // if ((innerDiameter = plotItem.innerDiameter) && !enableMultiSlicing) { // (centerLabelConfig = sliced && plotItem.centerLabelConfig.label ? // plotItem.centerLabelConfig : dataset.centerLabelConfig) && // (centerLabelText = centerLabelConfig.label) && // chart.drawDoughnutCenterLabel (centerLabelText, plotItem.center[0], plotItem.center[1], // innerDiameter, innerDiameter, centerLabelConfig, true); // } return sliced; }; }, // handlers function that returns an object containing the event handler APIs. handlers = function handlers(dataset) { var animationManager = dataset.getFromEnv('animationManager'); return { 'plotDragMove': function plotDragMove(evt) { var o = this, plotItem = o.data('plotItem'), chart = plotItem.chart, evtData = evt.data, dx = evtData[0], dy = evtData[1], x = evtData[2], y = evtData[3], seriesData = plotItem.seriesData, datasetConf = dataset.config, angle; if (isNaN(dx) || isNaN(dy) || !datasetConf.enableRotation || seriesData.singletonCase || seriesData.isRightClicked) { return; } angle = getClickArcTangent.call(evt, x, y, seriesData.pieCenter, seriesData.chartPosition, 1); if (seriesData.dragStartAngle !== angle && !seriesData.isRotating) { seriesData.isRotating = true; /** * This event is fired on drag rotation start of pie chart. * * @event FusionCharts#rotationStart * @group chart:pie * * @param { number} startingAngle - Gives the value of the * startingAngle of the chart, when the chart * starts rotating */ chart.fireChartInstanceEvent('RotationStart', { startingAngle: seriesData._rotationalStartAngle = chart._startingAngle() }); } datasetConf.startAngle += angle - seriesData.dragStartAngle; seriesData.dragStartAngle = angle; seriesData.moveDuration = 0; // Check if already there is an initiation for visual updates. if (!datasetConf.updateInited) { // set the flag to truth value. datasetConf.updateInited = true; chart.addJob('pie_batch_rotate', chart._batchRotate || (chart._batchRotate = function () { // visually update the chart dataset._rotate(); // turn the flag to falsy after an interval datasetConf.updateInited = false; }), _schedular.priorityList.draw, { oneInAFrame: true }); } }, 'plotDragStart': function plotDragStart(evt) { var o = this, plotItem = o.data('plotItem'), chart = plotItem.chart, seriesData = plotItem.seriesData, datasetConf = dataset.config, button = (0, _lib.pluckNumber)(evt.button, evt.originalEvent.button), startingAng = -datasetConf.startAngle * rad2deg, angle, x = evt.data[0], y = evt.data[1]; seriesData.isRightClicked = !!(!_lib.touchEnabled && button !== 0 && button !== 1); if (!datasetConf.enableRotation || seriesData.isRightClicked) { return; } seriesData.isRotating = false; // Calculate chart's current position. Chart cotainer may be moved mean while seriesData.chartPosition = getContainerPosition(chart.getFromEnv('chart-container')); angle = getClickArcTangent.call(evt, x, y, seriesData.pieCenter, seriesData.chartPosition, 1); seriesData.dragStartAngle = angle; seriesData.startingAngleOnDragStart = startingAng; }, 'plotDragEnd': function plotDragEnd() { var o = this, plotItem = o.data('plotItem'), chart = plotItem.chart, dataSet = chart.getChildren('dataset')[0], dataSetConfig = dataSet.config, chartConfig = chart.config, seriesData = plotItem.seriesData, startingAng = -dataSetConfig.startAngle * rad2deg; if (seriesData.isRightClicked) { return; } chartConfig.clicked = true; if (!chart.disposed) { /* extend2 (chart.logic.chartInstance.jsVars._reflowData, reflowUpdate, true); */ dataset._rotate(); } delete chartConfig.clicked; if (seriesData.isRotating) { /* The events mouseup, dragend and click are raised in order. In order * to update the flag isRotating to false post click event, setTimeout * called, to take immediate effect, is programmed to update the flag. * Thus, the flag gets updated post the series of events, in effect. * NB: Click event is subscribed conditionally. */ setTimeout(function () { seriesData.isRotating = false; }, 0); /** * This event is fired on drag rotation end of pie chart. * * @event FusionCharts#rotationEnd * @group chart:pie * * @param { number} changeInAngle - Gives the value by how much * the chart was rotated * @param { number} startingAngle - Gives the value of the * startingAngle of the chart on rotation end. */ chart.fireChartInstanceEvent('RotationEnd', { startingAngle: (0, _lib.normalizeAngle)(startingAng, true), changeInAngle: startingAng - dataSetConfig.startingAngleOnDragStart }); } !seriesData.isHovered && dataset.config.handlersAPI.onPlotHover(o, false); }, 'plotRollOver': function plotRollOver(e) { var ele = this, plotItem = ele.plotItem || ele.data('plotItem'), chart = plotItem.chart, conf = plotItem.seriesData, dataset = chart.getDatasets()[0], animationManager = dataset.getFromEnv('animationManager'); if (!conf.isRotating) { chart.plotEventHandler(ele, e, ROLLOVER); dataset.config.handlersAPI.onPlotHover(ele, true, animationManager); } dataset.fireEvent('datasetrollover', plotItem); conf.isHovered = true; }, 'plotRollOut': function plotRollOut(e) { var ele = this, plotItem = ele.plotItem || ele.data('plotItem'), chart = plotItem.chart, conf = plotItem.seriesData, dataset = chart.getDatasets()[0]; if (!conf.isRotating) { chart.plotEventHandler(ele, e, ROLLOUT); dataset.config.handlersAPI.onPlotHover(ele, false); } dataset.fireEvent('datasetrollout', plotItem); conf.isHovered = false; }, 'onPlotHover': function onPlotHover(plot, hover) { var plotItem = plot.data('plotItem'), center = plotItem.center, rolloverProps = plotItem.rolloverProperties || {}, color = hover ? rolloverProps.color : plotItem.color, borderWidth = hover ? rolloverProps.borderWidth : plotItem.borderWidth, borderColor = hover ? rolloverProps.borderColor : plotItem.borderColor; if (color) { if (hover) { color.cx = center[0]; color.cy = center[1]; color.r = plotItem.radius; } rolloverProps.enabled && animationManager.setAnimation({ el: plotItem.graphic, component: dataset, attr: { fill: (0, _lib.toRaphaelColor)(color), 'stroke-width': borderWidth, 'stroke': borderColor } }); } } }; }, sortArrayByPoint = function sortArrayByPoint(a, b) { return a.point.value - b.point.value; }, sortArrayByAngle = function sortArrayByAngle(a, b) { return a.angle - b.angle; }, labelClickFn = function labelClickFn(chart, link) { link && chart.getFromEnv('linkClickFN') && chart.getFromEnv('linkClickFN').call({ link: link }, true); }, hideFn = function hideFn() { this.hide(); }, alignments = ['start', 'start', 'end', 'end'], alignCenter = 'middle', ySign = [-1, 1, 1, -1], xSign = [1, 1, -1, -1]; /** * function to Remove data plots if the number of current data plots/categories * is more than the existing ones. * @param {Object} datasetJSON JSON for dataset configurations */ function _trimData(datasetJSON) { if (!this.config.JSONData) { return; } var dataSet = this, i = void 0, len = void 0, removeDataArr = void 0, legend = dataSet.getFromEnv('legend'), config = void 0, prevData = dataSet.config.JSONData, prevDataLength = prevData.data && prevData.data.length, currDataLength = datasetJSON.data && datasetJSON.data.length || 0, dataDiff = prevDataLength - currDataLength; // Removing data plots if the number of current data plots/categories // is more than the existing ones. if (dataDiff > 0) { dataSet.removeData(currDataLength, dataDiff, false); } removeDataArr = dataSet.components.removeDataArr || []; for (i = 0, len = removeDataArr.length; i < len; i++) { config = removeDataArr[i].config; config.legendItemId && legend.disposeItem(config.legendItemId); } } (0, _dependencyManager.addDep)({ name: 'pie2dAnimation', type: 'animationRule', extension: _index2['default'] }); // Adding required shapes for chart. (0, _redraphaelShapes2['default'])(Raphael); /** * class definition for pie2d dataset chart API */ var Pie2DDataset = function (_AreaDataset) { _inherits(Pie2DDataset, _AreaDataset); /** * Constructor fn * @memberof Pie2DDataset */ function Pie2DDataset() { _classCallCheck(this, Pie2DDataset); var _this = _possibleConstructorReturn(this, _AreaDataset.call(this)); _this.plotGraphicClick = plotGraphicClick(_this); return _this; } /** * Sets the type of the component * @return {string} type */ Pie2DDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ Pie2DDataset.prototype.getName = function getName() { return 'pie2D'; }; /** * parse defualt configuration of the chart */ Pie2DDataset.prototype.__setDefaultConfig = function __setDefaultConfig() { _AreaDataset.prototype.__setDefaultConfig.call(this); this.config.doughnutradius = 0; }; /** * Function for parsing all the attributes and value given by the user at chart,dataset and set level. * This function is called once from the init() function of the Column class. * @param {Object} datasetJSON JSON for dataset configurations * @return {boolean} Indicates whether the configuration was successful or not */ Pie2DDataset.prototype.configureAttributes = function configureAttributes(datasetJSON) { if (!datasetJSON) { return false; } this.trimData(datasetJSON); this.config.JSONData = datasetJSON; var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, // dataLabelStyle = chartConfig.dataLabelStyle, conf = dataSet.config, JSONData = dataSet.config.JSONData, chartAttr = dataSet.getFromEnv('chart-attrib'), is3D = chart.config.is3D, radius3D = void 0, use3DLighting = void 0, toolTipSepChar = void 0, enableMultiSlicing = void 0, enableAnimation = void 0; // Set all the handler APIs in the config of dataset. conf.handlersAPI = handlers(dataSet); dataSet.setState('visible', (0, _lib.pluckNumber)(dataSet.config.JSONData.visible, !Number(dataSet.config.JSONData.initiallyhidden), 1) === 1); (0, _lib.parseConfiguration)({}, dataSet.config, chart && chart.config); enableAnimation = conf.enableAnimation = (0, _lib.pluckNumber)(chartAttr.animation, chartAttr.defaultanimation, 1); conf.animation = !enableAnimation ? false : { duration: (0, _lib.pluckNumber)(chartAttr.animationduration, chartAttr.moveduration, 1) * 1000 }; conf.transposeAnim = !enableAnimation && !(0, _lib.pluckNumber)(conf.transposeanimation, 1) ? false : { duration: (0, _lib.pluckNumber)(chartAttr.transposeanimduration, 0.2) * 1000 }; conf.showPlotBorder = (0, _lib.pluckNumber)(chartAttr.showplotborder, 1); conf.showHoverEffect = (0, _lib.pluckNumber)(chartAttr.plothovereffect, chartAttr.showhovereffect, UNDEF); conf.showTooltip = (0, _lib.pluckNumber)(chartAttr.showtooltip, 1); conf.toolText = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(JSONData.plottooltext, chartAttr.plottooltext))); // thickness of pie slice border enableMultiSlicing = conf.enableMultiSlicing = (0, _lib.pluckNumber)(chartAttr.enablemultislicing, 1); // whether to use 3d lighing effect on pie use3DLighting = conf.use3DLighting = (0, _lib.pluckNumber)(chartAttr.use3dlighting, 1); // radius of the pie 3d lighting effect radius3D = conf.radius3D = use3DLighting ? (0, _lib.pluckNumber)(chartAttr.radius3d, 90) : 100; // whether to show the zero values on pie conf.showZeroPies = (0, _lib.pluckNumber)(chartAttr.showzeropies, 1); conf.showPercentInToolTip = (0, _lib.pluckNumber)(chartAttr.showpercentintooltip, 1); conf.showLabels = (0, _lib.pluckNumber)(chartAttr.showlabels, 1); conf.showValues = (0, _lib.pluckNumber)(JSONData.showvalues, chartAttr.showvalues, 1); conf.showPercentValues = (0, _lib.pluckNumber)(chartAttr.showpercentvalues, chartAttr.showpercentagevalues, 0); toolTipSepChar = conf.toolTipSepChar = (0, _lib.pluck)(chartAttr.tooltipsepchar, chartAttr.hovercapsepchar, _lib.COMMASPACE); conf.labelSepChar = (0, _lib.pluck)(chartAttr.labelsepchar, toolTipSepChar); conf.pieBorderColor = (0, _lib.pluck)(chartAttr.plotbordercolor, chartAttr.piebordercolor); conf.pieBorderAlpha = (0, _lib.pluckNumber)(chartAttr.plotborderalpha, chartAttr.pieborderalpha); conf.pieBorderThickness = conf.showPlotBorder ? (0, _lib.pluckNumber)(chartAttr.plotborderthickness, chartAttr.pieborderthickness, chartConfig.plotborderthickness, 1) : 0; // length of the dash conf.plotDashLen = (0, _lib.pluckNumber)(chartAttr.plotborderdashlen, 5); // distance between dash conf.plotDashGap = (0, _lib.pluckNumber)(chartAttr.plotborderdashgap, 4); conf.showValueInLegend = (0, _lib.pluckNumber)(chartAttr.showvalueinlegend, 0); conf.showLabelInLegend = (0, _lib.pluckNumber)(chartAttr.showlabelinlegend, 1); conf.valueBeforeLabelInLegend = (0, _lib.pluckNumber)(chartAttr.valuebeforelabelinlegend, 0); conf.showValueAsPercentInLegend = (0, _lib.pluckNumber)(chartAttr.showvalueaspercentinlegend, 1); conf.legendSepChar = (0, _lib.pluck)(chartAttr.legendsepchar, ', '); conf.showvalues = (0, _lib.pluckNumber)(chartAttr.showvalues, 1); conf.chartPosition = (0, _lib.getPosition)(chart.getFromEnv('chart-container'), chart); conf.timerThreshold = 30; // radius3d can not be greater than 100 and can not be less than 0 if (radius3D > 100) { radius3D = 100; } if (radius3D < 0) { radius3D = 0; } // todo need to remove conf.showLegend = (0, _lib.pluckNumber)(chartAttr.showlegend, 0); conf.reverselegend = !(0, _lib.pluckNumber)(chartAttr.reverselegend, 0); // conf.alphaanimation = pluckNumber(chartAttr.alphaanimation, 1); // required in 3d chart.config.is3D = is3D; conf.pieYScale = (0, _lib.pluckNumber)(chartAttr.pieyscale, 40); if (conf.pieYScale < 1) { conf.pieYScale = 1; } // fix for FCXT-296 if (conf.pieYScale >= 100) { conf.pieYScale = 80; } conf.pieYScale /= 100; conf.pieSliceDepth = (0, _lib.pluckNumber)(chartAttr.pieslicedepth, 15); if (conf.pieSliceDepth < 1) { conf.pieSliceDepth = 1; } conf.managedPieSliceDepth = conf.pieSliceDepth; conf.enableMultiSlicing = !!enableMultiSlicing; conf.startAngle = (0, _lib.pluckNumber)(chartAttr.startingangle, 0) % 360 * -(pi / 180); // HCObj.chart.startingAngle = pluck(dataArr.length > 1 ? FCChartObj.startingangle : 0, 0); conf.usePerPointLabelColor = chartAttr.colorlabelsfromplot == _lib.ONESTRING; conf.reversePlotOrder = (0, _lib.pluckNumber)(chartAttr.reverseplotorder, 0); conf.animateClockWise = (0, _lib.pluckNumber)(chartAttr.animateclockwise, conf.reversePlotOrder); conf.showShadow = (0, _lib.pluckNumber)(chartAttr.showshadow, 1); conf.singletonCase = JSONData.data.length === 1; conf.valueTotal = 0; dataSet._setConfigure(); // add legend items chartConfig.showLegend && dataSet._addLegend(); }; /** * function to Remove data plots if the number of current data plots/categories * is more than the existing ones. * @param {Object} datasetJSON JSON for dataset configurations */ Pie2DDataset.prototype.trimData = function trimData(datasetJSON) { _trimData.call(this, datasetJSON); }; /** * parse and format display value, tooltext and other texts * @param {Object} dataJSON input data json * @param {Object} config config of plot */ Pie2DDataset.prototype._parseDisplayProperties = function _parseDisplayProperties(dataJSON, config) { var setTooltext, pValue, toolText = '', TTValue, value, labelText, displayValueText, displayValue, displayValueArgs, showValue, dataSet = this, chart = dataSet.getFromEnv('chart'), numberFormatter = dataSet.getFromEnv('number-formatter'), chartAttr = chart.getFromEnv('chart-attrib'), conf = dataSet.config, dataValue = (0, _lib.pluckNumber)(config.y, numberFormatter.getCleanValue(dataJSON.value, true)), totalValue = conf.valueTotal, showLabels = conf.showLabels, name = (0, _lib.parseUnsafeString)((0, _lib.pluck)(config.seriesName, dataJSON.label, dataJSON.name, _lib.BLANKSTRING)), showPercentValues = conf.showPercentValues, showPercentInToolTip = conf.showPercentInToolTip, labelSepChar = conf.labelSepChar, toolTipSepChar = conf.toolTipSepChar, showTooltip = conf.showTooltip; // Adding label, tooltext, and display value setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(dataJSON.tooltext, conf.toolText))); pValue = config.pValue = numberFormatter.percentValue(dataValue / totalValue * 100); value = config.value = numberFormatter.dataLabels(dataValue) || _lib.BLANKSTRING; labelText = (0, _lib.pluckNumber)(dataJSON.showlabel, showLabels) === 1 ? name : _lib.BLANKSTRING; displayValueText = (showValue = (0, _lib.pluckNumber)(dataJSON.showvalue, conf.showValues)) === 1 ? showPercentValues === 1 ? pValue : value : _lib.BLANKSTRING; TTValue = showPercentInToolTip ? pValue : value; displayValue = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)(dataJSON.displayvalue)); // red-1416 displayValueArgs = (0, _lib.pluck)(displayValue, name + labelSepChar + (showPercentValues ? pValue : value), _lib.BLANKSTRING); if (displayValue !== UNDEF && showValue) { displayValueText = displayValue; } else { // create the datalabel str if (displayValueText !== _lib.BLANKSTRING && labelText !== _lib.BLANKSTRING) { displayValueText = labelText + labelSepChar + displayValueText; } else { displayValueText = (0, _lib.pluck)(labelText, displayValueText); } } // Create the Tooltext if (showTooltip) { if (setTooltext !== UNDEF) { toolText = (0, _lib.parseTooltext)(setTooltext, [1, 2, 3, 5, 6, 7, 14, 24, 25], { formattedValue: value, label: name, yaxisName: (0, _lib.parseUnsafeString)(chartAttr.yaxisname), xaxisName: (0, _lib.parseUnsafeString)(chartAttr.xaxisname), percentValue: pValue, sum: numberFormatter.dataLabels(totalValue), unformattedSum: totalValue }, dataJSON, chartAttr); } else { toolText = name; if (toolText != _lib.BLANKSTRING) { toolText = toolText + toolTipSepChar + TTValue; } else { toolText = TTValue; } } } config.displayValue = displayValueText; config.displayValueArgs = displayValueArgs; config.toolText = toolText; config.seriesName = name; config.categoryLabel = name; }; /** * function to check whether text style attributes are present in the input json * @param {Object} dataJSON - input data json * @return {boolean} - whether text style attributes are present or not */ Pie2DDataset.prototype._isStyled = function _isStyled(dataJSON) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config; if (chartConfig.usedataplotcolorforlabels || dataJSON.labelbordercolor || dataJSON.labelbgcolor || dataJSON.labelborderthickness || dataJSON.labelborderalpha || dataJSON.labelalpha || dataJSON.labelfont || dataJSON.labelfontsize || dataJSON.labelfontcolor || dataJSON.labelfontalpha || dataJSON.labelalpha || dataJSON.labelfontbold || dataJSON.labelfontitalic || dataJSON.labelborderpadding || dataJSON.labelborderradius || dataJSON.labelbgalpha || dataJSON.labelborderdashed || dataJSON.labelborderdashlen || dataJSON.labelborderdashgap) { return true; } }; /** * Function for parsing all the attributes and value given by the user at set level. * This function is called once from the configure() function of the Column class. * @param {Object} newDataset JSON for dataset configurations for new data only in a case of realtime chart * @param {number} newIndex JSON for dataset configurations for new data only in a case of realtime chart */ Pie2DDataset.prototype._setConfigure = function _setConfigure(newDataset, newIndex) { var index, name, setColor, setAlpha, borderConfig, setPlotBorderColor, setPlotBorderAlpha, pointShadow, legendText, legValue, isSliced, centerLabelConfig, setBorderDashed, pointDashStyle, dataObj, tempIndex, config, dataValue, dataConfig, dataJSON, dataSet = this, dataSetComponents = dataSet.components, removeDataArr = dataSetComponents.removeDataArr = dataSetComponents.removeDataArr || [], chart = dataSet.getFromEnv('chart'), chartAttr = chart.getFromEnv('dataSource').chart, chartConfig = chart.config, conf = dataSet.config, JSONData = dataSet.config.JSONData, setDataArr = (newDataset || JSONData).data, setDataLen = setDataArr && setDataArr.length, showZeroPies = conf.showZeroPies, totalValue = conf.valueTotal || 0, dataArr = [], // dataLabelStyle = parsexAxisStyles({}, {}, chartAttr, chartConfig.dataLabelStyle, setColor), plotBorderDash = (0, _lib.pluckNumber)(chartAttr.plotborderdashed, 0), dataStore = dataSet.components.data || (dataSet.components.data = []), numberFormatter = dataSet.getFromEnv('number-formatter'), colorM = dataSet.getFromEnv('color-manager'), labelInLeg = conf.labelInLeg, valInLeg = conf.valInLeg, // seriesCenterLabelConfig = conf.centerLabelConfig, setBorderWidth = conf.pieBorderThickness, reversePlotOrder = conf.reversePlotOrder, radius3D = conf.radius3D, enableMultiSlicing = conf.enableMultiSlicing, lastSlicedid = conf.lastSlicedid || 0, // length of the dash seriesDashLen = (0, _lib.pluckNumber)(chartAttr.plotBorderDashed, 5), // distance between dash seriesDashGap = (0, _lib.pluckNumber)(chartAttr.plotborderdashgap, 4), valBefore = (0, _lib.pluckNumber)(chartAttr.valuebeforelabelinlegend, 0), valAsPerInLeg = (0, _lib.pluckNumber)(chartAttr.showvalueaspercentinlegend, 1), nullCount = 0, sepChar = (0, _lib.pluck)(chartAttr.legendsepchar, ', '); chartConfig.dataLabelStyle = (0, _lib.parsexAxisStyles)({}, {}, chartAttr, chartConfig.dataLabelStyle, setColor); /* if (!add && newDataset) { totalValue = conf.valueTotal = 0; } */ // Parsing the attributes and values at set level. for (index = 0; index < setDataLen; index += 1) { /**/ dataObj = setDataArr[index]; dataValue = numberFormatter.getCleanValue(dataObj.value, true); if (!(dataValue === null || !showZeroPies && dataValue === 0)) { /* if (!add && newDataset && newIndex) { totalValue = (conf.valueTotal += (dataValue - dataStore[newIndex].config.y)); } */ dataArr.push(dataObj); totalValue += dataValue; } else { nullCount += 1; } } !conf.singletonCase && (conf.singletonCase = setDataLen - nullCount === 1); if (nullCount && dataStore.length > setDataLen - nullCount) { for (index = dataStore.length - 1; nullCount > 0; index -= 1, nullCount -= 1) { if (dataStore[index]) { dataObj = dataStore[index]; dataConfig = dataObj.config; removeDataArr.push(dataObj); dataConfig.y = null; } } } if (totalValue === 0) { dataArr = []; } conf.valueTotal = totalValue; // counts the total number of labels conf.dataLabelCounter = 0; chartConfig.allPlotSliceEnabled = chartConfig.enableslicing; for (index = (setDataLen = dataArr.length) - 1; index >= 0; index -= 1) { // individual data obj // for further manipulation tempIndex = index; if (newDataset) { dataJSON = dataArr[index]; if (newIndex !== UNDEF) { tempIndex = newIndex + index; dataObj = dataStore[tempIndex]; } else { tempIndex = dataStore.length - setDataLen + index; dataObj = dataStore[tempIndex]; } } else { dataObj = dataStore[index] || (dataStore[index] = { graphics: {}, config: {} }); dataJSON = dataArr[index]; } config = dataObj && dataObj.config; if (!config) { config = dataStore[tempIndex].config = {}; } if (!dataObj.graphics) { dataStore[tempIndex].graphics = {}; } // Taking the value // we multiply the value with 1 to convert it to integer config.y = dataValue = numberFormatter.getCleanValue(dataJSON.value, true); // Label provided with data point config.seriesName = name = (0, _lib.parseUnsafeString)((0, _lib.pluck)(dataJSON.label, dataJSON.name, _lib.BLANKSTRING)); config.labellink = (0, _lib.pluck)(dataJSON.labellink, chartAttr.labellink); // parsing slice cosmetics attribute supplied in data points // Color for each slice setColor = (0, _lib.pluck)(dataJSON.color, colorM.getPlotColor(index)); // Alpha for each slice setAlpha = (0, _lib.pluck)(dataJSON.alpha, chartAttr.plotfillalpha, _lib.HUNDREDSTRING); borderConfig = config.borderConfig = dataSet._parseBorderConfig(setColor, setAlpha, dataJSON); // each slice border color setPlotBorderColor = borderConfig.setPlotBorderColor; // each slice border alpha setPlotBorderAlpha = borderConfig.setPlotBorderAlpha; // Used to set alpha of the shadow pointShadow = { opacity: mathMax(setAlpha, setPlotBorderAlpha) / 100 }; // Check if pre-sliced isSliced = Boolean((0, _lib.pluckNumber)(dataJSON.issliced, chartAttr.issliced, /* config.sliced, */0)); if (isSliced) { if (!enableMultiSlicing) { if (lastSlicedid !== -1) { dataStore[dataStore.length - lastSlicedid - 1].sliced = false; } conf.lastSlicedid = index; } conf.preSliced = isSliced; } setBorderDashed = (0, _lib.pluckNumber)(dataJSON.dashed, plotBorderDash); pointDashStyle = setBorderDashed ? (0, _lib.getDashStyle)((0, _lib.pluck)(dataJSON.dashlen, seriesDashLen), (0, _lib.pluck)(dataJSON.dashgap, seriesDashGap), setBorderWidth) : DASH_DEF; // parse all the toolText and display value related properties. dataSet._parseDisplayProperties(dataJSON, config); legendText = labelInLeg ? name : _lib.BLANKSTRING; if (valInLeg) { legValue = valAsPerInLeg ? numberFormatter.legendPercentValue(dataValue / totalValue * 100) : numberFormatter.legendValue(dataValue); legendText = valBefore ? legValue + (legendText && sepChar + legendText) : (legendText && legendText + sepChar) + legValue; } conf.dataLabelCounter += 1; // Add style for individual data labels of pie // check if there is indivual level cosmetics in the data Object. if (dataSet._isStyled(dataJSON)) { config.style = (0, _lib.parsexAxisStyles)(dataJSON, {}, chartAttr, chartConfig.dataLabelStyle, setColor); } else if (config.style) { // if there is a style already existant delete it. delete config.style; } config.showInLegend = legendText !== _lib.BLANKSTRING; // prevent legend item when no label config.isVisible = true; config.name = legendText; // config.legendCosmetics= this.parseLegendOptions(chartAttr, dataJSON), config.shadow = pointShadow; config.setColor = setColor; config.color = (0, _printColor2['default'])(setColor, setAlpha, radius3D, conf.doughnutradius); config._3dAlpha = setAlpha; config.borderColor = (0, _lib.convertColor)(setPlotBorderColor, setPlotBorderAlpha); config.borderWidth = setBorderWidth; config.link = (0, _lib.getValidValue)(dataJSON.link); config.sliced = isSliced; config.dashStyle = pointDashStyle; if (!(config.doNotSlice = (0, _lib.pluck)(dataJSON.enableslicing, chartConfig.enableslicing) != _lib.ONESTRING) && chartConfig.allPlotSliceEnabled === _lib.ZEROSTRING) { chartConfig.allPlotSliceEnabled = _lib.ONESTRING; } dataSet._parseHoverEffectOptions(index); config.centerLabelConfig = centerLabelConfig; config.radius3D = radius3D; } if (reversePlotOrder) { dataStore && dataStore.reverse(); } // /special conf for pie/doughnut conf.dataArr = dataArr; // Pass the configuration whether user wants to supress rotation. conf.enableRotation = dataStore.length > 1 ? (0, _lib.pluckNumber)(chartAttr.enablerotation, 1) : 0; }; /** * parse attributes related to hover effect * @param {number} index -index of data plot */ Pie2DDataset.prototype._parseHoverEffectOptions = function _parseHoverEffectOptions(index) { var highlight, hoverColor, hoverAlpha, hoverBorderColor, hoverBorderAlpha, hoverBorderThickness, isHoverColorString, highlightColors, hColorsLen, hColorsLoop, dataSet = this, chart = dataSet.getFromEnv('chart'), chartAttr = chart.getFromEnv('dataSource').chart, conf = dataSet.config, config = dataSet.components.data[index].config, JSONData = dataSet.config.JSONData, dataJSON = JSONData.data[index], setColor = config.setColor, setAlpha = config._3dAlpha, radius3D = conf.radius3D, borderConfig = config.borderConfig, setPlotBorderAlpha = borderConfig.setPlotBorderAlpha, setPlotBorderColor = borderConfig.setPlotBorderColor, setBorderWidth = conf.setBorderWidth, hoverEffect = (0, _lib.pluckNumber)(config.hovereffect, conf.showHoverEffect), hoverEffects = config.hoverEffects = { enabled: hoverEffect }; // Enable hover effect when any of the hover attributes are explicitly set if (hoverEffect === UNDEF) { hoverEffect = hoverEffects.enabled = (0, _lib.pluck)(dataJSON.hovercolor, JSONData.hovercolor, chartAttr.plotfillhovercolor, dataJSON.hoveralpha, JSONData.hoveralpha, chartAttr.plotfillhoveralpha, dataJSON.borderhovercolor, JSONData.borderhovercolor, chartAttr.plotborderhovercolor, dataJSON.borderhoveralpha, JSONData.borderhoveralpha, chartAttr.plotborderhoveralpha, chartAttr.plotfillhoveralpha, dataJSON.borderhoverthickness, JSONData.borderhoverthickness, chartAttr.plotborderhoverthickness, UNDEF) !== UNDEF; } // Parsing the hover effects only if showhovereffect is not 0. if (hoverEffect) { highlight = (0, _lib.pluckNumber)(dataJSON.highlightonhover, JSONData.highlight, chartAttr.highlight, 1); hoverColor = (0, _lib.pluck)(dataJSON.hovercolor, JSONData.hovercolor, chartAttr.plotfillhovercolor); if (hoverColor && highlight) { highlight = 0; } hoverColor = (0, _lib.pluck)(hoverColor, setColor); hoverAlpha = (0, _lib.pluck)(dataJSON.hoveralpha, JSONData.hoveralpha, chartAttr.plotfillhoveralpha, setAlpha); hoverBorderColor = (0, _lib.pluck)(dataJSON.borderhovercolor, JSONData.borderhovercolor, chartAttr.plotborderhovercolor, setPlotBorderColor); hoverBorderAlpha = (0, _lib.pluck)(dataJSON.borderhoveralpha, JSONData.borderhoveralpha, chartAttr.plotborderhoveralpha, chartAttr.plotfillhoveralpha, setPlotBorderAlpha); hoverBorderThickness = (0, _lib.pluckNumber)(dataJSON.borderhoverthickness, JSONData.borderhoverthickness, chartAttr.plotborderhoverthickness, setBorderWidth); hoverColor.replace(/,+?$/, ''); if (highlight === 1) { isHoverColorString = typeof hoverColor === 'string'; highlightColors = isHoverColorString ? hoverColor.split(/\s{0,},\s{0,}/) : hoverColor.color.split(/\s{0,},\s{0,}/); hColorsLen = highlightColors.length; for (hColorsLoop = 0; hColorsLoop < hColorsLen; hColorsLoop++) { highlightColors[hColorsLoop] = (0, _lib.getLightColor)(highlightColors[hColorsLoop], 70); } if (isHoverColorString) { hoverColor = highlightColors.join(','); } else { hoverColor.color = highlightColors.join(','); } } dataSet._setHoverColor(hoverEffects, hoverColor, hoverAlpha, radius3D); hoverEffects.alpha = hoverAlpha; hoverEffects.borderColor = (0, _lib.convertColor)(hoverBorderColor, hoverBorderAlpha); hoverEffects.borderAlpha = hoverBorderAlpha; hoverEffects.borderWidth = hoverBorderThickness; } else { hoverEffects.enabled = false; } }; /** * It draws data labels * @param {boolean} isRotating state; if pie is rotating or not * @param {Array} plotItems array of datapots * @param {Object} plot config of data plot * @param {Object} seriesData contains pie center center co-ordinates and radius * @param {Object} anim anim object */ Pie2DDataset.prototype.placeDataLabels = function placeDataLabels(isRotating, plotItems, plot, seriesData) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, animationManager = dataSet.getFromEnv('animationManager'), toolTipController = dataSet.getFromEnv('toolTipController'), legend = chart.getChildren('legend')[0], legendConfig, legendWidth, legendAlign, legendBorderwidth, labelGroup = dataSet.getContainer('label-group'), plotOptions = dataSet.config, canvasLeft = chartConfig.canvasLeft, canvasTop = chartConfig.canvasTop, canvasWidth = chartConfig.canvasWidth, cx = canvasLeft + chartConfig.canvasWidth * 0.5, cy = canvasTop + chartConfig.canvasHeight * 0.5, smartLabel = chart.getFromEnv('smartLabel'), dataLabelsOptions = plotOptions.dataLabelOptions, style = dataLabelsOptions.style, lineHeight = (0, _lib.pluckNumber)(mathCeil(parseFloat(style.lineHeight)), 12), placeInside = plotItems.length === 1 ? chartConfig.singletonPlaceValue : false, skipOverlapLabels = dataLabelsOptions.skipOverlapLabels, manageLabelOverflow = dataLabelsOptions.manageLabelOverflow, connectorPadding = dataLabelsOptions.connectorPadding, distanceOption = dataLabelsOptions.distance, remainingHeight, seriesCenter = seriesData && seriesData.metrics || [cx, cy, 2 * plotOptions.pieMinRadius, plotOptions.innerSize || 0], centerY = seriesCenter[1], centerX = seriesCenter[0], radius = seriesCenter[2] * 0.5, // divide the points into quarters for anti collision quarters = [[], // top right [], // bottom right [], // bottom left [] // top left ], plotLeft = canvasLeft, plotTop = canvasTop, plotWidth = canvasWidth, dataLabelsRadius = plot.labelsRadius = radius + distanceOption, labelFontSize = parseInt(style.fontSize, 10), labelHeight = labelFontSize, halfLabelHeight = labelHeight / 2, xDisplacement = [connectorPadding, connectorPadding, -connectorPadding, -connectorPadding], maxLabels = plot.labelsMaxInQuadrant = mathFloor(dataLabelsRadius / labelHeight), isSmartLineSlanted = dataLabelsOptions.isSmartLineSlanted, innerRadius = seriesCenter[3] / 2, align, i, labelWidth, j, oriY, maxYmayHave, spaceRequired, length, k, sliced, x1, x2, x3, x4, y1, y2, y3, points, point, angle, connector, connectorPath, excess, excessArr, labelQuadrantHeight, maxQuadrantLabel, dataLabel, dataLabelCheck, quarter, transX, transY, smartLabelObj, slicedTranslation, centerDistance, sameSideQuadrentLastY = Number.POSITIVE_INFINITY, extraLineSpaceComp, lPoint, pointConfig, pointGraphics, leftClubbedQuadrent = [], rightClubbedQuadrent = [], prevTextPos, prevConnectorPos, plotDragStart = plotOptions.handlersAPI.plotDragStart, plotDragEnd = plotOptions.handlersAPI.plotDragEnd, plotDragMove = plotOptions.handlersAPI.plotDragMove, plotRollOver = plotOptions.handlersAPI.plotRollOver, plotRollOut = plotOptions.handlersAPI.plotRollOut, // paper = dataSet.getFromEnv('paper'), _textAttrs, _textCss, _textAttrsWithXY, cloneOb = function cloneOb(ob) { var clonedOb = {}, key = ''; for (key in ob) { clonedOb[key] = ob[key]; } return ob; }, applyAttrFnGen = function applyAttrFnGen(el, attr) { return function () { el.attr(attr); }; }; if (legend) { legendConfig = legend.config; legendWidth = legendConfig.symbolWidth; legendAlign = legendConfig.align; legendBorderwidth = legendConfig.borderWidth; } else { legendWidth = 0; legendAlign = 0; legendBorderwidth = 0; } // run parent method /** ^ * Introduced the isRotating argument too to detect * whether this is called during rotation. */ smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); if (!isRotating) { // do not set the style every time // Do it for first time smartLabel.setStyle(style); } // arrange points for detection collision // Creates an array of quarter containing labels of each // quarter if there has only one label the draw it inside if (!innerRadius && plotOptions.singletonCase && placeInside) { point = plotItems[0]; if ((_textAttrs = point.config._textAttrs).text) { pointGraphics = point.graphics; pointConfig = point.config; dataLabelCheck = pointGraphics.label; point.slicedTranslation = [plotLeft, plotTop]; _textAttrs['text-anchor'] = alignCenter; _textAttrs.x = 0; _textAttrs.y = 0; _textAttrs.transform = ['t', centerX, centerY]; dataLabel = animationManager.setAnimation({ el: dataLabelCheck || 'text', attr: _textAttrs, component: dataSet, css: _textCss, label: 'label', container: labelGroup }); if (!dataLabelCheck) { pointGraphics.label = dataLabel; dataLabel.on('fc-dragstart', plotDragStart).on('fc-dragmove', plotDragMove).on('fc-dragend', plotDragEnd).on('fc-click', labelClickFn.bind(dataLabel, chart, point.config.labellink)).on('fc-click', plotClickHandler(dataSet, dataLabel)).on('fc-mouseover', plotRollOver).on('fc-mouseout', plotRollOut); } dataLabel.x = centerX; dataLabel.data('textPos', { x: centerX, y: centerY }).data('plotItem', _textAttrs.plotItem).data(EVENTARGS, _textAttrs.eventArgs); if (pointConfig.y !== null && pointConfig.y !== UNDEF) { dataLabel.show(); } if (pointGraphics.connector) { animationManager.setAnimation({ el: pointGraphics.connector, component: dataSet, attr: { path: [] } }); } } } else { if (placeInside) { centerDistance = innerRadius + (radius - innerRadius) / 2; (0, _lib.fcEach)(plotItems, function (point) { pointConfig = point.config; if ((_textAttrs = pointConfig._textAttrs).text) { pointGraphics = point.graphics; dataLabelCheck = pointGraphics.label; if (pointConfig.y !== null && pointConfig.y !== UNDEF) { connector = pointGraphics.connector; connector && connector.show(); dataLabel && dataLabel.show(); } _textAttrs.transform = 't0,0'; angle = pointConfig.angle; y3 = centerY + centerDistance * mathSin(angle); // previous implementation adds halfLebelHeight - 2 which makes the // label aligned to top instead middle [RED - 1717] /* y3 = centerY + (centerDistance * mathSin (angle)) + halfLabelHeight - 2; */ x3 = centerX + centerDistance * mathCos(angle); _textAttrs._x = x3; _textAttrs._y = y3; if (point.sliced) { slicedTranslation = point.slicedTranslation; transX = slicedTranslation[0] - plotLeft; transY = slicedTranslation[1] - plotTop; x3 = x3 + transX; y3 = y3 + transY; } _textAttrs['text-anchor'] = alignCenter; _textAttrs.x = 0; _textAttrs.y = 0; _textAttrs.transform = ['t', x3, y3]; dataLabel = animationManager.setAnimation({ el: dataLabelCheck || 'text', attr: _textAttrs, component: dataSet, label: 'label', css: _textCss, container: labelGroup }); if (!dataLabelCheck) { pointGraphics.label = dataLabel; dataLabel.on('fc-dragstart', plotDragStart).on('fc-dragmove', plotDragMove).on('fc-dragend', plotDragEnd).on('fc-click', labelClickFn.bind(dataLabel, chart, point.config.labellink)).on('fc-click', plotClickHandler(dataSet, dataLabel)).on('fc-mouseover', plotRollOver).on('fc-mouseout', plotRollOut); } dataLabel.x = _textAttrs._x; // storing original x value // to use while slicing in (IE Issue original // x get changed form animate) dataLabel.x = _textAttrs._x; dataLabel.y = _textAttrs._y; dataLabel.data('plotItem', _textAttrs.plotItem).data(EVENTARGS, _textAttrs.eventArgs); if (_textAttrs.visibility === VISIBLE) { dataLabel.show(); } } }); } else { // outside for (i = plotItems.length - 1; i >= 0; i--) { point = plotItems[i]; pointConfig = point.config; _textAttrs = pointConfig._textAttrs || {}; if (!(_textAttrs.text = pointConfig.displayValue)) { point.graphics.connector && (point.graphics.connector = animationManager.setAnimation({ el: point.graphics.connector, component: dataSet })); point.graphics.label && (point.graphics.label = animationManager.setAnimation({ el: point.graphics.label, component: dataSet, callback: hideFn })); continue; } pointGraphics = point.graphics; if (pointConfig.y !== null && pointConfig.y !== UNDEF) { dataLabel = pointGraphics.label; connector = pointGraphics.connector; connector && connector.show(); dataLabel && dataLabel.show(); } _textAttrs.text = pointConfig.displayValue; _textAttrs.transform = 't0,0'; angle = pointConfig.angle % pi2; if (angle < 0) { angle = pi2 + angle; } // Calculate bottom right quarter labels if (angle >= 0 && angle < piBy2) { quarter = 1; } else // Calculate bottom left quarter labels if (angle < pi) { quarter = 2; } else // Calculate top left quarter labels if (angle < pi3By2) { quarter = 3; } else { // Calculate top right quarter labels quarter = 0; } // Now put labels according to each quarter quarters[quarter].push({ point: point, angle: angle }); } i = k = 4; // if excess then remove the low value slice first while (i--) { if (skipOverlapLabels) { // Find labels can fit into the quarters or not excess = quarters[i].length - maxLabels; if (excess > 0) { // sort by point.value quarters[i].sort(sortArrayByPoint); // remove extra data form the array // which labels can not be fitted into // the quarters excessArr = quarters[i].splice(0, excess); // hide all removed labels for (j = 0, length = excessArr.length; j < length; j += 1) { point = excessArr[j].point; _textAttrs = point.config._textAttrs; pointGraphics = point.graphics; if (pointGraphics.label) { pointGraphics.label = animationManager.setAnimation({ el: pointGraphics.label, component: dataSet }); } if (pointGraphics.connector) { pointGraphics.connector = animationManager.setAnimation({ el: pointGraphics.connector, component: dataSet }); } } } } // now we sort the data labels by its label angle quarters[i].sort(sortArrayByAngle); } maxQuadrantLabel = mathMax(quarters[0].length, quarters[1].length, quarters[2].length, quarters[3].length); labelQuadrantHeight = mathMax(mathMin(maxQuadrantLabel, maxLabels) * labelHeight, dataLabelsRadius + labelHeight); // Club the first and second quadrent as they appear in the right side of the // chart and club the other two. Clubbing here means merge all the points together // so that marginal quadrent case are handled like one point at first quadrent and // second point at another quadrent but placed closely. rightClubbedQuadrent = quarters[0].concat(quarters[1]); leftClubbedQuadrent = quarters[2].concat(quarters[3]); for (i = rightClubbedQuadrent.length - 1; i >= 0; i--) { lPoint = rightClubbedQuadrent[i].point.config; // Clear if any previous values are stored delete lPoint.clearance; delete lPoint.clearanceShift; oriY = mathAbs(labelQuadrantHeight * mathSin(lPoint.angle)); if (Math.abs(sameSideQuadrentLastY - oriY) < lineHeight * 2) { lPoint.clearance = 0; rightClubbedQuadrent[i + 1].point.clearanceShift = lineHeight / 2; } sameSideQuadrentLastY = oriY; } sameSideQuadrentLastY = Number.POSITIVE_INFINITY; for (i = 0, length = leftClubbedQuadrent.length; i < length; i++) { lPoint = leftClubbedQuadrent[i].point.config; // Clear if any previous values are stored delete lPoint.clearance; delete lPoint.clearanceShift; oriY = mathAbs(labelQuadrantHeight * mathSin(lPoint.angle)); if (Math.abs(sameSideQuadrentLastY - oriY) < lineHeight * 2) { lPoint.clearance = 0; leftClubbedQuadrent[i - 1].point.clearanceShift = lineHeight / 2; } sameSideQuadrentLastY = oriY; } // reverse 1st and 3rd quardent points quarters[1].reverse(); quarters[3].reverse(); while (k--) { points = quarters[k]; length = points.length; if (!skipOverlapLabels) { if (length > maxLabels) { labelHeight = labelQuadrantHeight / length; } else { labelHeight = labelFontSize; } halfLabelHeight = labelHeight / 2; } // 1st pass // place all labels at 1st quarter // calculate the total available space to put labels spaceRequired = length * labelHeight; // calculate the remaining height remainingHeight = labelQuadrantHeight; // place all child point for (i = 0; i < length; i += 1, spaceRequired -= labelHeight) { // Get the y position of the label (radius // where data label is to draw) oriY = mathAbs(labelQuadrantHeight * mathSin(points[i].angle)); if (remainingHeight < oriY) { oriY = remainingHeight; } else if (oriY < spaceRequired) { oriY = spaceRequired; } remainingHeight = (points[i].oriY = oriY) - labelHeight; } // 2nd pass (reverse) align = alignments[k]; // place all labels at 1st quarter maxYmayHave = labelQuadrantHeight - (length - 1) * labelHeight; remainingHeight = 0; // place all child point for (i = points.length - 1; i >= 0; i -= 1, maxYmayHave += labelHeight) { point = points[i].point; angle = points[i].angle; pointConfig = point.config; _textAttrs = pointConfig._textAttrs || {}; if (!_textAttrs.text) { continue; } _textCss = pointConfig._textCss; _textCss.cursor = pointConfig.labellink ? 'pointer' : ''; pointGraphics = point.graphics; sliced = pointConfig.sliced; dataLabel = pointGraphics.label; oriY = mathAbs(labelQuadrantHeight * mathSin(angle)); if (oriY < remainingHeight) { oriY = remainingHeight; } else if (oriY > maxYmayHave) { oriY = maxYmayHave; } remainingHeight = oriY + labelHeight; // If the there is a label down underneath or // bordered put elipses else wrap the word. extraLineSpaceComp = pointConfig.clearance === UNDEF ? mathCeil((0, _lib.pluckNumber)(parseFloat(pointConfig.style.border), 12), 12) * 2 : mathCeil((0, _lib.pluckNumber)(parseFloat(pointConfig.style.border), pointConfig.clearance)) * 2; y1 = (oriY + points[i].oriY) / 2; x1 = centerX + xSign[k] * dataLabelsRadius * mathCos(math.asin(y1 / labelQuadrantHeight)); y1 *= ySign[k]; y1 += centerY; y2 = centerY + radius * mathSin(angle); x2 = centerX + radius * mathCos(angle); // Relation: centerX <= connectorStartX <= connectorEndX // (for right half and vice versa for left half) (k < 2 && x1 < x2 || k > 1 && x1 > x2) && (x1 = x2); x3 = x1 + xDisplacement[k]; y3 = y1 - halfLabelHeight - 2; x4 = x3 + xDisplacement[k]; _textAttrs._x = x4; if (manageLabelOverflow) { labelWidth = k > 1 ? x4 - chartConfig.canvasLeft : chartConfig.canvasLeft + plotWidth - x4; smartLabel.setStyle(pointConfig.style); lineHeight = (0, _lib.pluckNumber)(mathCeil(parseFloat(pointConfig.style.lineHeight)), 12) + extraLineSpaceComp; // decrease the labelwidth of the legend text if legend position is right and // x translation is positive if (legendAlign === 'right' && pointConfig.transX > 0) { labelWidth -= legendWidth + legendBorderwidth * 2; } else if (legendAlign !== 'right' && pointConfig.transY > 0) { // decrease the y position of the legend text if legend position is below and // y translation is positive y1 -= labelHeight; } smartLabelObj = smartLabel.getSmartText(pointConfig.displayValue, labelWidth, lineHeight); if (pointConfig.clearance === UNDEF && smartLabelObj.height > labelHeight) { y1 += labelHeight; } _textAttrs.text = smartLabelObj.text; // _textAttrs.title = smartLabelObj.tooltext || ''; _textAttrs.tooltip = smartLabelObj.tooltext; /* dataLabel.attr ( { text: smartLabelObj.text //title: (smartLabelObj.tooltext || '') }) .tooltip (smartLabelObj.tooltext); */ } _textAttrs._y = y1; if (sliced) { transX = pointConfig.transX; transY = pointConfig.transY; x3 = x3 + transX; x1 = x1 + transX; x2 = x2 + transX; y2 = y2 + transY; y1 = y1 + transY; y3 = y3 + transY; x4 = x4 + transX; } _textAttrs['text-anchor'] = align; _textAttrs.vAlign = 'middle'; _textAttrs.opacity = 1; _textAttrs.x = x4; _textAttrs.y = y1; prevTextPos = dataLabel && dataLabel.data('textPos'); // Skip when valid value is not provided if (pointConfig.y !== null && pointConfig.y !== UNDEF) { if (prevTextPos) { _textAttrsWithXY = cloneOb(_textAttrs); animationManager.setAnimation({ el: dataLabel, attr: _textAttrsWithXY, callback: applyAttrFnGen(dataLabel, _textAttrs), component: dataSet }); } else { // for the initial rendering. dataLabel = pointGraphics.label = animationManager.setAnimation({ el: 'text', attr: _textAttrs, css: _textCss, label: 'label', container: labelGroup, component: dataSet }); dataLabel.on('fc-dragstart', plotDragStart).on('fc-dragmove', plotDragMove).on('fc-dragend', plotDragEnd).on('fc-click', labelClickFn.bind(dataLabel, chart, point.config.labellink)).on('fc-click', plotClickHandler(dataSet, dataLabel)).on('fc-mouseover', plotRollOver).on('fc-mouseout', plotRollOut); } } dataLabel.x = _textAttrs._x; dataLabel._x = _textAttrs._x; dataLabel.y = _textAttrs._y; if (_textAttrs.tooltip) { toolTipController.enableToolTip(dataLabel, _textAttrs.tooltip); delete _textAttrs.tooltip; } if (_textAttrs.visibility === VISIBLE) { dataLabel.show(); } dataLabel.data('textPos', { x: x4, y: y1 }).data('plotItem', _textAttrs.plotItem).data(EVENTARGS, _textAttrs.eventArgs); // draw the connector if (connector = pointGraphics.connector) { pointConfig.connectorPath = connectorPath = [M, x2, y2, // base L, // first break, next to the label isSmartLineSlanted ? x1 : x2, y1, x3, y1 // end of the string at the label ]; prevConnectorPos = connector.data('connectorPath'); if (prevConnectorPos) { if (!chartConfig.clicked) { animationManager.setAnimation({ el: connector, attr: { path: connectorPath }, label: 'connector', component: dataSet }); } } else { animationManager.setAnimation({ el: connector, attr: { path: connectorPath }, label: 'connector', component: dataSet }); } connector.data('connectorPath', { path: connectorPath }); } } } } } }; /** * set hover effect depending on the 3D lighting mode * @param {Object} hoverEffects conatins hover effects * @param {string} hoverColor color string * @param {number} hoverAlpha color alpha * @param {boolean} radius3D if 3D Lighting Mode is on */ Pie2DDataset.prototype._setHoverColor = function _setHoverColor(hoverEffects, hoverColor, hoverAlpha, radius3D) { var dataSet = this; if (radius3D) { hoverEffects.color = (0, _printColor2['default'])(hoverColor, hoverAlpha, radius3D, dataSet.config.doughnutradius); } else { hoverEffects.color = hoverColor; hoverEffects.alpha = hoverAlpha; } }; /** * Function to an existing data of a dataset. * @param {Object} dataObj data JSON * @param {integer} index The data index whoch needs to be updated * @param {boolean} draw Indicates whether the chart should redraw itself or not */ Pie2DDataset.prototype.updateData = function updateData() { var dataSet = this, conf = dataSet.config, dataStore = dataSet.components.data; conf.valueTotal -= dataStore[arguments[1]].config.y; _AreaDataset.prototype.updateData.call(this, arguments); }; /** * function to rotate pie slices */ Pie2DDataset.prototype._rotate = function _rotate() { var _ringPath, _rotateAttrs, dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, plotData = dataSet.components.data, chartConfig = chart.config, piePlotOptions = conf.piePlotOptions, startAngle = (conf.startAngle || 0) % pi2, slicedOffset = conf.slicingDistance, valueTotal = conf.valueTotal, factor = pi2 / valueTotal, cx = chartConfig.canvasLeft + chartConfig.canvasWidth * 0.5, cy = chartConfig.canvasTop + chartConfig.canvasHeight * 0.5, r = conf.pieMinRadius, r2 = (piePlotOptions.innerSize || 0) * 0.5, val, angle, angle1, angle2, setConfig, setGraphics, i; angle1 = angle2 = startAngle; for (i = 0; i < plotData.length; i += 1) { setConfig = plotData[i].config; setGraphics = plotData[i].graphics; val = setConfig.y; if (val === null || val === UNDEF) { continue; } // plotItem = plotItems[i]; angle2 = angle1; // This conditional assignment of value 2 * pi is to by-pass a // computational error inherent to any computer system, which // happens here for certain values in singleton cases. angle1 -= !conf.singletonCase ? val * factor : pi2; angle = (angle1 + angle2) * 0.5; setConfig.angle = angle; setConfig.transX = mathCos(angle) * slicedOffset; setConfig.transY = mathSin(angle) * slicedOffset; setConfig.slicedTranslation = TRANSFORMSTR + mathCos(angle) * slicedOffset + _lib.COMMASTRING + mathSin(angle) * slicedOffset; if (!(_rotateAttrs = setConfig._rotateAttrs)) { _rotateAttrs = setConfig._rotateAttrs = { ringpath: [], transform: _lib.BLANKSTRING }; } _ringPath = _rotateAttrs.ringpath; _ringPath[0] = cx; _ringPath[1] = cy; _ringPath[2] = r; _ringPath[3] = r2; _ringPath[4] = angle1; _ringPath[5] = angle2; setGraphics.element.attr({ ringpath: _rotateAttrs.ringpath, transform: setConfig.sliced ? setConfig.slicedTranslation : '' }); } dataSet.placeDataLabels(true, plotData, conf); }; /** * function to fetch radius and slice offset * @return {Object} contains radius and slice offset */ Pie2DDataset.prototype._parsePiePlotOptions = function _parsePiePlotOptions() { var dataSet = this, conf = dataSet.config; return { size: conf.pieMinRadius, slicedOffset: conf.slicingDistance }; }; /** * function to fetch data label style as object * @return {Object} contains data label style */ Pie2DDataset.prototype._parseDataLabelOptions = function _parseDataLabelOptions() { return { style: this.getFromEnv('chart').config.dataLabelStyle }; }; /** * Function to register datasets in the internal data store of legend class. */ Pie2DDataset.prototype._addLegend = function _addLegend() { var i, config, dataObj, dataset = this, legend = dataset.getFromEnv('legend'), legendItem, configObject, dataStore = dataset.components.data; for (i = 0; i < dataStore.length; i++) { dataObj = dataStore[i]; config = dataObj.config; if (config.y !== null && config.seriesName) { // If seriesName is valid and y is not null, legend item can be drawn configObject = { index: i, type: dataset.getName(), label: config.seriesName, enabled: (0, _lib.pluckNumber)(config.includeInLegend, 1) }; legendItem = legend.getItem(config.legendItemId); if (!legendItem) { config.legendItemId = legend.createItem(dataset); legendItem = legend.getItem(config.legendItemId); dataset.addExtEventListener('fc-click', legendItem.itemClickFn, legendItem); } legendItem.configure(configObject); legendItem.setStateCosmetics('default', { symbol: { fill: (0, _lib.toRaphaelColor)(config.setColor), rawFillColor: config.setColor, stroke: (0, _lib.toRaphaelColor)(config.borderColor) } }); } else { // else, legend item should not be drawn. If legend item is present, it should be disposed if (!config.legendItemId) { continue; } legendItem = legend.getItem(config.legendItemId); legendItem && legend.disposeItem(legendItem.getId()); delete config.legendItemId; } } }; /** * fetches data plot from data store * @param {number} id - index of data plot which is to be fetched * @param {boolean} slicedState - sliced or not * @return {Object} - data plot */ Pie2DDataset.prototype.getPlotData = function getPlotData(id, slicedState) { var dataset = this, data = dataset.components.data[id].config, userData = dataset.config.userData || (dataset.config.userData = []), plotData, value, prop; if (!userData[id]) { plotData = userData[id] = {}; for (prop in data) { _typeof(value = data[prop]) !== 'object' && typeof value !== 'function' && prop.indexOf('_') !== 0 && (plotData[prop] = value); } plotData.value = plotData.y; plotData.categoryLabel = plotData.label = plotData.seriesName; delete plotData.y; delete plotData.total; delete plotData.doNotSlice; delete plotData.name; delete plotData.seriesName; delete plotData.centerAngle; delete plotData.showInLegend; delete plotData.angle; delete plotData.endAngle; delete plotData.isVisible; delete plotData.setColor; delete plotData.slicedTranslation; delete plotData.startAngle; delete plotData.transX; delete plotData.transY; delete plotData.pValue; } else { plotData = userData[id]; } plotData.sliced = slicedState; return plotData; }; /** * parse border cosmetics * @param {string} setColor color hex * @param {string} setAlpha aplha value * @param {Object} dataJSON data Object * @return {Object} contains plot border color and alpha */ Pie2DDataset.prototype._parseBorderConfig = function _parseBorderConfig(setColor, setAlpha, dataJSON) { var dataSet = this, conf = dataSet.config, pieBorderColor = conf.pieBorderColor, chart = dataSet.getFromEnv('chart'), chartAttr = chart.getFromEnv('dataSource').chart, // each slice border color setPlotBorderColor = (0, _lib.pluck)(dataJSON.bordercolor, pieBorderColor), // each slice border alpha setPlotBorderAlpha = (0, _lib.pluck)(dataJSON.borderalpha, chartAttr.plotborderalpha, chartAttr.pieborderalpha); setPlotBorderColor = (0, _lib.pluck)(setPlotBorderColor, (0, _lib.getLightColor)(setColor, 25)).split(_lib.COMMASTRING)[0]; setPlotBorderAlpha = chartAttr.showplotborder == _lib.ZEROSTRING ? _lib.ZEROSTRING : (0, _lib.pluck)(setPlotBorderAlpha, setAlpha, '80'); return { setPlotBorderColor: setPlotBorderColor, setPlotBorderAlpha: setPlotBorderAlpha }; }; Pie2DDataset.prototype.legendInteractivity = function legendInteractivity(legendItem) { var dataset = this, dataStore = dataset.components.data, len = void 0, i = void 0, legendItemId = legendItem.getId(), setGraphics = void 0, config = void 0; for (i = 0, len = dataStore.length; i < len; i++) { config = dataStore[i].config; if (config.legendItemId === legendItemId) { setGraphics = dataStore[i].graphics; dataset.plotGraphicClick.call(setGraphics.element); } } }; /** * Function to hide the graphics elements */ Pie2DDataset.prototype.hideElements = function hideElements() { var elem = this, chart = elem.data && elem.data('plotItem').chart, dataSet = chart.getChildren('dataset') && chart.getChildren('dataset')[0], i = 0, shadowArr = elem._ && elem._.shadows || []; if (dataSet) { elem.hide(); for (; i < shadowArr.length; i += 1) { shadowArr[i].hide(); } } }; // hideFn (graphic, type) { // return function () { // graphic[type].hide(); // }; // } /** * function to create group for dataset */ Pie2DDataset.prototype._createContainer = function _createContainer() { var dataset = this, // paper = dataset.getFromEnv('paper'), dsType = dataset.getName(), parentContainer = void 0, pieGroups = void 0, piePlotGroups = void 0, pieLabelGroups = void 0, groupName = dataset.groupName, parent = dataset.getLinkedParent(), group = groupName || dataset.dsGroup || dsType; !parent.getChildContainer(group + 'Group') && (group = 'default'); parentContainer = parent.getChildContainer('datalabelsGroup'); // Add all neccessary containers to the dataset pieGroups = dataset.getContainer('pie-groups') || dataset.addContainer('pie-groups', createGroup('pie', parentContainer, dataset)); piePlotGroups = dataset.getContainer('pie-plot-groups') || dataset.addContainer('pie-plot-groups', createGroup('pie-plot', pieGroups, dataset)); pieLabelGroups = dataset.getContainer('pie-label-groups') || dataset.addContainer('pie-label-groups', createGroup('pie-label', pieGroups, dataset)); dataset.getContainer('plot-group') || dataset.addContainer('plot-group', createGroup('plots', piePlotGroups, dataset)); dataset.getContainer('plot-shadow-group') || dataset.addContainer('plot-shadow-group', createGroup('plot-shadows', piePlotGroups, dataset).toBack()); dataset.getContainer('label-group') || dataset.addContainer('label-group', createGroup('labels', pieLabelGroups, dataset)); dataset.getContainer('connector-shadow-group') || dataset.addContainer('connector-shadow-group', // paper.group('connector-shadows', pieLabelGroups)); createGroup('connector-shadows', pieLabelGroups, dataset)); dataset.getContainer('anchor-shadow-group') || dataset.addContainer('anchor-shadow-group', // paper.group('anchor-shadows', pieLabelGroups)); createGroup('anchor-shadows', pieLabelGroups, dataset)); }; /** * Parses and calculates position during post space management * * @memberof Pie2DDataset */ Pie2DDataset.prototype.allocatePosition = function allocatePosition() { var dataset = this, plotData = dataset.components.data, i, dataObj, len = plotData.length; for (i = 0; i < len; i++) { dataObj = plotData[i]; dataset.parsePlotAttributes(dataObj, i); dataset.parseLabelAttributes(dataObj, i); } }; /** * Parsing and calculation of plot cosmetics and positions * * @param {any} dataObj dataObj * @param {any} index index * @memberof Pie2DDataset */ Pie2DDataset.prototype.parsePlotAttributes = function parsePlotAttributes(dataObj, index) { var j, singleFillColor, dataSet = this, plotData = dataSet.components.data, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, conf = dataSet.config, i = index, toolText, setLink, ringPath, angle1, angle2, set, val, displayValue, sliced, color, angle, dataLength = plotData.length, canvasWidth = chartConfig.canvasWidth, canvasHeight = chartConfig.canvasHeight, cx = chartConfig.canvasLeft + canvasWidth * 0.5, cy = chartConfig.canvasTop + canvasHeight * 0.5, previousData, valueTotal = conf.valueTotal, factor, piePlotOptions = conf.piePlotOptions = dataSet._parsePiePlotOptions(), slicedOffset = piePlotOptions.slicedOffset, connector, r = piePlotOptions.size, r2 = (conf.innerSize || 0) * 0.5, startAngle = (conf.startAngle || 0) % pi2, initialAngle, isTranspose, endAngle = startAngle - pi2, animateClockWise = conf.animateClockWise, setElAttr; factor = valueTotal && pi2 / valueTotal; // Log the chart position for calculating mouse xy. conf.pieCenter = [cx, cy]; angle1 = startAngle; angle2 = startAngle; if (index > 0) { angle1 = plotData[index - 1].config.startAngle; angle2 = plotData[index - 1].config.endAngle; } set = dataObj.config; val = set.y; displayValue = set.displayValue; sliced = set.sliced; toolText = set.toolText; setLink = !!set.link; if (val === null || val === UNDEF || set.isVisible === false) { return; } color = set.color; color.r = r; color.cx = cx; color.cy = cy; angle2 = angle1; // This conditional assignment of value 2 * pi is to by-pass a // computational error inherent to any computer system, which // happens here for certain values in singleton cases. angle1 -= !conf.singletonCase ? val * factor : pi2; angle = (angle1 + angle2) * 0.5; if (isTranspose) { if (i < dataLength) { initialAngle = UNDEF; for (j = i + 1; j < dataLength && initialAngle === UNDEF; j += 1) { initialAngle = plotData[j].config.endAngle; } } if (initialAngle === UNDEF) { initialAngle = endAngle; } } else { initialAngle = animateClockWise ? endAngle : startAngle; } previousData = conf.previousData = { cx: cx, cy: cy, r: r, r2: r2 }; ringPath = !dataSet.config.drawn ? [cx, cy, r, r2, angle1, angle2] : [previousData.cx, previousData.cy, previousData.r, previousData.r2, angle1, angle2]; set.eventArgs = { index: conf.reversePlotOrder ? dataLength - 1 - i : i, link: set.link, value: set.y, displayValue: set.displayValueArgs, categoryLabel: set.categoryLabel, isSliced: sliced, toolText: toolText, pValue: set.pValue }; // slicedTranslation is used when isSliced is set to 1. sliced && (set.slicedTranslation = 't' + mathCos(angle) * slicedOffset + ',' + mathSin(angle) * slicedOffset); setElAttr = { 'stroke-width': set.borderWidth, 'stroke': set.borderColor, fill: isVML || isTranspose && singleFillColor ? singleFillColorFn(set.color, conf.doughnutradius) : (0, _lib.toRaphaelColor)(set.color), transform: sliced ? set.slicedTranslation : '', 'stroke-dasharray': set.dashStyle, redrawDataLabels: startAngle, 'ringpath': ringPath, cursor: setLink ? POINTER : '' }; set.props = { element: { attr: setElAttr } }; set.eventArgs = { index: conf.reversePlotOrder ? dataLength - 1 - i : i, link: set.link, value: set.y, displayValue: set.displayValueArgs, categoryLabel: set.categoryLabel, isSliced: sliced, toolText: toolText, pValue: set.pValue }; set.plotItem = { chart: chart, index: i, // @todo check requirement seriesData: conf, value: val, pValue: set.pValue, displayValue: set.displayValue || '', angle: set.angle = angle, angle1: set.startAngle = angle1, angle2: set.endAngle = angle2, slicedX: mathCos(angle) * slicedOffset, slicedY: mathSin(angle) * slicedOffset, sliced: sliced, labelText: displayValue, toolText: toolText, name: set.name, link: set.link, percentage: valueTotal ? val * valueTotal / 100 : 0, originalIndex: dataLength - i - 1, style: set.style, color: (0, _lib.toRaphaelColor)(set.color), borderColor: set.borderColor, borderWidth: set.borderWidth, rolloverProperties: set.hoverEffects, radius: r, center: [cx, cy], innerDiameter: 2 * r2, centerLabelConfig: set.centerLabelConfig, isVisible: set.isVisible, label: set.seriesName, connector: connector, transX: set.transX = mathCos(angle) * slicedOffset, transY: set.transY = mathSin(angle) * slicedOffset, slicedTranslation: set.slicedTranslation = 't' + mathCos(angle) * slicedOffset + ',' + mathSin(angle) * slicedOffset }; }; /** * Parsing and calculation of plot cosmetics and positions * * @param {any} dataObj dataObj * @param {any} index index * @memberof Pie2DDataset */ Pie2DDataset.prototype.parseLabelAttributes = function parseLabelAttributes(dataObj) { var dataSet = this, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, dataLabelStyle = chartConfig.dataLabelStyle, conf = dataSet.config, style = chartConfig.style, set, val, displayValue, colorLabelFromPoint = false, textDirection = chartConfig.textDirection, dataLabelOptions = conf.dataLabelOptions, _textAttrs, _textCss; set = dataObj.config; if (!(_textAttrs = set._textAttrs)) { _textAttrs = set._textAttrs = {}; } val = set.y; displayValue = set.displayValue; style = set.style; if (val === null || val === UNDEF || set.isVisible === false) { return; } if (displayValue !== UNDEF) { // If data label cosmetics exists. if (style) { if (!(_textCss = set._textCss)) { _textCss = set._textCss = {}; } _textCss.fontFamily = style.fontFamily; _textCss.fontSize = style.fontSize; _textCss.lineHeight = style.lineHeight; _textCss.fontWeight = style.fontWeight; _textCss.fontStyle = style.fontStyle; } set.plotItem.style = set.style = style || (style = dataLabelStyle); _textAttrs.text = displayValue; _textAttrs.fill = (colorLabelFromPoint ? (0, _lib.toRaphaelColor)(set.color) : style.color) || '#000000'; _textAttrs['text-bound'] = [style.backgroundColor, style.borderColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash]; _textAttrs.direction = textDirection; _textAttrs.lineHeight = style.lineHeight; _textAttrs.visibility = visibleStr; } else { // hide the label _textAttrs.visibility = HIDDEN; } set.props.label = { attr: _textAttrs, css: _textCss }; set.props.connector = { attr: { visibility: VISIBLE, 'stroke-width': dataLabelOptions.connectorWidth, stroke: dataLabelOptions.connectorColor || '#606060' } }; }; /** * Function for drawing 2D pie * This function is called every time for each dataset when they are initially drawn or shown/hidden from */ Pie2DDataset.prototype.draw = function draw() { // retrive requitrd objects var singleFillColor, dataSet = this, animationManager = dataSet.getFromEnv('animationManager'), chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, dataLabelStyle = chartConfig.dataLabelStyle, conf = dataSet.config, showShadow = conf.showShadow, i, alphaanimation = chartConfig.alphaanimation, dataSetComponents = dataSet.components, dataStore = dataSetComponents.data, removeDataArr = dataSetComponents.removeDataArr = dataSetComponents.removeDataArr || [], dataObj, toolText, setElement, setElementCheck, eventArgs, style = chartConfig.style, pool = dataSet.pool, visible = dataSet.getState('visible'), plotGroup, plotShadow, labelGroup, connectorShadowGroup, anchorShadowGroup, setGraphics, set, val, displayValue, plotItem, dataLabel, plotData = dataSetComponents.data || [], dataLength = plotData.length, canvasWidth = chartConfig.canvasWidth, canvasHeight = chartConfig.canvasHeight, cx = chartConfig.canvasLeft + canvasWidth * 0.5, cy = chartConfig.canvasTop + canvasHeight * 0.5, // Fetching previous center points and // other data if required valueTotal, plotDragStart = conf.handlersAPI.plotDragStart, plotDragEnd = conf.handlersAPI.plotDragEnd, plotDragMove = conf.handlersAPI.plotDragMove, plotRollOver = conf.handlersAPI.plotRollOver, plotRollOut = conf.handlersAPI.plotRollOut, restoreColor = function restoreColor() { var i, dataObj; if (singleFillColor) { for (i = 0; i < dataLength; i += 1) { // set original color dataObj = plotData[i]; dataObj.graphics.element && dataObj.graphics.element.attr({ fill: (0, _lib.toRaphaelColor)(dataObj.config.color) }); } } }, isDimensionModified = function () { var pieCenter = conf.pieCenter || [], piePlotOptions = conf.piePlotOptions || [], oldDimensions = { cx: pieCenter[0], cy: pieCenter[1], r: piePlotOptions.size, r2: (conf.innerSize || 0) * 0.5 }, tolerance = 5; return function (newDimesion) { var prop, flag = false; for (prop in newDimesion) { if (mathAbs(newDimesion[prop] - oldDimensions[prop]) > tolerance) { flag = true; break; } } return flag; }; }(), piePlotOptions = conf.piePlotOptions = dataSet._parsePiePlotOptions(), dataLabelOptions = conf.dataLabelOptions, connector, connectorCheck, r = piePlotOptions.size, r2 = (conf.innerSize || 0) * 0.5, plotAnimCallBack, _textAttrs, _textCss, anim = { plot: { data: [], animType: 'linear' }, initial: { data: [] }, final: { data: [] } }, placeDataLabels = function placeDataLabels() { dataSet.placeDataLabels(false, dataStore, conf, null, anim); }, toolTipController = dataSet.getFromEnv('toolTipController'); if (!dataSet.getContainer('pie-groups')) { dataSet._createContainer(); } plotGroup = dataSet.getContainer('plot-group'); plotShadow = dataSet.getContainer('plot-shadow-group'); labelGroup = dataSet.getContainer('label-group'); connectorShadowGroup = dataSet.getContainer('connector-shadow-group'); anchorShadowGroup = dataSet.getContainer('anchor-shadow-group'); if (dataSet.config.drawn) { singleFillColor = isDimensionModified({ cx: cx, cy: cy, r: r, r2: r2 }) && false; } labelGroup.css(dataLabelStyle); valueTotal = conf.valueTotal; // hide all groups if dataset is not visible OR // none of that plots has positive value if (!visible || !valueTotal) { plotGroup.hide(); plotShadow.hide(); labelGroup.hide(); connectorShadowGroup.hide(); anchorShadowGroup.hide(); } else { plotGroup.show(); plotShadow.show(); labelGroup.show(); connectorShadowGroup.show(); anchorShadowGroup.show(); } removeDataArr.length && dataSet.removeElement(anim); for (i = 0; i < dataLength; i += 1) { dataObj = plotData[i]; setGraphics = dataObj.graphics; set = dataObj.config; if (!(_textAttrs = set._textAttrs)) { _textAttrs = set._textAttrs = {}; } val = set.y; displayValue = set.displayValue; toolText = set.toolText; style = set.style; if (val === null || val === UNDEF || set.isVisible === false) { continue; } setElementCheck = setGraphics.element; dataLabel = setGraphics.label; connectorCheck = setGraphics.connector; if (displayValue !== UNDEF) { // If data label cosmetics exists. if (style) { if (!(_textCss = set._textCss)) { _textCss = set._textCss = {}; } _textCss.fontFamily = style.fontFamily; _textCss.fontSize = style.fontSize; _textCss.lineHeight = style.lineHeight; _textCss.fontWeight = style.fontWeight; _textCss.fontStyle = style.fontStyle; } else if (set._textCss) { /* If there was a perviously applied cosmetics for a data Object, need to remove the already applied css. */ dataLabel && dataLabel.removeCSS(); delete set._textCss; _textCss = UNDEF; } set.style = style || (style = dataLabelStyle); _textAttrs = set.props.label.attr; if (!dataLabel) { if (pool && pool.label && pool.label.length) { dataLabel = setGraphics.label = pool.label.splice(0, 1)[0]; } } else { if (_textCss) { dataLabel.css(_textCss); delete _textCss.fontFamily; delete _textCss.fontSize; delete _textCss.lineHeight; delete _textCss.fontWeight; delete _textCss.fontStyle; _textCss = UNDEF; } } dataLabel && animationManager.setAnimation({ el: dataLabel, attr: { opacity: 1 }, component: dataSet }); if (dataLabelOptions.distance > 0 && dataLabelOptions.connectorWidth && dataLabelOptions.enableSmartLabels) { if (!connectorCheck) { if (pool && pool.connector.length) { connectorCheck = setGraphics.connector = pool.connector.splice(0, 1)[0]; } } connector = animationManager.setAnimation({ el: connectorCheck || 'path', container: labelGroup, label: 'connector', attr: set.props.connector.attr, component: dataSet }).show(); if (!connectorCheck) { setGraphics.connector = connector; connector.on('fc-dragstart', plotDragStart).on('fc-dragmove', plotDragMove).on('fc-dragend', plotDragEnd).on('fc-mouseover', plotRollOver).on('fc-mouseout', plotRollOut); } animationManager.setAnimation({ el: connector, attr: { opacity: 1 }, doNotRemove: true, component: dataSet }); } else { connectorCheck && animationManager.setAnimation({ el: connectorCheck, doNotRemove: true, attr: { opacity: 0 }, component: dataSet }); } } else { // hide the label dataLabel && animationManager.setAnimation({ el: dataLabel, callback: hideFn, doNotRemove: true, component: dataSet }); connectorCheck && animationManager.setAnimation({ el: connectorCheck, callback: hideFn, doNotRemove: true, component: dataSet }); } // --when all values of the dataplots are 0-- if (!valueTotal) { dataLabel && dataLabel.hide(); connector && connector.hide(); } else { dataLabel && dataLabel.show(); connector && connector.show(); } // if (!dataSet.config.drawn) { if (alphaanimation) { animationManager.setAnimation({ el: plotGroup, attr: { opacity: 1 }, component: dataSet, callback: plotAnimCallBack }); } if (valueTotal) { animationManager.setAnimation({ el: labelGroup, attr: { opacity: 1 }, component: dataSet }); } // create the element if not available. setElement = animationManager.setAnimation({ el: setElementCheck || 'ringpath', attr: set.props.element.attr, label: 'ringpath', props: { startAngle: dataSet.config.startAngle }, container: plotGroup, component: dataSet }); if (!setElementCheck) { setGraphics.element = setElement; setElement.on('fc-dragstart', plotDragStart).on('fc-dragmove', plotDragMove).on('fc-dragend', plotDragEnd).on('fc-click', plotClickHandler(dataSet, setElement)).on('fc-mouseover', plotRollOver).on('fc-mouseout', plotRollOut); } plotItem = set.plotItem; eventArgs = set.eventArgs; plotItem.graphic = setElement; setElement.show().shadow(showShadow && set.shadow, plotShadow).data('plotItem', plotItem).data('dataset', this).data(EVENTARGS, eventArgs); toolTipController.enableToolTip(setElement, toolText); _textAttrs.plotItem = plotItem; _textAttrs[EVENTARGS] = eventArgs; connector && connector.data('plotItem', plotItem).data(EVENTARGS, eventArgs); } placeDataLabels(); !dataSet.config.__attachRestoreColor && dataSet.addExtEventListener('animationComplete', restoreColor, animationManager); dataSet.config.__attachRestoreColor = true; // Marking dataSet drawn dataSet.config.drawn = true; }; /** * function to slice in other sliced out slices which are not clicked * @param {number} mainPieId index of clicked sliced * @return {boolean} true when at least one other pie is sliced */ Pie2DDataset.prototype.sliceInOtherPies = function sliceInOtherPies(mainPieId) { var dataset = this, plotItems = dataset.components.data, i = plotItems.length, numSliced = 0, plot; dataset.enableMultiSlicing = true; while (i--) { i !== mainPieId && (plot = plotItems[i]).config.sliced && ++numSliced && dataset.plotGraphicClick.call(plot.graphics); } dataset.enableMultiSlicing = false; // Returns true when at least one other pie is sliced return !!numSliced; }; /** * Function to remove a data from a dataset * @param {Object} anim - object reference of animation manager argument * consist of elements and their configuration */ Pie2DDataset.prototype.removeElement = function removeElement() { // todo: if we remove a data at a specified index, make animation proper for that. var dataSet = this, animationManager = dataSet.getFromEnv('animationManager'), chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, components = dataSet.components, removeDataArr = components.removeDataArr || [], pool = dataSet.pool = dataSet.pool = {}, len = removeDataArr.length, conf = dataSet.config, removeData, element, // pieCenter = conf.pieCenter, ele, canvasWidth = chartConfig.canvasWidth, canvasHeight = chartConfig.canvasHeight, cx = chartConfig.canvasLeft + canvasWidth * 0.5, cy = chartConfig.canvasTop + canvasHeight * 0.5, hideFn = dataSet.hideElements, graphics, r = conf.pieMinRadius, r2 = (conf.innerSize || 0) * 0.5, i, startAngle = conf.startAngle, // plotItem, endAngle = startAngle - pi2; for (i = 0; i < len; i++) { removeData = removeDataArr[0]; graphics = removeData.graphics; for (ele in graphics) { element = graphics[ele]; if (!element) { continue; } // element will just change ringpath if (ele === 'element') { animationManager.setAnimation({ el: element, attr: { ringpath: [cx, cy, r, r2, endAngle, endAngle + 0.01], transform: '' }, callback: hideFn, component: dataSet }); // other elements will fadeout } else { animationManager.setAnimation({ el: element, attr: { opacity: 0 }, callback: hideFn, component: dataSet }); } if (!pool[ele]) { pool[ele] = []; } // hide the elements when updated to lower number of visual count of elements. pool[ele].push(element); } removeDataArr.splice(0, 1); } }; /** * function to get eventarg for this dataset * @param {Object} legendItem the legendItem * @return {Object} arguement object for event */ Pie2DDataset.prototype.getEventArgs = function getEventArgs(legendItem) { var dataset = this, // get the index of the current legend-item index = legendItem.config.index, set = dataset.components.data[index], config = set.config || {}, eventArgs; eventArgs = { datasetName: config.seriesName, datasetIndex: index, id: config.userID, visible: config.isVisible, label: config.seriesName, value: config.value, percentValue: config.pValue, tooltext: config.toolText, link: config.link, sliced: config.sliced }; return eventArgs; }; /** * remove legenditem. * @param {Object} config config object */ Pie2DDataset.prototype.remove = function remove(config) { var dataset = this, legendItemId = dataset.config.legendItemId, legend = dataset.getFromEnv('legend'); legend && legendItemId && legend.disposeItem(legendItemId); _AreaDataset.prototype.remove.call(this, config); }; return Pie2DDataset; }(_area2['default']); exports['default'] = Pie2DDataset; exports.plotGraphicClick = plotGraphicClick; exports.trimData = _trimData; exports.labelClickFn = labelClickFn; exports.plotClickHandler = plotClickHandler; exports.hideFn = hideFn; /***/ }), /* 477 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var defaultTransform = 't0,0'; exports['default'] = { 'initial.dataset.pie2D': function initialDatasetPie2D() { return { 'group.appearing': function groupAppearing(inputJSON) { var component = inputJSON.component, chartConfig = component.getFromEnv('chartConfig'); return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: chartConfig.alphaanimation ? 'plot' : 'initial' }]; }, 'ringpath.appearing': function ringpathAppearing(inputJSON) { var component = inputJSON.component, ringpath = inputJSON.attr.ringpath.slice(0), finalRingPath = inputJSON.attr.ringpath.slice(0), startAngle = inputJSON.props.startAngle, dataset = inputJSON.component, dsConfig = dataset.config, chartConfig = component.getFromEnv('chartConfig'), animateClockWise = dsConfig.animateClockWise; if (chartConfig.alphaanimation) { return [{}]; } else { if (animateClockWise) { // If animateClockwise is enabled, replace the start and end angle with its complement // (2Pi - curAngle) finalRingPath[4] += 2 * Math.PI; finalRingPath[5] += 2 * Math.PI; } ringpath[4] = startAngle; ringpath[5] = startAngle; return [{ initialAttr: { ringpath: ringpath }, finalAttr: { ringpath: finalRingPath, transform: '' }, startEnd: { start: 0, end: 0.75 }, effect: 'linear', slot: 'plot' }, { initialAttr: { transform: '', ringpath: finalRingPath }, finalAttr: { ringpath: finalRingPath }, startEnd: { start: 0.75, end: 1 }, effect: 'linear', slot: 'plot' }]; } }, 'label.appearing': [{ initialAttr: { opacity: '0' }, finalAttr: { opacity: '1' }, slot: 'final' }], 'connector.updating': function connectorUpdating(inputJSON) { return [{ initialAttr: { path: inputJSON.attr.path, 'stroke-opacity': '0' }, finalAttr: { 'stroke-opacity': '1' }, slot: 'final' }]; }, 'label.updating': function labelUpdating(inputJSON) { return [{ initialAttr: { x: inputJSON.el.attrs.x }, slot: 'plot' }]; } }; }, 'slicing.dataset.pie2D': function slicingDatasetPie2D() { return { 'slice.updating': function sliceUpdating(inputJSON) { var t = inputJSON.attr && inputJSON.attr.transform; if (t !== defaultTransform) { return [{ initialAttr: { transform: defaultTransform }, slot: 'plot' }]; } else { return [{ finalAttr: { transform: defaultTransform }, slot: 'plot' }]; } } }; } }; /***/ }), /* 478 */, /* 479 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.manageGradientLegendSpace = exports._manageLegendSpace = undefined; var _lib = __webpack_require__(125); /** * function to calculate and allote space for legend */ function _manageLegendSpace() { var iapi = this, config = iapi.config, legend = iapi.getChildren('legend') && iapi.getChildren('legend')[0], gradientLegend = iapi.getChildren('gLegend') && iapi.getChildren('gLegend')[0], conf, colorRangeObj = iapi.getFromEnv('dataSource').colorrange, hasLegend = config.hasLegend, spaceTakenByLegend = {}, hasGradientLegend = iapi.hasGradientLegend, legendPosition, allottedSpace, factor, chartAttr = iapi.getFromEnv('dataSource').chart, mapByCategory = (0, _lib.pluckNumber)(chartAttr.mapbycategory, 0), isGradient = hasGradientLegend && colorRangeObj && (0, _lib.pluckNumber)(colorRangeObj.gradient); // Check if jsonData has colorrange if (isGradient && !mapByCategory) { conf = gradientLegend.conf; hasGradientLegend = true; config.gLegendEnabled = true; factor = 0.5; legendPosition = conf.legendPosition; } else { conf = legend && legend.config; hasGradientLegend = false; config.gLegendEnabled = false; legendPosition = conf && conf.legendPos; factor = legendPosition === _lib.POSITION_RIGHT ? 0.8 : 0.4; } if (legendPosition === _lib.POSITION_RIGHT) { allottedSpace = config.availableWidth * factor; } else { allottedSpace = config.availableHeight * factor; } if (hasGradientLegend) { spaceTakenByLegend = iapi.manageGradientLegendSpace(allottedSpace); } else { if (hasLegend !== false && legend && !legend.getState('removed')) { spaceTakenByLegend = legend && legend._manageLegendPosition(allottedSpace); } } iapi._allocateSpace({ bottom: spaceTakenByLegend && spaceTakenByLegend.bottom || 0, right: spaceTakenByLegend && spaceTakenByLegend.right || 0 }); } /** * Calculates the dimension required by gradient legend * @param {Object} allottedSpace Allowed space for Gradient legend component * @return {Object} Dimension of space taken (width, height) */ function manageGradientLegendSpace(allottedSpace) { var iapi = this, config = iapi.config, gradientLegend = iapi.getFromEnv('gLegend'), conf = gradientLegend && gradientLegend.conf, legendPosition, returnDimension, gLegendPadding, spaceUsed; config.gLegendPadding = (0, _lib.pluckNumber)(iapi.getFromEnv('chart-attrib').legendpadding, 10); gLegendPadding = Math.min(config.gLegendPadding, 0.5 * allottedSpace); if (conf) { legendPosition = conf.legendPosition; spaceUsed = gradientLegend.getLogicalSpace(allottedSpace); if (legendPosition === _lib.POSITION_BOTTOM) { returnDimension = { bottom: (spaceUsed.height || 0) + gLegendPadding }; } else { returnDimension = { right: (spaceUsed.width || 0) + gLegendPadding }; } } else { returnDimension = { bottom: 0, right: 0 }; } return returnDimension; } exports._manageLegendSpace = _manageLegendSpace; exports.manageGradientLegendSpace = manageGradientLegendSpace; /***/ }), /* 480 */, /* 481 */, /* 482 */, /* 483 */, /* 484 */, /* 485 */, /* 486 */ /***/ (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['default'] = function (R) { var win = window, UNDEF, toFloat = win.parseFloat, ARRAY = 'array', BLANK = '', COMMA = ',', SPACE = ' ', NONE = 'none', createNode = R._createNode, setFillAndStroke = R._setFillAndStroke, Element = R.el.constructor, // High performance path rendering extension for Red Raphael. LITEPATH = 'litepath', CSSFLOOD = 'position:absolute;left:0;top:0;width:21600px;height:21600px;', COORD21600 = '21600 21600', s2vcmd = { 'Q': 'L', 'Z': 'X', 'q': 'l', 'z': 'x', ',': ' ' }, p2s = /,?([achlmqrstvxz]),?/gi, p2srep, path2string = function path2string() { return this.join(COMMA).replace(p2s, p2srep); }, litepathsetter, vmlTransformHelper; // pathString if (R.svg) { p2srep = '$1'; litepathsetter = function litepathsetter() { var o = this, path = R.is(arguments[0], ARRAY) ? arguments[0] : Array.prototype.slice.call(arguments); if (!path) { path = 'M0,0'; } else if (typeof path === 'string') { path = path.replace(p2s, p2srep); } else { path.toString = path2string; } o.node.setAttribute('d', path.toString()); // don't need to return anything as the attrbute is already applied. Nothing other need to be changes }; // eslint-disable-next-line no-unused-vars R._engine.litepath = function (path, svg, zoom, group, attributes) { var el = createNode('path'), p; (group || svg).canvas.appendChild(el); p = new Element(el, svg, group); p.type = LITEPATH; p.id = el.raphaelid = R._oid++; el.raphael = true; setFillAndStroke(p, attributes || { fill: NONE, stroke: '#000' }); return p; }; R._getPath.litepath = function (el) { return R.parsePathString(el.node.getAttribute('d')); }; } else if (R.vml) { // eslint-disable-next-line no-unused-vars p2srep = function p2srep(cmd, $1) { return s2vcmd[$1] || $1; }; vmlTransformHelper = function vmlTransformHelper() { var o = this; o._transform.apply(o, arguments); o._.bcoord && (o.node.coordsize = o._.bcoord); return o; }; litepathsetter = function litepathsetter(path) { var o = this; if (!path) { path = 'M0,0'; } else if (typeof path === 'string') { path = path.replace(p2s, p2srep); } else { path.toString = path2string; } o.node.path = path; return o; }; // eslint-disable-next-line no-unused-vars R._engine.litepath = function (pathString, vml, zoom, group, attributes) { var el = createNode('shape'), s = el.style, p = new Element(el, vml, group), attr = attributes || { fill: NONE, stroke: '#000' }, skew; s.cssText = CSSFLOOD; zoom = toFloat(zoom); if (isNaN(zoom)) { el.coordsize = COORD21600; } else { p._.bzoom = zoom; s.width = '1px'; s.height = '1px'; el.coordsize = p._.bcoord = zoom + SPACE + zoom; } el.coordorigin = vml.coordorigin; p.type = LITEPATH; p.id = el.raphaelid = R._oid++; el.raphael = true; p._transform = p.transform; p.transform = vmlTransformHelper; R._setFillAndStroke(p, attr); (group || vml).canvas.appendChild(el); skew = createNode('skew'); skew.on = true; el.appendChild(skew); p.skew = skew; return p; }; R._getPath.litepath = function (el) { return R.parsePathString(el.node.path || BLANK); }; } R.fn[LITEPATH] = function (path, zoomInput, group) { var paper = this, attributes, zoom, out; // Checking if path is just an object and not group if ((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.constructor !== Element) { attributes = path; path = path.litepath; zoom = path.zoom; group = path.group; } if (zoomInput && zoomInput.constructor === Element) { group = zoomInput; zoom = UNDEF; } else { zoom = zoomInput; } if (path && path.constructor === Element) { group = path; path = BLANK; } // create element and update the custom attribute. out = R._engine[LITEPATH](path, this, zoom, group, attributes); out.ca[LITEPATH] = litepathsetter; path && out.attr(LITEPATH, R.is(path, ARRAY) ? [path] : path); return paper.__set__ && this.__set__.push(out), paper._elementsById[out.id] = out; }; }; /***/ }), /* 487 */, /* 488 */, /* 489 */, /* 490 */, /* 491 */, /* 492 */, /* 493 */, /* 494 */, /* 495 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.setAxisDimention = exports.getSpecificyAxisConf = exports.getSpecificxAxisConf = exports._feedAxesRawData = undefined; var _mscartesian = __webpack_require__(459); var _mscartesian2 = _interopRequireDefault(_mscartesian); var _cartesianAxisDualY = __webpack_require__(496); var _cartesianAxisDualY2 = _interopRequireDefault(_cartesianAxisDualY); var _lib = __webpack_require__(125); var _combiDualYDataset = __webpack_require__(497); var _combiDualYDataset2 = _interopRequireDefault(_combiDualYDataset); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var _feedAxesRawData, getSpecificxAxisConf, getSpecificyAxisConf, setAxisDimention, mathMax = Math.max; var MSDyBaseCartesian = function (_MSCartesian) { _inherits(MSDyBaseCartesian, _MSCartesian); /** * constructor fn */ function MSDyBaseCartesian() { _classCallCheck(this, MSDyBaseCartesian); var _this = _possibleConstructorReturn(this, _MSCartesian.call(this)); _this.registerFactory('axis', _cartesianAxisDualY2['default'], ['canvas']); _this.registerFactory('dataset', _combiDualYDataset2['default'], ['vCanvas']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSDyBaseCartesian.getName = function getName() { return 'MSDyBaseCartesian'; }; MSDyBaseCartesian.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSCartesian.prototype.__setDefaultConfig.call(this); this.config.syncaxislimits = 0; }; MSDyBaseCartesian.prototype._feedAxesRawData = function _feedAxesRawData() { var iapi = this, config = iapi.config, colorM = iapi.getFromEnv('color-manager'), dataObj = iapi.getFromEnv('dataSource'), chartAttrs = iapi.getFromEnv('chart-attrib'), xAxisConf, yAxisConf, sYAxisConf, is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, primaryAxisOnleft = config.primaryAxisOnleft = (0, _lib.pluckNumber)(chartAttrs.primaryaxisonleft, 1), syncAxisLimits = (0, _lib.pluckNumber)(chartAttrs.syncaxislimits, 0), sYAxisTrendlines = [{ line: [] }], pYAxisTrendlines = [{ line: [] }], trendlinesArr, trendlineObj, arrLen, len, i, j, trendlines = dataObj.trendlines || [], showZeroPlane = (0, _lib.pluckNumber)(chartAttrs.showzeroplane, 1), showZeroPlaneValue = (0, _lib.pluckNumber)(chartAttrs.showzeroplanevalue); if (!showZeroPlane && showZeroPlaneValue === _lib.UNDEF) { showZeroPlaneValue = 0; } xAxisConf = iapi.getSpecificxAxisConf(); yAxisConf = iapi.getSpecificyAxisConf(); sYAxisConf = { isActive: false, isPercent: iapi.isPercentage, axisIndex: 1, uniqueClassName: 1, outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisNamePadding: chartAttrs.yaxisnamepadding, axisValuePadding: chartAttrs.yaxisvaluespadding, axisNameFont: chartAttrs.syaxisnamefont, axisNameFontSize: chartAttrs.syaxisnamefontsize, axisNameFontColor: chartAttrs.syaxisnamefontcolor, axisNameFontBold: chartAttrs.syaxisnamefontbold, axisNameFontItalic: chartAttrs.syaxisnamefontitalic, axisNameBgColor: chartAttrs.syaxisnamebgcolor, axisNameBorderColor: chartAttrs.syaxisnamebordercolor, axisNameAlpha: chartAttrs.syaxisnamealpha, axisNameFontAlpha: chartAttrs.syaxisnamefontalpha, axisNameBgAlpha: chartAttrs.syaxisnamebgalpha, axisNameBorderAlpha: chartAttrs.syaxisnameborderalpha, axisNameBorderPadding: chartAttrs.syaxisnameborderpadding, axisNameBorderRadius: chartAttrs.syaxisnameborderradius, axisNameBorderThickness: chartAttrs.syaxisnameborderthickness, axisNameBorderDashed: chartAttrs.syaxisnameborderdashed, axisNameBorderDashLen: chartAttrs.syaxisnameborderdashlen, axisNameBorderDashGap: chartAttrs.syaxisnameborderdashgap, axisNameWidth: chartAttrs.syaxisnamewidth, useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, rotateAxisName: (0, _lib.pluckNumber)(chartAttrs.rotateyaxisname, 1), axisName: chartAttrs.syaxisname, divLineColor: (0, _lib.pluck)(chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.divlinealpha, colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.divlinedashgap, 2), showAlternateGridColor: (0, _lib.pluckNumber)(chartAttrs.showalternatehgridcolor, 1), alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatehgridcolor, colorM.getColor('altHGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatehgridalpha, colorM.getColor('altHGridAlpha')), numDivLines: chartAttrs.numdivlines, // @todo have to change the y axis max and min value afterwards when percentage axis is ready axisMinValue: syncAxisLimits ? (0, _lib.pluckNumber)(chartAttrs.syaxisminvalue, chartAttrs.pyaxisminvalue, chartAttrs.yaxisminvalue) : chartAttrs.syaxisminvalue, axisMaxValue: syncAxisLimits ? (0, _lib.pluckNumber)(chartAttrs.syaxismaxvalue, chartAttrs.pyaxismaxvalue, chartAttrs.yaxismaxvalue) : chartAttrs.syaxismaxvalue, setAdaptiveMin: chartAttrs.setadaptivesymin || chartAttrs.setadaptiveymin, adjustDiv: chartAttrs.adjustdiv, labelStep: chartAttrs.yaxisvaluesstep, showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showsyaxisvalues, chartAttrs.showsyaxisvalue, chartAttrs.showyaxisvalues, chartAttrs.showyaxisvalue), showLimits: (0, _lib.pluckNumber)(chartAttrs.showsecondarylimits, chartAttrs.showyaxislimits, chartAttrs.showlimits), showDivLineValues: (0, _lib.pluckNumber)(chartAttrs.showdivlinesecondaryvalue, chartAttrs.showyaxisvalues, chartAttrs.showyaxisvalue, 1), showZeroPlane: showZeroPlane, zeroPlaneColor: chartAttrs.zeroplanecolor, zeroPlaneThickness: (0, _lib.pluckNumber)(chartAttrs.zeroplanethickness, chartAttrs.divlinethickness, 2), zeroPlaneAlpha: chartAttrs.zeroplanealpha, showZeroPlaneValue: showZeroPlaneValue, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, trendlineAlpha: chartAttrs.trendlinealpha, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, showAxisLine: is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showsyaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, 0), axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.syaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.syaxislinealpha, chartAttrs.axislinealpha, 100), axisLineColor: (0, _lib.pluck)(chartAttrs.syaxislinecolor, chartAttrs.axislinecolor, '#000000') }; xAxisConf.vtrendlines = (0, _lib.extend2)([], dataObj.vtrendlines); for (i = 0, len = trendlines.length; i < len; i++) { trendlinesArr = trendlines[i] && trendlines[i].line || []; arrLen = trendlinesArr.length; for (j = 0; j < arrLen; j++) { trendlineObj = trendlinesArr[j] || {}; // parentyaxis = (trendlineObj.parentyaxis && trendlineObj.parentyaxis.toLowerCase()) || BLANK; if (trendlineObj.parentyaxis === 's') { sYAxisTrendlines[0].line.push(trendlineObj); } else { pYAxisTrendlines[0].line.push(trendlineObj); } } } yAxisConf.trendlines = (0, _lib.extend2)([], pYAxisTrendlines); sYAxisConf.trendlines = (0, _lib.extend2)([], sYAxisTrendlines); if (primaryAxisOnleft === 1) { yAxisConf.isVertical = true; yAxisConf.isReverse = true; yAxisConf.isOpposit = false; sYAxisConf.isVertical = true; sYAxisConf.isReverse = true; sYAxisConf.isOpposit = true; } else { yAxisConf.isVertical = true; yAxisConf.isReverse = true; yAxisConf.isOpposit = true; sYAxisConf.isVertical = true; sYAxisConf.isReverse = true; sYAxisConf.isOpposit = false; } return { yAxisConf: [yAxisConf, sYAxisConf], xAxisConf: [xAxisConf] }; }; /** * Returns x-axis configuration for chart. * @return {Object} configurations of x-axis. */ MSDyBaseCartesian.prototype.getSpecificxAxisConf = function getSpecificxAxisConf() { var iapi = this, chartAttrs = iapi.getFromEnv('chart-attrib'), is3D = iapi.config.is3D, xAxisConf = iapi.getBasexAxisConf(), config = iapi.config; xAxisConf.zeroPlaneThickness = (0, _lib.pluckNumber)(chartAttrs.vzeroplanethickness, chartAttrs.vdivlinethickness, 2); xAxisConf.zeroPlaneAlpha = (0, _lib.pluckNumber)(chartAttrs.vzeroplanealpha, chartAttrs.vdivlinealpha, config.zeroplanealpha); xAxisConf.showZeroPlaneValue = chartAttrs.showvzeroplanevalue; xAxisConf.showAxisLine = is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showxaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, 0); xAxisConf.axisLineColor = (0, _lib.pluck)(chartAttrs.xaxislinecolor, chartAttrs.axislinecolor, '#000000'); xAxisConf.isReverse = false; xAxisConf.showAlternateGridColor = (0, _lib.pluckNumber)(chartAttrs.showalternatevgridcolor, 0); xAxisConf.numDivLines = chartAttrs.numvdivlines; xAxisConf.maxLabelHeight = chartAttrs.maxlabelheight; xAxisConf.axisName = chartAttrs.xaxisname; xAxisConf.setAdaptiveMin = chartAttrs.setadaptivexmin; xAxisConf.showLimits = chartAttrs.showvlimits; xAxisConf.showDivLineValues = (0, _lib.pluckNumber)(chartAttrs.showvdivlinevalues, chartAttrs.showvdivlinevalues); return xAxisConf; }; /** * Returns y-axis configuration for chart. * @return {Object} configurations of y-axis. */ MSDyBaseCartesian.prototype.getSpecificyAxisConf = function getSpecificyAxisConf() { var iapi = this, chartAttrs = iapi.getFromEnv('chart-attrib'), is3D = iapi.config.is3D, palleteString = is3D ? _lib.chartPaletteStr.chart3D : _lib.chartPaletteStr.chart2D, config = iapi.config, colorM = iapi.getFromEnv('color-manager'), syncAxisLimits = (0, _lib.pluckNumber)(chartAttrs.syncaxislimits, 0), showZeroPlane = (0, _lib.pluckNumber)(chartAttrs.showzeroplane, 1), showZeroPlaneValue = (0, _lib.pluckNumber)(chartAttrs.showzeroplanevalue); if (!showZeroPlane && showZeroPlaneValue === _lib.UNDEF) { showZeroPlaneValue = 0; } return { outCanfontFamily: (0, _lib.pluck)(chartAttrs.outcnvbasefont, chartAttrs.basefont, 'Verdana,sans'), outCanfontSize: (0, _lib.pluckFontSize)(chartAttrs.outcnvbasefontsize, chartAttrs.basefontsize, 10), outCancolor: (0, _lib.pluck)(chartAttrs.outcnvbasefontcolor, chartAttrs.basefontcolor, colorM.getColor(palleteString.baseFontColor)).replace(/^#? ([a-f0-9]+)/ig, '#$1'), axisNamePadding: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamepadding, chartAttrs.yaxisnamepadding), axisValuePadding: (0, _lib.pluckNumber)(chartAttrs.pyaxisvaluespadding, chartAttrs.yaxisvaluespadding), axisNameFont: (0, _lib.pluck)(chartAttrs.pyaxisnamefont, chartAttrs.yaxisnamefont), axisNameFontSize: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamefontsize, chartAttrs.yaxisnamefontsize), axisNameFontColor: (0, _lib.pluck)(chartAttrs.pyaxisnamefontcolor, chartAttrs.yaxisnamefontcolor), axisNameFontBold: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamefontbold, chartAttrs.yaxisnamefontbold), axisNameFontItalic: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamefontitalic, chartAttrs.yaxisnamefontitalic), axisNameBgColor: (0, _lib.pluck)(chartAttrs.pyaxisnamebgcolor, chartAttrs.yaxisnamebgcolor), axisNameBorderColor: (0, _lib.pluck)(chartAttrs.pyaxisnamebordercolor, chartAttrs.yaxisnamebordercolor), axisNameAlpha: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamealpha, chartAttrs.yaxisnamealpha), axisNameFontAlpha: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamefontalpha, chartAttrs.yaxisnamefontalpha), axisNameBgAlpha: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamebgalpha, chartAttrs.yaxisnamebgalpha), axisNameBorderAlpha: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderalpha, chartAttrs.yaxisnameborderalpha), axisNameBorderPadding: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderpadding, chartAttrs.yaxisnameborderpadding), axisNameBorderRadius: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderradius, chartAttrs.yaxisnameborderradius), axisNameBorderThickness: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderthickness, chartAttrs.yaxisnameborderthickness), axisNameBorderDashed: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderdashed, chartAttrs.yaxisnameborderdashed), axisNameBorderDashLen: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderdashlen, chartAttrs.yaxisnameborderdashlen), axisNameBorderDashGap: (0, _lib.pluckNumber)(chartAttrs.pyaxisnameborderdashgap, chartAttrs.yaxisnameborderdashgap), axisNameWidth: (0, _lib.pluckNumber)(chartAttrs.pyaxisnamewidth, chartAttrs.yaxisnamewidth), useEllipsesWhenOverflow: chartAttrs.useellipseswhenoverflow, rotateAxisName: (0, _lib.pluckNumber)(chartAttrs.rotateyaxisname, 1), axisName: (0, _lib.pluck)(chartAttrs.pyaxisname, chartAttrs.yaxisname), divLineColor: (0, _lib.pluck)(chartAttrs.divlinecolor, colorM.getColor(palleteString.divLineColor)), divLineAlpha: (0, _lib.pluck)(chartAttrs.divlinealpha, colorM.getColor('divLineAlpha')), divLineThickness: (0, _lib.pluckNumber)(chartAttrs.divlinethickness, 1), divLineIsDashed: Boolean((0, _lib.pluckNumber)(chartAttrs.divlinedashed, chartAttrs.divlineisdashed, 0)), divLineDashLen: (0, _lib.pluckNumber)(chartAttrs.divlinedashlen, 4), divLineDashGap: (0, _lib.pluckNumber)(chartAttrs.divlinedashgap, 2), showAlternateGridColor: (0, _lib.pluckNumber)(chartAttrs.showalternatehgridcolor, 1), alternateGridColor: (0, _lib.pluck)(chartAttrs.alternatehgridcolor, colorM.getColor('altHGridColor')), alternateGridAlpha: (0, _lib.pluck)(chartAttrs.alternatehgridalpha, colorM.getColor('altHGridAlpha')), numDivLines: chartAttrs.numdivlines, axisMinValue: syncAxisLimits ? (0, _lib.pluckNumber)(chartAttrs.syaxisminvalue, chartAttrs.pyaxisminvalue, chartAttrs.yaxisminvalue) : (0, _lib.pluckNumber)(chartAttrs.pyaxisminvalue, chartAttrs.yaxisminvalue), axisMaxValue: syncAxisLimits ? (0, _lib.pluckNumber)(chartAttrs.syaxismaxvalue, chartAttrs.pyaxismaxvalue, chartAttrs.yaxismaxvalue) : (0, _lib.pluckNumber)(chartAttrs.pyaxismaxvalue, chartAttrs.yaxismaxvalue), setAdaptiveMin: chartAttrs.setadaptiveymin, adjustDiv: chartAttrs.adjustdiv, labelStep: chartAttrs.yaxisvaluesstep, showAxisValues: (0, _lib.pluckNumber)(chartAttrs.showyaxisvalues, chartAttrs.showyaxisvalue), showLimits: (0, _lib.pluckNumber)(chartAttrs.showyaxislimits, chartAttrs.showlimits, iapi.showLimits), showDivLineValues: (0, _lib.pluckNumber)(chartAttrs.showdivlinevalues, chartAttrs.showdivlinevalue), showZeroPlane: showZeroPlane, zeroPlaneColor: chartAttrs.zeroplanecolor, zeroPlaneThickness: (0, _lib.pluckNumber)(chartAttrs.zeroplanethickness, chartAttrs.divlinethickness, config.zeroplanethickness, 2), zeroPlaneAlpha: (0, _lib.pluckNumber)(chartAttrs.zeroplanealpha, chartAttrs.divlinealpha, config.zeroplanealpha), showZeroPlaneValue: showZeroPlaneValue, showZeroPlaneOnTop: config.showzeroplaneontop, trendlineColor: chartAttrs.trendlinecolor, trendlineToolText: chartAttrs.trendlinetooltext, trendlineThickness: chartAttrs.trendlinethickness, trendlineAlpha: chartAttrs.trendlinealpha, showTrendlinesOnTop: chartAttrs.showtrendlinesontop, showAxisLine: is3D ? 0 : (0, _lib.pluckNumber)(chartAttrs.showyaxisline, chartAttrs.showaxislines, chartAttrs.drawAxisLines, 0), axisLineThickness: (0, _lib.pluckNumber)(chartAttrs.yaxislinethickness, chartAttrs.axislinethickness, 1), axisLineAlpha: (0, _lib.pluckNumber)(chartAttrs.yaxislinealpha, chartAttrs.axislinealpha, 100), axisLineColor: (0, _lib.pluck)(chartAttrs.yaxislinecolor, chartAttrs.axislinecolor, '#000000'), forceTrendBelow: !!config.is3D }; }; MSDyBaseCartesian.prototype.setAxisDimention = function setAxisDimention() { var iapi = this, config = iapi.config, children = iapi.getChildren(), yAxisArr = children.yAxis, xAxis = children.xAxis && children.xAxis[0], yAxis = yAxisArr[0], sYAxis = yAxisArr[1], xDepth = config.xDepth, canvas = children.canvas[0], canvasConfig = canvas.config, canvasBorderWidth = canvasConfig.canvasBorderWidth, canvasPadding = canvasConfig.canvasPadding, canvasPaddingLeft = canvasConfig.canvasPaddingLeft, canvasPaddingRight = canvasConfig.canvasPaddingRight, canvasPaddingTop = canvasConfig.canvasPaddingTop, yAxisStartXPos, sYAxisStartXPos, primaryAxisOnleft = config.primaryAxisOnleft, canvasPaddingBottom = canvasConfig.canvasPaddingBottom; xAxis && xAxis.setAxisDimention({ x: config.canvasLeft + (xDepth || 0) + mathMax(canvasPaddingLeft, canvasPadding), y: config.canvasBottom + (config.shift || 0) + canvasBorderWidth, opposite: config.canvasTop - canvasBorderWidth, axisLength: config.canvasWidth - (xDepth || 0) - mathMax(canvasPaddingLeft, canvasPadding) - mathMax(canvasPaddingRight, canvasPadding) }); if (primaryAxisOnleft) { config.yAxisStartXPos = config.canvasLeft - canvasBorderWidth; config.sYAxisStartXPos = config.canvasRight + canvasBorderWidth; } else { config.yAxisStartXPos = config.canvasRight + canvasBorderWidth; config.sYAxisStartXPos = config.canvasLeft - canvasBorderWidth; } yAxisStartXPos = config.yAxisStartXPos; sYAxisStartXPos = config.sYAxisStartXPos; yAxis && yAxis.setAxisDimention({ x: yAxisStartXPos, y: config.canvasTop + canvasPaddingTop, opposite: sYAxisStartXPos, axisLength: config.canvasHeight - canvasPaddingTop - canvasPaddingBottom }); sYAxis && sYAxis.setAxisDimention({ x: sYAxisStartXPos, y: config.canvasTop + canvasPaddingTop, opposite: yAxisStartXPos, axisLength: config.canvasHeight - canvasPaddingTop - canvasPaddingBottom }); }; return MSDyBaseCartesian; }(_mscartesian2['default']); exports._feedAxesRawData = _feedAxesRawData = MSDyBaseCartesian.prototype._feedAxesRawData; exports.getSpecificxAxisConf = getSpecificxAxisConf = MSDyBaseCartesian.prototype.getSpecificxAxisConf; exports.getSpecificyAxisConf = getSpecificyAxisConf = MSDyBaseCartesian.prototype.getSpecificyAxisConf; exports.setAxisDimention = setAxisDimention = MSDyBaseCartesian.prototype.setAxisDimention; exports._feedAxesRawData = _feedAxesRawData; exports.getSpecificxAxisConf = getSpecificxAxisConf; exports.getSpecificyAxisConf = getSpecificyAxisConf; exports.setAxisDimention = setAxisDimention; exports['default'] = MSDyBaseCartesian; /***/ }), /* 496 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var children = void 0, canvas = chart.getChildren('canvas')[0], dataChanged = function dataChanged(obj1, obj2) { return JSON.stringify(obj1) !== JSON.stringify(obj2); }, zoomObj = { zoomable: true, pannable: true }, xAxis = void 0, syncAxisLimits = !!Number(chart.config.syncaxislimits), yAxes = void 0, axisRefVisualCartesian = canvas.getChildren('axisRefVisualCartesian')[0], config = chart._feedAxesRawData(), redraw = function redraw(e) { var sender = e.sender; axisRefVisualCartesian.addexplicitDrawItems(sender.getId(), sender); axisRefVisualCartesian.asyncDraw(); }, addCountInfo = function addCountInfo(e) { var dependentInfo = yAxes[1].config.dependentInfo; if (e.sender.getId() === dependentInfo.id) { dependentInfo.numDivLines = e.data; } }, addLimitInfo = function addLimitInfo(e) { var dependentInfo = yAxes[1].config.dependentInfo; if (e.sender.getId() === dependentInfo.id && dataChanged(dependentInfo.dataLimit, e.data)) { // the secondary axis will only get the required info and not call // for setting of data limit because of its setdatalimit is call is just after primary dependentInfo.dataLimit = e.data; if (yAxes[1].config.isDataLimitSet) { yAxes[1].setDataLimit(); } } }, addLimitInfoP = function addLimitInfoP(e) { var dependentInfo = yAxes[0].config.dependentInfo; if (e.sender.getId() === dependentInfo.id && dataChanged(dependentInfo.dataLimit, e.data)) { dependentInfo.dataLimit = e.data; // the primary axis is only dependent upon secondary when syncing of limits is // required, so when it will get the required info then it will call its setdatalimit yAxes[0].setDataLimit(); } }; (0, _lib.componentFactory)(chart, _category2['default'], 'xAxis', 1, config.xAxisConf); (0, _lib.componentFactory)(chart, _numeric2['default'], 'yAxis', 2, config.yAxisConf); children = chart.getChildren(); xAxis = children.xAxis[0]; yAxes = children.yAxis; yAxes.forEach(function (axis) { axis.setLinkedItem('canvas', canvas); axisRefVisualCartesian.setLinkedItem(axis.getId(), axis); axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, axis); canvas.attachAxis(axis, true, chart.zoomY ? zoomObj : {}); }); xAxis.setLinkedItem('canvas', canvas); axisRefVisualCartesian.setLinkedItem(xAxis.getId(), xAxis); yAxes[1].setAxisConfig({ dependentInfo: { id: yAxes[0].getId(), count: true, limit: syncAxisLimits } }); if (!yAxes[1].getState('divlineEventAdded')) { yAxes[1].addExtEventListener('divlinesSet', addCountInfo, yAxes[0]); yAxes[1].setState('divlineEventAdded', true); } if (syncAxisLimits) { if (!yAxes[1].getState('dataLimitEventAdded')) { yAxes[1].addExtEventListener('dataLimitSet', addLimitInfo, yAxes[0]); yAxes[1].setState('dataLimitEventAdded', true); } yAxes[0].setAxisConfig({ dependentInfo: { id: yAxes[1].getId(), limit: true } }); if (!yAxes[0].getState('dataLimitEventAdded')) { yAxes[0].addExtEventListener('dataLimitSet', addLimitInfoP, yAxes[1]); yAxes[0].setState('dataLimitEventAdded', true); } } axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, xAxis); canvas.attachAxis(xAxis, false, chart.zoomX ? zoomObj : {}); chart._setCategories(); }; var _lib = __webpack_require__(125); var _numeric = __webpack_require__(377); var _numeric2 = _interopRequireDefault(_numeric); var _category = __webpack_require__(422); var _category2 = _interopRequireDefault(_category); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 497 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var jsonData = chart.getFromEnv('dataSource'), datasetsJSON = jsonData.dataset, children = chart.getChildren(), canvas = children.canvas[0], vCanvasArr = canvas.getChildren('vCanvas'), vCanvas = vCanvasArr[0], svCanvas = vCanvasArr[1], datasetJSON = void 0, isdual = chart.getFromEnv('chartConfig').isdual, i = void 0, canvasDatasetsDef = { vCanvasDatasetsDef0: {}, vCanvasDatasetsDef1: {} }, datasetsDef = void 0, datasetDef = void 0, DsGroupClass = void 0, dsType = void 0, parentyaxis = void 0, relatedVCanvas = void 0, relatedPrevDatasetMap = void 0, prevDatasetMap = { vCanvas0: {}, vCanvas1: {} }; if (!datasetsJSON) { chart.setChartMessage(); } for (i = 0; i < datasetsJSON.length; i++) { datasetJSON = datasetsJSON[i]; parentyaxis = datasetJSON.parentyaxis || ''; if (parentyaxis.toLowerCase() === 's' && isdual) { dsType = (0, _lib.pluck)(datasetJSON.renderas, chart.config.sDefaultDatasetType); relatedVCanvas = svCanvas; relatedPrevDatasetMap = prevDatasetMap.vCanvas1; datasetsDef = canvasDatasetsDef.vCanvasDatasetsDef1; } else { dsType = (0, _lib.pluck)(datasetJSON.renderas, chart.config.defaultDatasetType); relatedVCanvas = vCanvas; relatedPrevDatasetMap = prevDatasetMap.vCanvas0; datasetsDef = canvasDatasetsDef.vCanvasDatasetsDef0; } dsType = chart.getDSType(dsType, parentyaxis.toLowerCase() === 's'); DsGroupClass = chart.getDSGroupdef(dsType, parentyaxis.toLowerCase() === 's'); if (DsGroupClass) { (0, _lib.componentFactory)(relatedVCanvas, DsGroupClass, MULTISERIESCOLUMNMANAGER); relatedPrevDatasetMap[DsGroupClass.getName().toLowerCase()] = true; } relatedPrevDatasetMap[dsType.toLowerCase()] = true; if (datasetsDef[dsType]) { datasetsDef[dsType].conf.push(datasetJSON); datasetsDef[dsType].indices.push(i); } else { datasetsDef[dsType] = {}; datasetsDef[dsType].indices = [i]; datasetsDef[dsType].classDef = chart.getDSdef(dsType); datasetsDef[dsType].conf = [datasetJSON]; datasetsDef[dsType].pYAxis = parentyaxis.toLowerCase(); datasetsDef[dsType].parent = DsGroupClass ? relatedVCanvas.getChildren(MULTISERIESCOLUMNMANAGER)[0] : relatedVCanvas; } } chart.config._hascolumn = false; for (var key in canvasDatasetsDef) { if (canvasDatasetsDef.hasOwnProperty(key)) { datasetsDef = canvasDatasetsDef[key]; for (dsType in datasetsDef) { if (datasetsDef.hasOwnProperty(dsType)) { datasetDef = datasetsDef[dsType]; if (datasetDef.parent.getType() === 'group') { datasetDef.parent.configure(datasetDef.conf); } (0, _lib.datasetFactory)(datasetDef.parent, datasetDef.classDef, 'dataset_' + dsType, datasetDef.conf.length, datasetDef.conf, datasetDef.indices); // set a flag if any column dataset is encountered. used to determine the thickness of the crossline dsType === 'column' && (chart.config._hascolumn = true); } } } } (0, _dataset.removeComponents)(vCanvasArr[0], Object.keys(prevDatasetMap.vCanvas0)); (0, _dataset.removeComponents)(vCanvasArr[1], Object.keys(prevDatasetMap.vCanvas1)); }; var _lib = __webpack_require__(125); var _dataset = __webpack_require__(498); var MULTISERIESCOLUMNMANAGER = 'multiseriesColumnManager'; /** * function to create dataset, groupmaneger. * assign dataset to group manager. * @param {Object} chart Chart API **/ /***/ }), /* 498 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * function to remove component if name is matched with value in set * @param {Object} component from where it would iterate * @param {Array} set criteria; if matched then remove */ var removeComponents = function removeComponents(component, set) { component && component.iterateComponents(function (child) { if (set.indexOf(child.getName().toLowerCase()) === -1 && !child.getLinkedParent().getState('removed')) { child.remove(); } }); }; exports.removeComponents = removeComponents; /***/ }), /* 499 */, /* 500 */, /* 501 */, /* 502 */, /* 503 */, /* 504 */, /* 505 */, /* 506 */, /* 507 */, /* 508 */, /* 509 */, /* 510 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _area = __webpack_require__(450); var _area2 = _interopRequireDefault(_area); var _lib = __webpack_require__(125); var _spline = __webpack_require__(511); var _spline2 = _interopRequireDefault(_spline); var _dependencyManager = __webpack_require__(132); var _mssplinePath = __webpack_require__(512); var _index = __webpack_require__(513); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var BLANKSTRING = '', // hot tracker threshold in pixels SETROLLOVERATTR = _lib.preDefStr.setRolloverAttrStr, SETROLLOUTATTR = _lib.preDefStr.setRolloutAttrStr, MAX_MITER_LINEJOIN = 2; (0, _dependencyManager.addDep)({ name: 'mssplineareaAnimation', type: 'animationRule', extension: _index2['default'] }); /** * class definition of mssplinearea dataset */ var MSSplineAreaDataset = function (_AreaDataset) { _inherits(MSSplineAreaDataset, _AreaDataset); function MSSplineAreaDataset() { _classCallCheck(this, MSSplineAreaDataset); var _this = _possibleConstructorReturn(this, _AreaDataset.call(this)); _this.drawCommonElements = _lib.stubFN; return _this; } /** * Sets the type of the component * @return {string} type */ MSSplineAreaDataset.prototype.getType = function getType() { return 'dataset'; }; /** * function to create component and configure and also configure the chart * It creates components which are depend on data and configure them and also configure chart * It calls helper function namely, configure * @param {Object} dataObj contains json data of the chart */ MSSplineAreaDataset.prototype.configureAttributes = function configureAttributes(dataObj) { _AreaDataset.prototype.configureAttributes && _AreaDataset.prototype.configureAttributes.call(this, dataObj); _spline2['default'].call(this); }; /** * Function to get the maximum and minimum from dataset * @return {Object} contains max, min value */ MSSplineAreaDataset.prototype.getDataLimits = function getDataLimits() { return { max: this.config.maxValue, min: this.config.minValue }; }; /** * Draws the plots * * @memberof MSSplineAreaDataset */ MSSplineAreaDataset.prototype.drawPlots = function drawPlots() { var dataSet = this, conf = dataSet.config, chart = dataSet.getFromEnv('chart'), chartConfig = chart.config, len, i, num, xAxis = dataSet.getFromEnv('xAxis'), xPos, yPos, lastXPos, lastYPos = null, linePathArr = [], dataTemp = [], pathObject, config, dataStore = dataSet.components.data, dataObj, setElement, hotElement, setValue, connectNullData = chartConfig.connectnulldata, minimizeTendency = chartConfig.minimizetendency, plotBorderColor = conf.plotbordercolor, plotBorderAlpha = conf.plotborderalpha, plotBorderDashStyle = conf.plotBorderDashStyle, plotBorderThickness = conf.plotborderthickness, container = dataSet.getContainer(), pathArr = [], splineElementDummy = dataSet.getGraphicalElement('splineElement'), splineElement, colorArr = conf.fillColor, removeDataArr = dataSet.components.removeDataArr || [], removeDataArrLen = removeDataArr.length, shadowContainer = container && container.shadowGroup, shadow = conf.shadow, hoverEffects, visible = dataSet.getState('visible'), anchorAlpha, radius, attr, animState, isAnchorVisible, anchorShadow, anchorProps = {}, isOnlyLineBorder = !chartConfig.drawfullareaborder, connectorDummy = dataSet.getGraphicalElement('connector'), connector, animationManager = dataSet.getFromEnv('animationManager'), imageElement, splineElementAttr, connectorAttr, scrollMinVal, scrollMaxVal, _oldStartIndex = conf._oldStartIndex, _oldEndIndex = conf._oldEndIndex, JSONData = dataSet.config.JSONData, // take the series type seriesType = JSONData.renderas || chart.config.defaultDatasetType, isSplineArea = /area/ig.test(seriesType); conf.imagesLoaded = 0; if (!dataStore) { dataStore = dataSet.components.data; } len = xAxis.getTicksLen(); scrollMinVal = conf.scrollMinVal; scrollMaxVal = conf.scrollMaxVal; if (scrollMinVal > _oldStartIndex) { dataSet.flushOnScroll(_oldStartIndex, scrollMinVal > _oldEndIndex ? _oldEndIndex : scrollMinVal); } if (scrollMaxVal < _oldEndIndex) { dataSet.flushOnScroll(scrollMaxVal < _oldStartIndex ? _oldStartIndex : scrollMaxVal, _oldEndIndex); } conf._oldStartIndex = scrollMinVal; conf._oldEndIndex = scrollMaxVal; for (i = scrollMinVal; i < scrollMaxVal; i++) { dataObj = dataStore[i]; if (!dataObj) { continue; } config = dataObj && dataObj.config; setValue = config.setValue; anchorProps = config.anchorProps; anchorShadow = anchorProps.shadow; setElement = dataObj.graphics.element; hotElement = dataObj.graphics.hotElement; imageElement = dataObj.graphics.image; if (setValue === null) { setElement && setElement.hide(); hotElement && hotElement.hide(); imageElement && imageElement.hide(); if (!connectNullData) { lastYPos = null; } } else { yPos = config._Py; xPos = config._Px; if (visible === false) { yPos = config._Pby; } dataTemp.push({ x: xPos, y: yPos, lastXPos: lastXPos, lastYPos: lastYPos }); lastXPos = xPos; lastYPos = yPos; anchorAlpha = anchorProps.anchorAlpha; radius = anchorProps.radius; isAnchorVisible = radius && anchorAlpha; hoverEffects = config.hoverEffects; // Decide state for animation if (!setElement) { animState = 'appearing'; } else { if (visible && isAnchorVisible) { animState = 'updating'; } else { animState = 'disappearing'; } } // If anchor is image, draw it. Else, draw default anchor if (anchorProps.imageUrl) { dataSet.drawAnchorImage(dataObj); } else { attr = Object.assign({}, config.props.element.attr); if (animState === 'disappearing' || !visible) { attr = _lib.UNDEF; } setElement = dataObj.graphics.element = animationManager.setAnimation({ el: setElement || 'path', attr: attr, container: container.plotGroup, component: dataSet, label: 'anchor' }); imageElement && imageElement.hide(); setElement && setElement.show().shadow(anchorShadow, container.anchorShadowGroup).data('anchorRadius', anchorProps.radius).data('anchorHoverRadius', hoverEffects.anchorRadius).data('eventArgs', config.eventArgs); if (hoverEffects.enabled) { setElement && setElement.data('anchorRadius', anchorProps.radius).data('anchorHoverRadius', hoverEffects.anchorRadius).data('hoverEnabled', hoverEffects.enabled).data(SETROLLOVERATTR, hoverEffects.attrs.setRolloverAttr).data(SETROLLOUTATTR, hoverEffects.attrs.setRolloutAttr); } } } } num = len; pathObject = (0, _mssplinePath.getSplinePath)(dataTemp, config && config._Pby, minimizeTendency, isSplineArea, num); pathArr = pathObject.closedPath; pathArr = pathArr.join(); // Attributes of spline element splineElementAttr = { path: pathArr, stroke: (0, _lib.toRaphaelColor)({ color: plotBorderColor, alpha: plotBorderAlpha }), 'stroke-width': isOnlyLineBorder ? 0 : plotBorderThickness, fill: (0, _lib.toRaphaelColor)(colorArr), 'stroke-linecap': 'round', 'stroke-linejoin': plotBorderThickness > MAX_MITER_LINEJOIN ? 'round' : 'miter', 'stroke-dasharray': plotBorderDashStyle }; // if dataset is not visible then, no attrs is set if (!dataSet.getState('visible')) { splineElementAttr = _lib.UNDEF; } // Drawing/Reuse Spline Area splineElement = animationManager.setAnimation({ el: splineElementDummy || 'path', attr: splineElementAttr, container: container.commonElemsGroup, component: dataSet, label: 'line' }); // if the splineElement is removed then, remove it from graphical element of dataset if (!splineElement && splineElementDummy) { dataSet.removeGraphicalElement(splineElementDummy); } if (!splineElementDummy) { dataSet.addGraphicalElement('splineElement', splineElement); } if (pathArr === BLANKSTRING || !dataSet.getState('visible')) { splineElement && splineElement.hide(); } else { splineElement.show().shadow(shadow, shadowContainer); } if (isOnlyLineBorder) { // Attributes of connector connectorAttr = { path: linePathArr, stroke: (0, _lib.toRaphaelColor)({ color: plotBorderColor, alpha: plotBorderAlpha }), 'stroke-width': plotBorderThickness, 'stroke-linecap': 'round', 'stroke-linejoin': plotBorderThickness > MAX_MITER_LINEJOIN ? 'round' : 'miter', 'stroke-dasharray': plotBorderDashStyle, name: 'connector' }; // Draw/reuse connector connector = animationManager.setAnimation({ el: connectorDummy || 'path', attr: connectorAttr, container: container.areaGroup, state: !connectorDummy ? 'appearing' : dataSet.getState('visible') ? 'updating' : 'disappearing', component: dataSet, label: 'line' }); if (!connectorDummy) { dataSet.addGraphicalElement('connector', connector); } } for (i = 0; i < removeDataArrLen; i++) { dataSet._removeDataVisuals(removeDataArr.shift()); } }; /** * Returns the name of the component * @return {string} The name of the component, in this case 'column'. */ MSSplineAreaDataset.prototype.getName = function getName() { return 'splinearea'; }; return MSSplineAreaDataset; }(_area2['default']); exports['default'] = MSSplineAreaDataset; /***/ }), /* 511 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * getSplineExtremities is called to get back the maximum and minimum y values of the vertical envelope * of a spline. The data may contain null data values, to be tackled based on the connectNullData setting. * For connectNullData = 0, the curve splits into separate spline curves, to be tackled via recursivion, * as below. The parameters index and limits are left blank for the initial call to this method, used only * for recursion, tackled from within the method. */ var getSplineExtremities = function getSplineExtremities(data, chartWidth, connectNullData, index, limits) { // array to hold the pertinent data only, required for gradients' calculations var arrKnot = [], validValueFound = false, u = index || 0; limits = limits || { max: Number.MIN_VALUE, min: Number.MAX_VALUE }; // populating arrKnot with pertinent data by iterating and checking for (; u < data.length; ++u) { // checking for if the first valid data value is found if (!validValueFound) { // if data value is valid if (!isNaN(data[u].config.setValue) && data[u].config.setValue !== null) { validValueFound = true; // just ingore the null/invalid data value, for the first valid data value is yet to be found } else { continue; } // reach this position if the first valid data value is found for this data value itself arrKnot.push({ index: u, y: data[u].config.setValue }); // if valid first data value is already found } else { // for invalid data value if (isNaN(data[u].config.setValue) || data[u].config.setValue === null) { if (connectNullData) { // just ignore the data continue; } else { // split here, to end the curve and start a new curve break; } } else { arrKnot.push({ index: u, y: data[u].config.setValue }); } } } // spline curve is possible for a set of plots with more than 2 points if (arrKnot.length > 2) { // Examine the spline curve to find the min-max vertically evalSplineExtremities(arrKnot, chartWidth, limits); } // recursion is required for the case of a series splitted into multiple subset of points due to // existence of null data entries in the series if (u < data.length && !connectNullData) { getSplineExtremities(data, chartWidth, connectNullData, u, limits); } return limits; }, /** * * evalSplineExtremities is called to evaluate the vertical extremities of the bounding box of the spline. */ evalSplineExtremities = function evalSplineExtremities(arrKnot, chartWidth, limits) { // object to store gradients at spline plots var objGrad = {}, u, i, t, calcValue, delX; // Below, each gradient is initialised to zero for (i = 0; i < arrKnot.length; ++i) { // getting the original index for this data t = arrKnot[i].index; // initialised to zero objGrad['D' + t] = 0; } // The following iteration is a mathematical purpose - iterative method of approximation with faster // convergence. The more the number of iteration, more precise are the approximate solutions. for (u = 0; u < 10; ++u) { // iteration for convergence towards actual solutions for (i = 0; i < arrKnot.length; ++i) { if (i === 0) { calcValue = (3 * (arrKnot[i + 1].y - arrKnot[i].y) - objGrad['D' + arrKnot[i + 1].index]) / 2; } else if (i === arrKnot.length - 1) { calcValue = (3 * (arrKnot[i].y - arrKnot[i - 1].y) - objGrad['D' + arrKnot[i - 1].index]) / 2; } else { calcValue = (3 * (arrKnot[i + 1].y - arrKnot[i - 1].y) - objGrad['D' + arrKnot[i + 1].index] - objGrad['D' + arrKnot[i - 1].index]) / 4; } // gradient value updated in repository for use in subsequent loop/turn for faster convergence objGrad['D' + arrKnot[i].index] = calcValue; } } // Since, canvas width is not ready as yet, chart width is used instead to get as close as possible to // the required x-interval between two consecutive spline plots delX = Math.round(chartWidth / (arrKnot.length - 1)); // each spline constitutes of a number of smaller curves, each joining two consecutive pioints. for (i = 1; i < arrKnot.length; ++i) { // find the max-min y-values for the bounding box of the unit curve getSegmentExtremities(i, arrKnot, objGrad, limits, delX); } }, /** * getSegmentExtremities method is aclled to process unit curves constituting a spline * and evaluate the vertical limits of the curve. */ getSegmentExtremities = function getSegmentExtremities(index, data, objGradientStore, limits, delX) { // storing the reference of the repository of coordinates of the points var arrKnot = data, i = index, j = 0, slope1, slope2, a1, a2, a3, a4, maxY, minY, k, n, t, y1; // slopes of the curve at the two extremes of the spline slope1 = objGradientStore['D' + arrKnot[j].index]; slope2 = objGradientStore['D' + arrKnot[i].index]; // calculating the four coefficients characterising the cubic polynomial a1 = arrKnot[j].y; a2 = slope1; a3 = 3 * (arrKnot[i].y - arrKnot[j].y) - 2 * slope1 - slope2; a4 = 2 * (arrKnot[j].y - arrKnot[i].y) + slope1 + slope2; maxY = limits.max; minY = limits.min; for (k = 0, n = delX; k <= n; k++) { t = k / n; y1 = a1 + a2 * t + a3 * t * t + a4 * t * t * t; if (y1 < minY) { minY = y1; } if (y1 > maxY) { maxY = y1; } } limits.max = maxY; limits.min = minY; }, _calculateMaxMin = function _calculateMaxMin() { var dataset = this, conf = dataset.config, chart = dataset.getFromEnv('chart'), chartConf = dataset.getFromEnv('chartConfig'), chartWidth = chart.config.origRenderWidth, connectNullData = chartConf.connectnulldata, minimizeTendency = chartConf.minimizetendency, dataStore = dataset.components.data, infMin = Number.MIN_VALUE, infMax = Number.MAX_VALUE, limits; if (minimizeTendency === 0) { limits = getSplineExtremities(dataStore, chartWidth, connectNullData); conf.maxValue = Math.max(conf.maxValue, limits.max); conf.minValue = Math.min(conf.minValue, limits.min); if (conf.maxValue === infMin) { conf.maxValue = 0; } if (conf.minValue === infMax) { conf.minValue = 0; } } }; exports['default'] = _calculateMaxMin; /***/ }), /* 512 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var M = 'M', L = 'L', Z = 'Z', R = 'R', C = 'C', math = Math, mathSqrt = math.sqrt, mathAbs = math.abs, getSlope = function getSlope(x1, y1, x2, y2) { return (y2 - y1) / (x2 - x1); }, getPointY = function getPointY(x, m, x1, y1) { return (x - x1) * m + y1; }, getPointX = function getPointX(y, m, x1, y1) { return (y - y1) / m + x1; }, evalX = function evalX(x1, y1, x2, y2) { var sinTheta = (y2 - y1) / mathSqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)), rearPart = mathAbs(0.5 * sinTheta), frontPart = 1 - rearPart; return x1 * rearPart + x2 * frontPart; }, cmrcManager = function cmrcManager(curveArr, appendClosePath, endXPos, endYPos) { var len = curveArr.length, lastCurveCommandArr = curveArr[len - 1], len2 = lastCurveCommandArr.length, command = lastCurveCommandArr[0], lastRecorderXPos = lastCurveCommandArr[len2 - 2]; // drawing can not continue with less that two cordinates if (len2 < 3) { return; } if ((command === R || command === C) && len2 === 3) { // draw a straight line instead curveArr[len - 1][0] = L; } if (appendClosePath) { curveArr.push([L, lastRecorderXPos, endYPos, endXPos, endYPos, Z]); } }; /** * Returns the spline path. * * @param {Object} dataTemp The data object * @param {Object} yBasePos yAxis base position * @param {Boolean} minTend The chart's minimizetendency value * @param {Boolean} isSplineArea Whether spline area or not * @param {Number} num The xAxis length * * @return {Object} - The spline path */ function getSplinePath(dataTemp, yBasePos, minTend, isSplineArea, num) { var minimizeTendency = minTend, arrS = [null], curvePath = [], linePath = [], lastArrLength, lastObj, y1, y0, y2, x1, x0, x2, lastYPos, lastXPos, lineArrLen, slope, point, anchorX, anchorY, anchorX0, anchorY0, slopePrev, arrLen, startingIndex, tempArr, startXPos, prevPoint, nextPoint, i, len; for (i = 0, len = dataTemp.length; i < len; i += 1) { point = dataTemp[i]; prevPoint = dataTemp[i - 1] || {}; nextPoint = dataTemp[i + 1] || {}; x1 = point.x; y1 = point.y; x0 = prevPoint.x; y0 = prevPoint.y; x2 = nextPoint.x; y2 = nextPoint.y; lastYPos = point.lastYPos; lastXPos = point.lastXPos; arrLen = curvePath.length; lineArrLen = linePath.length; if (minimizeTendency) { // The new algo to find the spline path if (lastYPos !== null) { lastObj = tempArr; if (i === dataTemp.length - 1) { slopePrev = arrS[i - startingIndex - 1]; anchorX = (x1 + x0) / 2; anchorX0 = anchorX; anchorY0 = getPointY(anchorX0, slopePrev, x0, y0); if (y0 > y1 && anchorY0 < y1 || y0 < y1 && anchorY0 > y1) { anchorY0 = y1; anchorX0 = getPointX(anchorY0, slopePrev, x0, y0); } tempArr.push(anchorX0, anchorY0, anchorX, (y1 + y0) / 2, x1, y1); curvePath.push(tempArr); linePath.push(tempArr); isSplineArea && cmrcManager(curvePath, true, startXPos, yBasePos); isSplineArea && cmrcManager(linePath, false); } else { slopePrev = arrS[i - startingIndex - 1]; // High and Low if (y0 > y1 && y2 >= y1 || y0 < y1 && y2 <= y1) { slope = 0; anchorX = evalX(x0, y0, x1, y1); anchorY = y1; if (i - startingIndex !== 1) { anchorX0 = anchorX; anchorY0 = getPointY(anchorX0, slopePrev, x0, y0); if (y0 > y1 && anchorY0 < y1 || y0 < y1 && anchorY0 > y1) { anchorY0 = y1; anchorX0 = getPointX(anchorY0, slopePrev, x0, y0); } tempArr.push(anchorX0, anchorY0, anchorX, anchorY, x1, y1); } else { tempArr.push((x1 + x0) / 2, (y1 + y0) / 2, anchorX, anchorY, x1, y1); } } else if (y0 === y1) { slope = 0; tempArr.push(x0, y0, x1, y1, x1, y1); // Rise and decline } else if (y0 > y1 && y1 > y2 || y0 < y1 && y1 < y2) { slope = getSlope(x0, y0, x2, y2); anchorX = evalX(x0, y0, x1, y1); anchorY = getPointY(anchorX, slope, x1, y1); if (y0 > y1 && anchorY > y0 || y0 < y1 && anchorY < y0) { anchorY = y0; anchorX = getPointX(anchorY, slope, x1, y1); } if (i - startingIndex !== 1) { anchorX0 = anchorX; anchorY0 = getPointY(anchorX0, slopePrev, x0, y0); if (y0 > y1 && anchorY0 < y1 || y0 < y1 && anchorY0 > y1) { anchorY0 = y1; anchorX0 = getPointX(anchorY0, slopePrev, x0, y0); } tempArr.push(anchorX0, anchorY0, anchorX, anchorY, x1, y1); } else { tempArr.push((x1 + x0) / 2, (y1 + y0) / 2, anchorX, anchorY, x1, y1); } } arrS.push(slope); } } else if (lastYPos === null && i !== 0) { // Raphael Catmull-Rom Curve To fix // We can not draw a curve with two datapoints // If we have only 2 datapoints, we push the last one again lastObj || (lastObj = []); if (lastObj[0] === C) { curvePath.push(tempArr); linePath.push(tempArr); isSplineArea && cmrcManager(curvePath, true, startXPos, yBasePos); isSplineArea && cmrcManager(linePath, false); } curvePath.push([M, x1, y1]); linePath.push([M, x1, y1]); startXPos = x1; tempArr = [C]; startingIndex = i; arrS = [null]; } else { // first start curvePath.push([M, x1, y1]); // line linePath.push([M, x1, y1]); // store the staring x position // this will be nedded to close the line startXPos = x1; tempArr = [C]; startingIndex = i; } } else { // Default algo to find the spline path if (lastYPos !== null) { // This means we have a two consecutive valid points // and we will draw a curve. if (arrLen >= 2) { // This means atleast one command with two values has been inserted. // If the last inserted command is not a Catmull-Rom curve command R // we have to push one. if (curvePath[arrLen - 1][0] === M) { curvePath.push([R]); } // line if (linePath[lineArrLen - 1][0] === M) { linePath.push([R]); } // update properties arrLen = curvePath.length; lineArrLen = linePath.length; lastObj = curvePath[arrLen - 1]; lastArrLength = lastObj.length; curvePath[arrLen - 1].push(x1); curvePath[arrLen - 1].push(y1); // linePath[lineArrLen - 1].push(x1); linePath[lineArrLen - 1].push(y1); // Now for all area charts we need to close path when drawing ends // In this case if we have reached the end of data, we close. if (i === num - 1) { // End of drawing // Conncet only if the last command is a curve if (lastObj[0] === R) { // apply Catmull-Rom-Curve management. cmrcManager(curvePath, true, startXPos, yBasePos); cmrcManager(linePath, false); } } } else { // first start curvePath.push([M, lastXPos, lastYPos]); curvePath.push([R, x1, y1]); // line linePath.push([M, lastXPos, lastYPos]); linePath.push([R, x1, y1]); // store the staring x position // this will be nedded to close the line startXPos = lastXPos; } } else if (lastYPos === null && arrLen >= 2) { // Raphael Catmull-Rom Curve To fix // We can not draw a curve with two datapoints // If we have only 2 datapoints, we push the last one again lastObj = curvePath[arrLen - 1]; if (lastObj[0] === R) { cmrcManager(curvePath, true, startXPos, yBasePos); cmrcManager(linePath, false); } curvePath.push([M, x1, y1]); linePath.push([M, x1, y1]); startXPos = x1; } } } // If the line is Drawn [R] not closed [!Z] and we have reached the end, // We need to close the path with the previous one lastObj = curvePath[curvePath.length - 1]; if (isSplineArea && lastObj) { lastArrLength = lastObj.length; if (lastObj[lastArrLength - 1] !== Z && (lastObj[0] === R || lastObj[0] === C)) { // apply Catmull-Rom-Curve management. cmrcManager(curvePath, true, startXPos, yBasePos); cmrcManager(linePath, false); } } if (!isSplineArea) { curvePath = minimizeTendency ? curvePath : linePath; curvePath.length >= 2 && cmrcManager(curvePath, false); } return { closedPath: curvePath, openPath: linePath }; } exports.getSplinePath = getSplinePath; /***/ }), /* 513 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); /** * Function to calculate the spline area initial path from given pathArr * @param {Array} pathArr contains the base path of the area * @return {Array} basePathArr contains the initial path for spline area animation */ function getBaseSplinePath(pathArr) { var pathArrLen = pathArr.length, basePathArr = [], pathInstruction = void 0, storePathInstruction = void 0, pathRepetitionStarted = false, newPathStarted = true, index = void 0; for (index = 0; index < pathArrLen; ++index) { pathInstruction = pathArr[index]; if (newPathStarted) { basePathArr.push(pathInstruction); // For closing the current area, we need the starting point storePathInstruction = (0, _lib.extend2)([], pathInstruction); // Started collecting points for area, // thereby setting this flag to false to detect // repetition of path newPathStarted = false; continue; } if (pathInstruction === 'Z') { // We need to close the sub-path of area with the stored path instruction // We also need to start calculating the path for next area, therefore, // we change the flag to initials. newPathStarted = true; pathRepetitionStarted = false; storePathInstruction[0] = 'L'; basePathArr.push(storePathInstruction, 'Z'); continue; } if (pathRepetitionStarted) { // We ignore the repeated paths for calculation of area. continue; } basePathArr.push(pathInstruction); if (pathInstruction.toString() === pathArr[index - 1].toString()) { // Repetition detected, will ignore further points pathRepetitionStarted = true; } } return basePathArr; } exports['default'] = { '*.dataset.splinearea': function datasetSplinearea() { return { 'anchor.appearing': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, startEnd: { start: 0.5, end: 1 }, slot: 'plot' }], 'anchor.updating': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'anchor.disappearing': [{ finalAttr: { opacity: 0, 'fill-opacity': 0, 'stroke-opacity': 0 }, slot: 'final' }], 'line.appearing': function lineAppearing(inputJSON) { var dataset = inputJSON.component, dataStore = dataset.components.data, initialPath = dataset.getLinePath(dataStore, null, 'zero'), finalAttr = inputJSON.attr; return [{ initialAttr: { opacity: 0, path: getBaseSplinePath(initialPath.getPathArr()) }, finalAttr: { opacity: 1, path: finalAttr && finalAttr.path }, startEnd: { start: 0, end: 0.5 }, slot: 'plot', hookFn: function hookFn() { this.attr({ opacity: 1 }); } }]; }, 'label.appearing': [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }], 'label.updating': function labelUpdating() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; }, 'group.appearing': function groupAppearing(inputJSON) { if (inputJSON.attr.name === 'label-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } else if (inputJSON.attr.name === 'plot-group') { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, startEnd: { start: 0.5, end: 1 }, slot: 'plot' }]; } else { return [{ initialAttr: { opacity: 1 }, finalAttr: { opacity: 1 }, slot: 'final' }]; } } }; } }; /***/ }), /* 514 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _line = __webpack_require__(449); var _line2 = _interopRequireDefault(_line); var _lib = __webpack_require__(125); var _spline = __webpack_require__(511); var _spline2 = _interopRequireDefault(_spline); var _dependencyManager = __webpack_require__(132); var _mssplinePath = __webpack_require__(512); var _index = __webpack_require__(515); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF; (0, _dependencyManager.addDep)({ name: 'mssplineAnimation', type: 'animationRule', extension: _index2['default'] }); var MSSplineDataset = function (_LineDataset) { _inherits(MSSplineDataset, _LineDataset); function MSSplineDataset() { _classCallCheck(this, MSSplineDataset); return _possibleConstructorReturn(this, _LineDataset.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ MSSplineDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Sets the name of the component * @return {string} name */ MSSplineDataset.prototype.getName = function getName() { return 'spline'; }; /** * function to create component and configure and also configure the chart * It creates components which are depend on data and configure them and also configure chart * It calls helper function namely, configure * @param {Object} dataObj contains json data of the chart */ MSSplineDataset.prototype.configureAttributes = function configureAttributes(dataObj) { _LineDataset.prototype.configureAttributes && _LineDataset.prototype.configureAttributes.call(this, dataObj); _spline2['default'].call(this); }; /** * Function to get the maximum and minimum from dataset * @return {Object} contains max, min value */ MSSplineDataset.prototype.getDataLimits = function getDataLimits() { return { max: this.config.maxValue, min: this.config.minValue }; }; /** * Function to draw line * Line chart has a setLevel attribute 'color', thus line segments can have different colors, * but a line path can support only one color, so we are making multiple paths depending on the * color applied. lineOb is object having all line elements and key is the color and stroke combined, * thus all line segment having same color is grouped under one key. elements having different * line color is animated by fading in and out, on main color's line element transition is applied. */ MSSplineDataset.prototype.drawCommonElements = function drawCommonElements() { var dataset = this, dataStore = dataset.components.data, dsConfig = dataset.config, connectNullData = Number(dataset.getFromEnv('chartConfig').connectnulldata), xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), // styles lineDashStyle = dsConfig.lineDashStyle, lineThickness = dsConfig.linethickness, dataTemp = [], lastYPos = null, lastXPos, colorHash, lineColorObj = { color: dsConfig.linecolor, alpha: dsConfig.alpha }, lim = { x: xAxis.getLimit(), y: yAxis.getLimit() }, i, ii = dataset.getState('visible') ? dataStore.length : 0, lineOb = dsConfig.lineOb || {}, dataObj, config, setValue, startIndex = 0, endIndex, tempStore = [], chart = this.getFromEnv('chart'), isSplineArea = /area/ig.test(chart.defaultDatasetType); // Setting min and max pixels lim.x.minPixel = xAxis.getPixel(lim.x.min); lim.x.maxPixel = xAxis.getPixel(lim.x.max); lim.y.minPixel = yAxis.getPixel(lim.y.min); lim.y.maxPixel = yAxis.getPixel(lim.y.max); lim.y.base = yAxis.getPixel(0); lim.x.base = xAxis.getPixel(0); for (i = 0; i < ii; ++i) { dataObj = dataStore[i]; if (!dataObj) { continue; } config = dataObj.config || {}; setValue = config.setValue; config._Pbx = UNDEF; config._Pby = UNDEF; // Pushing configurations to save // reference for later tempStore[i] = { config: { _Px: config._Px, _Py: config._Py, setValue: config.setValue } }; if (!connectNullData && (setValue === null || setValue === UNDEF)) { lastYPos = null; continue; } dataTemp.push({ x: config._Px, y: config._Py, lastYPos: lastYPos, lastXPos: lastXPos }); lastYPos = config._Py; lastXPos = config._Px; } dsConfig.pathStartIndex = startIndex; dsConfig.pathEndIndex = endIndex; colorHash = 'default'; lineOb[colorHash] = lineOb[colorHash] || {}; lineOb[colorHash].used = true; lineOb[colorHash].path = [{ pathArr: (0, _mssplinePath.getSplinePath)(dataTemp, yAxis.getPixel(yAxis.getAxisBase()), chart.config.minimizetendency, isSplineArea).closedPath, path2Arr: [], getPathArr: function getPathArr() { var pathObj = this, pathArr = pathObj.pathArr, path2Arr = pathObj.path2Arr; if (pathArr.length || path2Arr.length) { return pathArr.concat(path2Arr); } else { return []; } } }]; lineOb[colorHash].attr = { 'stroke-dasharray': lineDashStyle, 'stroke-width': lineThickness, 'stroke': (0, _lib.toRaphaelColor)(lineColorObj), 'stroke-linecap': 'round' }; dataset._drawCommonElementsHelper(lineOb); // Saving for next dataset.config.lineOb = lineOb; dsConfig.prevLim = lim; // Storing current datastore dsConfig.prevDataStore = tempStore; }; return MSSplineDataset; }(_line2['default']); exports['default'] = MSSplineDataset; /***/ }), /* 515 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _index = __webpack_require__(452); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { '*.dataset.spline': _index2['default']['*.dataset.line'] }; /***/ }), /* 516 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var math = Math, mathMin = math.min, mathMax = math.max, mathAbs = math.abs, UNDEF; /** * ColumnMultiSeriesgroup basically manages all the position of multiseries columns side by side. * suppose multiseries column chart contains 2 dataset now what will be the column width and * position to accomodate all the columns. This manager conveys the column width and position * for every column plots to its children */ var ColumnMultiSeriesgroup = function (_ComponentInterface) { _inherits(ColumnMultiSeriesgroup, _ComponentInterface); /** * constructor function this class */ function ColumnMultiSeriesgroup() { _classCallCheck(this, ColumnMultiSeriesgroup); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this.setState('visible', true); return _this; } /** * Sets the type of the component * @return {string} type */ ColumnMultiSeriesgroup.prototype.getType = function getType() { return 'group'; }; /** * Sets the name of the component * @return {string} name */ ColumnMultiSeriesgroup.getName = function getName() { return 'columnMultiSeriesgroup'; }; /** * Sets the name of the component * @return {string} name */ ColumnMultiSeriesgroup.prototype.getName = function getName() { return 'columnMultiSeriesgroup'; }; /** * function to configure json data * @param {Object} managerJSON to set json data in configuration * @return {boolean} Indiactes whether the configuration was successful or not */ ColumnMultiSeriesgroup.prototype.preConfigure = function preConfigure(managerJSON) { if (!managerJSON) { return false; } this.config.JSONData = managerJSON; _ComponentInterface.prototype.preConfigure.call(this, managerJSON); }; /** * function to configure json data * @param {Object} managerJSON to set json data in configuration * @return {boolean} Indiactes whether the configuration was successful or not */ ColumnMultiSeriesgroup.prototype.configure = function configure(managerJSON) { if (!managerJSON) { return false; } _ComponentInterface.prototype.configure.call(this, managerJSON); }; /** * set visibility of this manager by checking the visbility of the children */ ColumnMultiSeriesgroup.prototype.setVisibility = function setVisibility() { var manager = this, numVisibleDataset = 0; manager._mapChildren(function (child) { child.setVisibility && child.setVisibility(); }); manager._mapChildren(function (child) { child.getState('visible') && numVisibleDataset++; }); manager.setState('visible', !!numVisibleDataset); }; /** * Create child containers */ ColumnMultiSeriesgroup.prototype.createContainer = function createContainer() { var manager = this, animationManager = manager.getFromEnv('animationManager'), key = void 0, parent = manager.getLinkedParent(), pContainer = void 0, parentChildContainers = parent.getChildContainer(); for (key in parentChildContainers) { pContainer = parentChildContainers[key]; !manager.getChildContainer(key) && manager.addChildContainer(key, animationManager.setAnimation({ el: 'group', attr: { name: 'manager-' + key }, component: manager, container: pContainer })); } }; /** * Sets the column dimentions * * @memberof ColumnMultiSeriesgroup */ ColumnMultiSeriesgroup.prototype.allocatePosition = function allocatePosition() { this.setColumnPosition(); }; /** * function call sync draw of its children */ ColumnMultiSeriesgroup.prototype.draw = function draw() { this.createContainer(); }; /** * function to calculate maximum canvas padding is required by the children of this manager * @return {Object} contains dimension required */ ColumnMultiSeriesgroup.prototype.getCanvasPadding = function getCanvasPadding() { var manager = this, dim, key, returnDimension = { paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 }; manager.setColumnPosition(); manager._mapChildren(function (child) { dim = !child.getState('removed') && child.getState('visible') && child.getCanvasPadding && child.getCanvasPadding() || {}; for (key in dim) { if (dim.hasOwnProperty(key)) { returnDimension[key] = Math.max(dim[key], returnDimension[key]); } } }); return returnDimension; }; /** * function to calculate column position and width */ ColumnMultiSeriesgroup.prototype.setColumnPosition = function setColumnPosition() { var manager = this, chartConfig = manager.getFromEnv('chartConfig'), chartAttr = manager.getFromEnv('chart-attrib'), xAxis = manager.getFromEnv('xAxis'), oldNumOfColumns = manager.getFromEnv('numOfColumns'), definedGroupPadding = chartConfig.plotSpacePercent, plotSpacePercent = mathMax((0, _lib.pluckNumber)(definedGroupPadding, 20) % 100, 0), groupPadding = plotSpacePercent / 200, xAxisZeroPos = xAxis.getPixel(0), xAxisFirstPos = xAxis.getPixel(1), maxColWidth = manager.getFromEnv('chart').isBar ? chartConfig.maxBarHeight : chartConfig.maxColWidth, groupMaxWidth = mathAbs(xAxisFirstPos - xAxisZeroPos), groupNetWidth = void 0, columnWidth = void 0, commonXShift = void 0, plotEffectivePadding = void 0, plotPaddingPercent = chartConfig.plotPaddingPercent, plotPadding = void 0, xPosFirst = void 0, xPosNext = void 0, isCrisp = true, groupNetHalfWidth = void 0, groupNetGapWidth = 4, overlapColumns = chartConfig.overlapColumns, count = 0, numOfColumns = 0; manager.addToEnv('groupMaxWidth', groupMaxWidth); manager._mapChildren(function (child) { if (!child.getState('removed') && child.getState('visible') !== false) { numOfColumns++; } }); manager.addToEnv('numOfColumns', numOfColumns); manager.addToEnv('numColDiff', (0, _lib.pluckNumber)(oldNumOfColumns - numOfColumns, 0)); groupNetWidth = (1 - definedGroupPadding * 0.01) * groupMaxWidth || mathMin(groupMaxWidth * (1 - groupPadding * 2), maxColWidth * (numOfColumns || 1)); // if plotSpacePercent is not defined explicitly in chart attributes then group net width // will be recalculated chartAttr.plotspacepercent === UNDEF && groupNetWidth >= chartConfig.canvasWidth / 2 && (groupNetWidth = groupMaxWidth - maxColWidth / 2); columnWidth = numOfColumns === 0 ? groupNetWidth : groupNetWidth / numOfColumns; plotPadding = numOfColumns > 1 ? !overlapColumns && plotPaddingPercent === UNDEF ? 4 : plotPaddingPercent > 0 ? columnWidth * plotPaddingPercent / 100 : 0 : 0; plotEffectivePadding = mathMin(columnWidth - 1, plotPadding); // columnWidth is subtracted by plotEffectivePadding to get space between // the columns for enhanced 3D effect. When overlapColumns is 0 // or plotPaddingPercent is present then // plotEffectivePadding has some value else it is 0 to give a overlapping effect. manager.addToEnv('plotWidth', columnWidth - plotEffectivePadding); commonXShift = -(numOfColumns / 2 * columnWidth - columnWidth / 2); manager._mapChildren(function (child) { if (!child.getState('removed') && child.getState('visible')) { child.addToEnv('shift', commonXShift + count * columnWidth + plotEffectivePadding / 2); count++; } }); groupNetHalfWidth = groupNetWidth / 2; xPosFirst = xAxisZeroPos - groupNetHalfWidth; xPosNext = xAxisFirstPos - groupNetHalfWidth; if (xPosNext - (xPosFirst + groupNetWidth) < groupNetGapWidth) { isCrisp = false; } if (plotSpacePercent === 0) { isCrisp = true; } manager.addToEnv('isCrisp', isCrisp); }; /** * function to accomodate the changes of its child and notify its parent for further action if its needed * @param {Object} updateInfo is an object with the informations about the changes in its child */ ColumnMultiSeriesgroup.prototype.childChanged = function childChanged() { var updateInfo = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manager = this, config = manager.config, parent = manager.getLinkedParent(), range = void 0, count = 0, prevVisiblity = manager.getState('visible'), changeInfo = {}, informParent = void 0; // get the number of visible children manager._mapChildren(function (child) { if (child.getState('visible')) { count++; } }); // set the manager visiblity according to number of children visible manager.setState('visible', !!count); // if the visiblity state changed then parent inform flag set to true prevVisiblity !== !!count && (informParent = true); // if the managers data limit get changed then also inform the parent if (updateInfo.dataLimitChanged !== false) { range = manager.getDataLimits(); if (range.min !== config.range.min || range.max !== config.range.max) { config.range.min = range.min; config.range.max = range.max; changeInfo.dataLimitChanged = true; informParent = true; } } // if the axis value got changed then inform parent // right now we do not change value padding on any type of update // if (updateInfo.paddingChanged !== false) { // padding = manager.getAxisValuePadding(); // if (padding.left !== config.padding.left || padding.right !== config.padding.right) { // config.padding.left = padding.left; // config.padding.right = padding.right; // changeInfo.paddingChanged = true; // informParent = true; // } // } if (informParent) { parent.childChanged && parent.childChanged(changeInfo); } else { manager.asyncDraw(); } }; /** * function to get value for axis padding from is children * @return {Object} with left and right member */ ColumnMultiSeriesgroup.prototype.getAxisValuePadding = function getAxisValuePadding() { var paddingObj = {}, axisPaddingLeft = -Infinity, axisPaddingRight = -Infinity; this._mapChildren(function (child) { if (child.getState('removed')) { return; } paddingObj = child.getAxisValuePadding && child.getAxisValuePadding() || {}; axisPaddingLeft = Math.max(axisPaddingLeft, paddingObj.left || -Infinity); axisPaddingRight = Math.max(axisPaddingRight, paddingObj.right || -Infinity); }); if (axisPaddingLeft === -Infinity) { axisPaddingLeft = 0; } if (axisPaddingRight === -Infinity) { axisPaddingRight = 0; } if (!this.config.padding) { this.config.padding = {}; this.config.padding.left = axisPaddingLeft; this.config.padding.right = axisPaddingRight; } return { left: axisPaddingLeft, right: axisPaddingRight }; }; /** * function to get data limits from its child datasets * return minimun and maximum value among the datasets limit * @param {boolean} allVisible whether consider all the datasets are visible or not * @return {Object} [min, max] */ ColumnMultiSeriesgroup.prototype.getDataLimits = function getDataLimits(allVisible) { var manager = this, min = +Infinity, max = -Infinity, maxminObj = void 0, numOfColumns = 0, getMaxMin = function getMaxMin(_maxminObj) { max = Math.max(max, _maxminObj.max); min = Math.min(min, _maxminObj.min); }; manager._mapChildren(function (child) { if (child.getState('removed')) { return; } if (child.getState('visible') === false) { if (allVisible) { maxminObj = child.getDataLimits(allVisible); getMaxMin(maxminObj); } return; } numOfColumns++; maxminObj = child.getDataLimits(allVisible); getMaxMin(maxminObj); }); if (!numOfColumns) { manager.setState('visible', false); } else { manager.setState('visible', true); } if (!this.config.range) { this.config.range = {}; this.config.range.min = this.config.dataMin; this.config.range.max = this.config.dataMax; } return { max: max, min: min }; }; /** * it return the status of dataset visiblity * @return {boolean} returns the visiblity status of dataset */ ColumnMultiSeriesgroup.prototype.isVisible = function isVisible() { return !this.isNotVisible; }; return ColumnMultiSeriesgroup; }(_componentInterface.ComponentInterface); exports['default'] = ColumnMultiSeriesgroup; /***/ }), /* 517 */, /* 518 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _mscartesian = __webpack_require__(459); var _mscartesian2 = _interopRequireDefault(_mscartesian); var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _columnMultiseries = __webpack_require__(516); var _columnMultiseries2 = _interopRequireDefault(_columnMultiseries); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * Class for multiseries column charts and who depend on this class * @type {class} */ var MSColumn2D = function (_MSCartesian) { _inherits(MSColumn2D, _MSCartesian); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSColumn2D.getName = function getName() { return 'MSColumn2D'; }; /** * Sets the name of the component * @return {string} name */ MSColumn2D.prototype.getName = function getName() { return 'MSColumn2D'; }; /** * constructor function of this class */ function MSColumn2D() { _classCallCheck(this, MSColumn2D); var _this = _possibleConstructorReturn(this, _MSCartesian.call(this)); _this.eiMethods = {}; return _this; } /** * parse defualt configuration of the chart */ MSColumn2D.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSCartesian.prototype.__setDefaultConfig.call(this); this.config.friendlyName = 'Multi-series Column Chart'; this.config.defaultDatasetType = 'column'; this.config.enablemousetracking = true; }; /** * This method return the dataset definations for this charts * @return {Object} Column dataset definition */ MSColumn2D.prototype.getDSdef = function getDSdef() { return _column2['default']; }; /** * This method return the dataset-group definations for this charts * @return {Object} Multiseries column group definition */ MSColumn2D.prototype.getDSGroupdef = function getDSGroupdef() { return _columnMultiseries2['default']; }; return MSColumn2D; }(_mscartesian2['default']); exports['default'] = MSColumn2D; /***/ }), /* 519 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.scrollTo = undefined; var _schedular = __webpack_require__(136); /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * method to scroll to a parcticular position of the scrollable chart * considering the start of the scrollable scale to be 0 and end as 1 * @param {number} value in between 0 and 1 */ function scrollTo(value) { var chart = this.apiInstance; chart.addJob('scrollToAPoint', function () { if (value >= 0 && value <= 1) { var children = chart.getChildren && chart.getChildren(), xAxis = children.xAxis[0], scroller = xAxis.getChildren('scrollBar') && xAxis.getChildren('scrollBar')[0], scrollAnchor = scroller && scroller.getChildren('scrollAnchor')[0], limit = xAxis.getLimit && xAxis.getLimit(), visibleConfig = xAxis.getVisibleConfig && xAxis.getVisibleConfig(), visibleLength = visibleConfig.maxValue - visibleConfig.minValue, totalLength = limit.max - limit.min, start = value * (totalLength - visibleLength) + limit.min, end = start + visibleLength, previousValue = (visibleConfig.minValue - limit.min) / (totalLength - visibleLength); scrollAnchor.config.scrollPosition = value; chart.fireChartInstanceEvent('scrollStart', { scrollPosition: previousValue }); xAxis.setVisibleConfig(start, end); chart.fireChartInstanceEvent('scrollEnd', { previousScrollPosition: previousValue, scrollPosition: value }); } }, _schedular.priorityList.postRender); } exports.scrollTo = scrollTo; /***/ }), /* 520 */, /* 521 */, /* 522 */, /* 523 */, /* 524 */, /* 525 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(526); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var visibleStr = _lib.preDefStr.visibleStr, UNDEF = void 0, math = Math, mathMin = math.min, mathMax = math.max; (0, _dependencyManager.addDep)({ name: 'cartesianStackAnimation', type: 'animationRule', extension: _index2['default'] }); /** * CartesianStackgroup basically manages all plots position of stack charts (column and area) in stacking * Suppose there are 2 column plot in a stack chart then what will be the base and y position would be * calculated in this manager. This manager calculated sum for all the stacks. It calculats and sets base * position and y position for every single plot. */ var CartesianStackgroup = function (_ComponentInterface) { _inherits(CartesianStackgroup, _ComponentInterface); /** * constructor function this class */ function CartesianStackgroup() { _classCallCheck(this, CartesianStackgroup); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this.setState('visible', true); return _this; } /** * Sets the type of the component * @return {string} type */ CartesianStackgroup.prototype.getType = function getType() { return 'group'; }; /** * Sets the name of the component * @return {string} name */ CartesianStackgroup.getName = function getName() { return 'cartesianStackGroup'; }; /** * Sets the name of the component * @return {string} name */ CartesianStackgroup.prototype.getName = function getName() { return 'cartesianStackGroup'; }; /** * function to configure json data * @param {Object} managerJSON to set json data in configuration * @return {boolean} Indiactes whether the configuration was successful or not */ CartesianStackgroup.prototype.preConfigure = function preConfigure(managerJSON) { if (!managerJSON) { return false; } this.config.JSONData = managerJSON; _ComponentInterface.prototype.preConfigure.call(this, managerJSON); }; /** * function to configure json data * @param {Object} managerJSON to set json data in configuration * @return {boolean} Indiactes whether the configuration was successful or not */ CartesianStackgroup.prototype.configure = function configure(managerJSON) { if (!managerJSON) { return false; } _ComponentInterface.prototype.configure.call(this, managerJSON); }; /** * sets the skipping information for the given data set * @param {Object} skipObj contains skipping info of the dataset */ CartesianStackgroup.prototype.setSkippingInfo = function setSkippingInfo(skipObj) { var dataSet = this; dataSet.addToEnv('skipInfo', skipObj || { drawOnlyMap: [], plotsPerBin: 1, draw: [], hide: [], skippingApplied: false, dragHashMap: [], prevDrawArray: [] }); }; /** * method to get the skipping information of the dataset * @return {Object} contains the skipping information of the dataset */ CartesianStackgroup.prototype.getSkippingInfo = function getSkippingInfo() { return this.getFromEnv('skipInfo') || { drawOnlyMap: [], plotsPerBin: 1, draw: [], hide: [], skippingApplied: false, dragHashMap: [], prevDrawArray: [] }; }; /** * set visibility of this manager by checking the visbility of the children */ CartesianStackgroup.prototype.setVisibility = function setVisibility() { var numVisibleDataset = 0; this._mapChildren(function (child) { child.getState('visible') && numVisibleDataset++; }); this.setState('visible', !!numVisibleDataset); }; /** * Create child containers */ CartesianStackgroup.prototype.createContainer = function createContainer() { var manager = this, animationManager = manager.getFromEnv('animationManager'), key = void 0, parent = manager.getLinkedParent(), pContainer = void 0, parentChildContainers = parent.getChildContainer(); // create all types child container to reside graphics elements for the children of this manager. // because this stack manager is common for the all types of stacked dataset for (key in parentChildContainers) { pContainer = parentChildContainers[key]; !manager.getChildContainer(key) && manager.addChildContainer(key, animationManager.setAnimation({ el: 'group', attr: { name: 'manager-' + key }, container: pContainer, component: manager })); } // create the container for the sum labels to reside the graphic element of sum label // so that the transformation to can be applied on scrolling !manager.getContainer('sumLabelsLayer') && manager.addContainer('sumLabelsLayer', animationManager.setAnimation({ el: 'group', attr: { name: 'manager-sumLabelsLayer', 'class': 'fusioncharts-datalabels' }, label: 'group', container: parent.getChildContainer('sumLabelsLayer'), component: manager })); !manager.getChildContainer('commonElemGroup') && manager.addChildContainer('commonElemGroup', animationManager.setAnimation({ el: 'group', attr: { name: 'manager-common-elem-group' }, label: 'group', container: parent.getChildContainer('areaVcanvasGroup'), component: manager })); !manager.getChildContainer('anchorGroup') && manager.addChildContainer('anchorGroup', animationManager.setAnimation({ el: 'group', attr: { name: 'manager-anchor-group' }, label: 'group', container: parent.getChildContainer('areaVcanvasGroup'), component: manager })); }; /** * function call sync draw of its children */ CartesianStackgroup.prototype.draw = function draw() { this.createContainer(); this.drawSumValue(); }; /** * function to calculate plot position, max and min of manager in case a of stacked dataset */ CartesianStackgroup.prototype._setStackPosition = function _setStackPosition() { var manager = this, dataMin = +Infinity, dataMax = -Infinity, oldNumOfColumns = manager.getFromEnv('numOfColumns'), // transposeAxis = manager.getFromEnv('chartConfig').transposeAxis, numOfColumns = 0, stackValueArr = [], skipInfo = manager.getSkippingInfo && manager.getSkippingInfo() || {}, skippingDrawArray = skipInfo.draw || [], skipDrawArrayLenth = skippingDrawArray.length, skippingApplied = skipInfo.skippingApplied; manager._mapChildren(function (child) { if (child.getState('removed') || child.getState('visible') === false) { return; } numOfColumns++; var datum = void 0, data = child.getData(), i = void 0, j = void 0, setValue = void 0, stackedValue = 0, len = data && data.length, base = 0; if (skippingApplied) { len = skipDrawArrayLenth; } for (j = 0; j < len; j++) { i = skippingDrawArray[j] || j; datum = data[i]; if (datum && datum.config && datum.config.setValue !== UNDEF) { if (!stackValueArr[i]) { stackValueArr[i] = {}; } setValue = datum.config.setValue; stackValueArr[i].positive || (stackValueArr[i].positive = 0); stackValueArr[i].negative || (stackValueArr[i].negative = 0); if (setValue >= 0) { base = stackValueArr[i].positive; stackedValue = setValue + base; stackValueArr[i].positive = stackedValue; } else if (setValue < 0) { base = stackValueArr[i].negative; stackedValue = setValue + base; stackValueArr[i].negative = stackedValue; } if (setValue !== null) { stackValueArr[i].isNotNull = true; } dataMax = mathMax(stackedValue, dataMax); dataMin = mathMin(stackedValue, dataMin); datum.config._y = stackedValue; datum.config._b = base; } } }); manager.config.stackValues = stackValueArr; manager.config.dataMin = dataMin; manager.config.dataMax = dataMax; if (!numOfColumns) { manager.setState('visible', false); } else { manager.setState('visible', true); } manager.addToEnv('stackValues', stackValueArr); manager.addToEnv('numOfColumns', numOfColumns); manager.addToEnv('numColDiff', (0, _lib.pluckNumber)(oldNumOfColumns - numOfColumns, 0)); }; /** * Sets the stack position. * * @memberof CartesianStackgroup */ CartesianStackgroup.prototype.allocatePosition = function allocatePosition() { this._setStackPosition(); }; /** * Helper function for determining the xPos of sumLabel * @param {number} index The index of the sumLabel * @return {number} x-position */ CartesianStackgroup.prototype._getXpos = function _getXpos(index) { var manager = this, shift = manager.getFromEnv('shift') || 0, xAxis = manager.getFromEnv('xAxis'); return xAxis.getPixel(index) + shift; }; /** * function to draw sum value of the stack * It renders the sum value of the stacked plots * @param {number} [start=0] start index of sumValue label draw * @param {number} end end index of sumValue label draw */ CartesianStackgroup.prototype.drawSumValue = function drawSumValue() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var end = arguments[1]; var manager = this, config = manager.config, // shift = manager.getFromEnv('shift') || 0, // xAxis = manager.getFromEnv('xAxis'), yAxis = manager.getFromEnv('yAxis'), paper = manager.getFromEnv('paper'), animationManager = manager.getFromEnv('animationManager'), chart = manager.getFromEnv('chart'), isBar = chart.isBar, SmartLabel = manager.getFromEnv('smartLabel'), chartConfig = chart.config, canvasRight = chartConfig.canvasRight, chartAttrs = manager.getFromEnv('chart-attrib'), stack100percent = (0, _lib.pluckNumber)(chartConfig.stack100percent), rotateValues = chartConfig.rotatevalues ? 270 : 0, stackValues = config.stackValues, range = end || stackValues && stackValues.length, style = chartConfig.dataLabelStyle, i = void 0, xPos = void 0, yPos = void 0, bgColor = void 0, bdColor = void 0, labelDim = void 0, sumLabelsLayer = manager.getContainer('sumLabelsLayer'), sumLabels = manager.getGraphicalElement('sumLabels'), sumLabel = void 0, attrs = void 0, positive = void 0, negative = void 0, offsetY = void 0, displayValue = void 0, sumValue = void 0, prevLen = void 0, currLen = void 0, label = void 0, showsum = (0, _lib.pluckNumber)(chartAttrs.showsum, chart.showsum, 0); // @TODO sumValue layers and sumvalue containers needs to be validated. if (showsum) { // @TODO layer gets hide; have to fix sumLabelsLayer.css(style); SmartLabel.setStyle(style); prevLen = sumLabels && sumLabels.length; currLen = stackValues.length; // Remove extra sum labels if the previous sumlabels count is greater than new sumvalue count if (prevLen > currLen) { while (prevLen >= currLen) { label = sumLabels[prevLen]; prevLen--; if (label) { label.hide(); manager.removeGraphicalElement(label); } } } for (i = start; i < range; i++) { sumLabel = Array.isArray(sumLabels) && sumLabels[i]; if (!stackValues[i] || !stackValues[i].isNotNull) { sumLabel && sumLabel.hide(); continue; } positive = stackValues[i].positive; negative = stackValues[i].negative; sumValue = positive + negative; /* Getting the y shift which decides how much to shift the y position of the sum label */ offsetY = sumValue < 0 ? negative : positive; displayValue = yAxis.dataLabels(sumValue); if (displayValue) { bgColor = style.backgroundColor; bdColor = style.borderColor; labelDim = SmartLabel.getOriSize(displayValue); if (isBar) { yPos = manager._getXpos(i) + labelDim.height / 2; xPos = yAxis.getPixel(stack100percent ? 100 : offsetY) + labelDim.width / 2; if (!stack100percent) { // adjust the x position of the label if it goes out of the canvas xPos -= xPos + labelDim.width > canvasRight ? xPos + labelDim.width - canvasRight : 0; } } else { xPos = manager._getXpos(i); yPos = yAxis.getPixel(stack100percent ? 100 : offsetY); } attrs = manager.getSumValuePosition(labelDim, { stack100percent: stack100percent, rotateValues: rotateValues, xPos: xPos, yPos: yPos, offsetY: offsetY }); attrs.text = displayValue; attrs.fill = style.color; attrs['text-bound'] = [bgColor, bdColor, style.borderThickness, style.borderPadding, style.borderRadius, style.borderDash]; attrs['line-height'] = style.lineHeight; attrs.visibility = visibleStr; attrs.transform = paper.getSuggestiveRotation(rotateValues, attrs.x, attrs.y); // @TODO needs to validate 'text-anchor' if (attrs['text-anchor']) { delete attrs['text-bound']; } sumLabel = animationManager.setAnimation({ el: sumLabel || 'text', attr: attrs, label: 'text', container: sumLabelsLayer, component: manager }); sumLabel.show(); if (!(Array.isArray(sumLabels) && sumLabels[i])) { manager.addGraphicalElement('sumLabels', sumLabel, true); } } } } else { animationManager.setAnimation({ el: sumLabelsLayer, label: 'sumLabelGroup' }); sumLabelsLayer.hide(); } }; /** * function calculate the coordinates for the sum value label * it returns the calculated x, y coordinate to render the label * @param {Object} labelDim display value dimention * @param {Object} labelConfig display value configuration * @return {Object} contains x, y positions of the label */ CartesianStackgroup.prototype.getSumValuePosition = function getSumValuePosition(labelDim, labelConfig) { var manager = this, chart = manager.getFromEnv('chart'), config = chart.config, canvasBottom = config.canvasBottom, canvasTop = config.canvasTop, is3D = chart.config.is3D, isBar = chart.isBar, stack100percent = labelConfig.stack100percent, gutter = 2, yDepth = config.yDepth, xDepth = config.xDepth, origTextHeight, outsideColSpace, yPos = labelConfig.yPos, textHeight, xPos = labelConfig.xPos, labelHeight, canvasBorderThickness = manager.getFromEnv('canvasConfig').canvasBorderWidth, offsetY = labelConfig.offsetY, rotateValues = labelConfig.rotateValues; // Storing the width and height in state if state not created if (rotateValues) { // If rotated values we use the width of // the text as height labelHeight = labelDim.width; } else { labelHeight = labelDim.height; } textHeight = origTextHeight = labelHeight; textHeight = textHeight / 2 + gutter; // If not stack 100 percent if (!stack100percent) { // For positive values if (offsetY >= 0) { outsideColSpace = yPos - canvasTop; // If text does not fit outside column shift the label inside the column if (outsideColSpace < origTextHeight) { yPos = yPos + textHeight - outsideColSpace; } else { // If text fits in the space between column and canvas yPos = yPos - textHeight; xPos += isBar ? gutter : 0; } } // For positive values if (offsetY < 0) { outsideColSpace = canvasBottom - yPos; if (outsideColSpace < origTextHeight) { yPos = yPos - textHeight; } else { yPos = yPos + textHeight; } if (is3D) { xPos -= xDepth; yPos += yDepth; } } } else { // Label management when stack100percent // If space not available outside canvas if (canvasTop <= origTextHeight) { yPos = textHeight; } else { // If space available outside canvas yPos = isBar ? labelConfig.yPos : canvasTop - textHeight - canvasBorderThickness; xPos += isBar ? canvasBorderThickness : 0; } } return { x: xPos, y: yPos }; }; /** * function to accomodate the changes of its child and notify its parent for further action if its needed * @param {Object} updateInfo is an object with the informations about the changes in its child */ CartesianStackgroup.prototype.childChanged = function childChanged() { var updateInfo = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manager = this, config = manager.config, parent = manager.getLinkedParent(), range = void 0, prevVisiblity = manager.getState('visible'), count = 0, changeInfo = {}, informParent = void 0; // get the number of visible children manager._mapChildren(function (child) { if (child.getState('visible')) { count++; } }); // set the manager visiblity according to number of children visible manager.setState('visible', !!count); // if the visiblity state changed then parent inform flag set to true prevVisiblity !== !!count && (informParent = true); // if the managers data limit get changed then also inform the parent if (updateInfo.dataLimitChanged !== false) { range = manager.getDataLimits(); if (range.min !== config.range.min || range.max !== config.range.max) { config.range.min = range.min; config.range.max = range.max; changeInfo.dataLimitChanged = true; informParent = true; } } // if the axis value got changed then inform parent // right now we do not change value padding on any type of update // if (updateInfo.paddingChanged !== false) { // padding = manager.getAxisValuePadding(); // if (padding.left !== config.padding.left || padding.right !== config.padding.right) { // config.padding.left = padding.left; // config.padding.right = padding.right; // changeInfo.paddingChanged = true; // informParent = true; // } // } if (informParent) { parent.childChanged && parent.childChanged(changeInfo); } else { manager.asyncDraw(); } }; /** * function to get value for axis padding from is children * @return {Object} with left and right member */ CartesianStackgroup.prototype.getAxisValuePadding = function getAxisValuePadding() { var paddingObj = {}, axisPaddingLeft = -Infinity, axisPaddingRight = -Infinity; this._mapChildren(function (child) { if (child.getState('removed')) { return; } paddingObj = child.getAxisValuePadding && child.getAxisValuePadding() || {}; axisPaddingLeft = Math.max(axisPaddingLeft, paddingObj.left || -Infinity); axisPaddingRight = Math.max(axisPaddingRight, paddingObj.right || -Infinity); }); if (axisPaddingLeft === -Infinity) { axisPaddingLeft = 0; } if (axisPaddingRight === -Infinity) { axisPaddingRight = 0; } if (!this.config.padding) { this.config.padding = {}; this.config.padding.left = axisPaddingLeft; this.config.padding.right = axisPaddingRight; } return { left: axisPaddingLeft, right: axisPaddingRight }; }; /** * function to get data limits from its child datasets * return minimun and maximum value among the datasets range * @param {boolean} allVisible whether consider all the datasets are visible or not * @return {Object} [min, max] */ CartesianStackgroup.prototype.getDataLimits = function getDataLimits(allVisible) { this._setStackPosition(); if (!this.config.range) { this.config.range || (this.config.range = {}); this.config.range.min = this.config.dataMin; this.config.range.max = this.config.dataMax; } return allVisible ? this._getStackLimit() : { max: this.config.dataMax, min: this.config.dataMin }; }; /** * functio to return limit of the manager by considering all the datasets are visble * @return {Object} contains data limit */ CartesianStackgroup.prototype._getStackLimit = function _getStackLimit() { var manager = this, dataMin = +Infinity, dataMax = -Infinity, stackValueArr = [], skipInfo = manager.getSkippingInfo && manager.getSkippingInfo() || {}, skippingDrawArray = skipInfo.draw || [], skipDrawArrayLenth = skippingDrawArray.length, skippingApplied = skipInfo.skippingApplied; manager._mapChildren(function (child) { if (child.getState('removed')) { return; } var datum = void 0, data = child.getData(), i = void 0, j = void 0, setValue = void 0, stackedValue = 0, len = data && data.length, base = 0; if (skippingApplied) { len = skipDrawArrayLenth; } for (j = 0; j < len; j++) { i = skippingDrawArray[j] || j; datum = data[i]; if (datum && datum.config && datum.config.setValue !== UNDEF && datum.config.setValue !== null) { if (!stackValueArr[i]) { stackValueArr[i] = {}; } setValue = datum.config.setValue; stackValueArr[i].positive || (stackValueArr[i].positive = 0); stackValueArr[i].negative || (stackValueArr[i].negative = 0); if (setValue > 0) { base = stackValueArr[i].positive; stackedValue = setValue + base; stackValueArr[i].positive = stackedValue; } else if (setValue < 0) { base = stackValueArr[i].negative; stackedValue = setValue + base; stackValueArr[i].negative = stackedValue; } dataMax = mathMax(stackedValue, dataMax); dataMin = mathMin(stackedValue, dataMin); } } }); return { max: dataMax, min: dataMin }; }; /** * it return the status of dataset visiblity * @return {boolean} returns the visiblity status of dataset */ CartesianStackgroup.prototype.isVisible = function isVisible() { return !this.isNotVisible; }; /** * function to get calculate width or hieght for stacked charts' sumvalue label * @param {number} maxAvailableSpace available space for height or width * @return {Object} contains top and right value */ CartesianStackgroup.prototype.getMaxSumValueSpace = function getMaxSumValueSpace() { var manager = this, stackSumValues = manager.config.stackValues, chart = manager.getFromEnv('chart'), i, dim = {}, len = stackSumValues && stackSumValues.length, numberFormatter = manager.getFromEnv('number-formatter'), formattedValue, width, height, maxHeight = 0, maxWidth = 0, sumValue, SmartLabel = manager.getFromEnv('smartLabel'), dataLabelStyle = chart.config.dataLabelStyle; SmartLabel.useEllipsesOnOverflow(chart.config.useEllipsesWhenOverflow); SmartLabel.setStyle(dataLabelStyle); for (i = 0; i < len; i++) { if (stackSumValues[i]) { sumValue = stackSumValues[i].positive + stackSumValues[i].negative; formattedValue = numberFormatter.dataLabels(sumValue); dim = SmartLabel.getOriSize(formattedValue); width = dim.width; height = dim.height; maxWidth = mathMax(maxWidth, width); maxHeight = mathMax(maxHeight, height); } } return { maxWidth: maxWidth, maxHeight: maxHeight }; }; /** * function to calculate maximum canvas padding is required by the children of this manager * @return {Object} contains dimension required */ CartesianStackgroup.prototype.getCanvasPadding = function getCanvasPadding() { var manager = this, dim, key, returnDimension = { paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 }; manager._setStackPosition(); manager._mapChildren(function (child) { dim = child.getCanvasPadding && child.getCanvasPadding() || {}; for (key in dim) { if (dim.hasOwnProperty(key)) { returnDimension[key] = Math.max(dim[key], returnDimension[key]); } } }); return returnDimension; }; return CartesianStackgroup; }(_componentInterface.ComponentInterface); exports['default'] = CartesianStackgroup; /***/ }), /* 526 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var groupFadeIn = function groupFadeIn() { return [{ initialAttr: { opacity: 1 }, finalAttr: { opacity: 1 }, slot: 'plot' }]; }, sumlabelFadeIn = function sumlabelFadeIn() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'final' }]; }; exports['default'] = { 'initial.group.cartesianStackGroup': function initialGroupCartesianStackGroup() { return { 'group.appearing': groupFadeIn, 'text.appearing': sumlabelFadeIn, '*': null }; }, 'initial.group.marimekkoStackgroup': function initialGroupMarimekkoStackgroup() { return { 'text.appearing': sumlabelFadeIn, '*': null }; } }; /***/ }), /* 527 */, /* 528 */, /* 529 */, /* 530 */, /* 531 */, /* 532 */, /* 533 */, /* 534 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _mscolumn2d = __webpack_require__(518); var _mscolumn2d2 = _interopRequireDefault(_mscolumn2d); var _quadrant = __webpack_require__(535); var _quadrant2 = _interopRequireDefault(_quadrant); var _xyAxis = __webpack_require__(537); var _xyAxis2 = _interopRequireDefault(_xyAxis); var _legend = __webpack_require__(462); var _legend2 = _interopRequireDefault(_legend); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, MOUSEOUT = 'fc-mouseout', /* function to find hovered trendlines */ _getHoveredTrendLine = function _getHoveredTrendLine(chartX, chartY, trendLines) { var i, trendLinesLen = trendLines && trendLines.length, xPos = chartX, yPos = chartY, slope, trendObj, A, B, C, dist, x1, y1, x2, y2; if (!trendLinesLen) { return undefined; } for (i = trendLinesLen - 1; i >= 0; i--) { trendObj = trendLines[i]; x1 = trendObj.x1; y1 = trendObj.y1; x2 = trendObj.x2; y2 = trendObj.y2; if (trendObj.isTrendZone) { if (xPos >= x1 && xPos <= x2 && yPos >= y1 && yPos <= y2) { return trendObj; } } else { if (y1 !== y2 && x1 !== x2) { // start and end values are different slope = (y1 - y2) / (x1 - x2); A = slope; B = -1; C = y1 - slope * x1; dist = Math.abs(A * xPos + B * yPos + C) / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2)); } else if (x1 === x2) { dist = Math.abs(x1 - xPos); } else if (y1 === y2) { dist = Math.abs(y1 - yPos); } if (dist <= trendObj.tolerance) { return trendObj; } } } }; var ScatterBase = function (_MSColumn2D) { _inherits(ScatterBase, _MSColumn2D); /** * constructor fn */ function ScatterBase() { _classCallCheck(this, ScatterBase); var _this = _possibleConstructorReturn(this, _MSColumn2D.call(this)); _this.registerFactory('axis', _xyAxis2['default'], ['canvas']); _this.registerFactory('legend', _legend2['default']); // this.registerFactory('composer', composer); _this.registerFactory('quadrant', function (chart) { var canvas = chart.getChildren('canvas')[0], quadrant = void 0, children = chart.getChildren(), redraw = function redraw() { return quadrant.asyncDraw(); }; (0, _lib.componentFactory)(canvas, _quadrant2['default'], 'quadrant'); quadrant = canvas.getChildren('quadrant')[0]; quadrant.addExtEventListener('visiblerangeset', redraw, children.xAxis[0]); quadrant.addExtEventListener('visiblerangeset', redraw, children.yAxis[0]); quadrant.configure(); }, ['dataset']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ ScatterBase.getName = function getName() { return 'ScatterBase'; }; ScatterBase.prototype.mouseoutHandler = function mouseoutHandler(e, _lastDatasetIndex, _lastPointIndex) { var chart = this, datasets = chart.config.datasetOrder || chart.getDatasets(), mouseTracker = chart.getChildren('mouseTracker')[0]; // check if the data plot exists. else hide all existing tooltips. if (datasets[_lastDatasetIndex] && datasets[_lastDatasetIndex].components.data[_lastPointIndex]) { datasets[_lastDatasetIndex]._firePlotEvent(MOUSEOUT, _lastPointIndex, e); } else { chart.getFromEnv('toolTipController').hideAll(); } // delete stored last ds details delete mouseTracker._lastDatasetIndex; delete mouseTracker._lastPointIndex; }; /** * Parse the chart attributes and store in chart's config * @param {Object} dataObj User input json */ ScatterBase.prototype.parseChartAttr = function parseChartAttr(dataObj) { _MSColumn2D.prototype.parseChartAttr.call(this, dataObj); this.config.drawTrendRegion = 0; }; ScatterBase.prototype.__setDefaultConfig = function __setDefaultConfig() { var config = this.config; _MSColumn2D.prototype.__setDefaultConfig && _MSColumn2D.prototype.__setDefaultConfig.call(this); config.valuefontbold = 0; config.stickytracking = 1; // realtime related attributes // @todo ideally this should be moved to a realtime base chart config.usemessagelog = 0; config.animationeffect = 'linear'; config.showshadow = 1; config.showhovereffect = UNDEF; config.plothovereffect = UNDEF; config.anchorhovereffect = UNDEF; config.plotborderdashed = UNDEF; config.stack100percent = UNDEF; config.showpercentvalues = UNDEF; config.showpercentintooltip = UNDEF; config.plotbordercolor = UNDEF; config.showtooltip = 1; config.seriesnameintooltip = 1; config.rotatevalues = 0; config.minimizetendency = 0; config.plotfillangle = 270; config.valuepadding = 2; config.useplotgradientcolor = 1; config.plotborderthickness = 1; config.plotfillalpha = '70'; config.showvalues = 1; config.valueposition = 'auto'; config.tooltipsepchar = ', '; config.usedataplotcolorforlabels = 0; config.placevaluesinside = 0; config.showplotborder = 1; config.use3dlighting = 1; config.useroundedges = 0; config.plotspacepercent = 20; config.plotpaddingpercent = UNDEF; config.plotfillratio = UNDEF; config.maxcolwidth = 50; config.plotborderdashlen = 5; config.plotborderdashgap = 4; config.useScaleRecursively = true; config.zeroplanethickness = 1; config.zeroplanealpha = 40; config.showzeroplaneontop = 0; config.setadaptivexmin = 1; }; /** * Method that draws trendline tooltip * @param {Object} trendline Hovered trendline/vTrendline * @param {Object} e reference of the original mouse event */ ScatterBase.prototype._drawTrendTooltip = function _drawTrendTooltip(trendline, e) { var iapi = this, toolTipController = iapi.getFromEnv('toolTipController'), currentToolTip = iapi.config.currentTrendToolTip, toolText = trendline.tooltext, originalEvent = e.originalEvent; // if (toolText) { if (currentToolTip) { toolTipController.draw(originalEvent, toolText, currentToolTip); } else { currentToolTip = iapi.config.currentTrendToolTip = toolTipController.draw(originalEvent, toolText); } }; ScatterBase.prototype._mouseEvtHandler = function _mouseEvtHandler(e, data) { var iapi = this, mouseTracker = data.mouseTracker, canvas = iapi.getChildren('canvas')[0], toolTipController = iapi.getFromEnv('toolTipController'), hoveredVtrendline, hoveredTrendLine, oriEvent = e.originalEvent, chartConfig = iapi.config, // tolerance for finding point in 3D charts when hovered over a plot // having value equal or close to 0 canvasBaseDepth = chartConfig.canvasBaseDepth || 0, canvasLeft = chartConfig.canvasLeft - (chartConfig.toleranceLeft || 0), canvasRight = chartConfig.canvasRight + (chartConfig.toleranceRight || 0), canvasBottom = chartConfig.canvasBottom + (chartConfig.toleranceBottom || 0), canvasTop = chartConfig.canvasTop - (chartConfig.toleranceTop || 0), datasets = chartConfig.datasetOrder || iapi.getDatasets(), coordinate, chartX, chartY, dataset, hoveredInfo, pointFound = false, i = datasets.length, j, l, derivedEvensInfo, _lastDatasetIndex = mouseTracker._lastDatasetIndex, _lastPointIndex = mouseTracker._lastPointIndex; coordinate = (0, _lib.getMouseCoordinate)(iapi.getFromEnv('chart-container'), oriEvent, iapi); chartX = coordinate.chartX; chartY = coordinate.chartY; // if inside the canvas if (chartX > canvasLeft - canvasBaseDepth && chartX < canvasRight && chartY > canvasTop && chartY < canvasBottom + canvasBaseDepth) { // todo make sure the datasets are as per their z-order while (i-- && !pointFound) { dataset = datasets[i]; if (dataset && dataset.getState('visible')) { hoveredInfo = dataset._getHoveredPlot && dataset._getHoveredPlot(chartX, chartY); if (hoveredInfo && hoveredInfo.hovered || hoveredVtrendline) { pointFound = true; hoveredInfo.datasetIndex = i; derivedEvensInfo = mouseTracker.getMouseEvents(e, hoveredInfo.datasetIndex, hoveredInfo.pointIndex); } } } // check if the mousepointer is hovering on any trend/vtrend line hoveredVtrendline = _getHoveredTrendLine(chartX, chartY, canvas.config.vtrendlines); hoveredTrendLine = _getHoveredTrendLine(chartX, chartY, canvas.config.trendlines); } // todo instead of sending event names, create a event object of that type and send it // fire out on last hovered plot if ((!pointFound || derivedEvensInfo && derivedEvensInfo.fireOut) && typeof _lastDatasetIndex !== 'undefined') { if (datasets[_lastDatasetIndex] && datasets[_lastDatasetIndex]._firePlotEvent) { // when mouseout is fired and there aren't any events that need to be fired over the current plot, // call mouseouthamndler through settimeout. if (derivedEvensInfo && !derivedEvensInfo.events.length) { mouseTracker.mouseoutTimer = setTimeout(function () { iapi.mouseoutHandler(e, _lastDatasetIndex, _lastPointIndex); }, 20); } else { iapi.mouseoutHandler(e, _lastDatasetIndex, _lastPointIndex); clearTimeout(mouseTracker.mouseoutTimer); } } // todo scope to have sticky tracked tooltip } // fire remaining events if (pointFound) { // hide trend line toolip if any if (iapi.config.currentTrendToolTip) { toolTipController.hide(iapi.config.currentTrendToolTip); } l = derivedEvensInfo.events && derivedEvensInfo.events.length; // Update only when events for current plot are present. // Reason: When cursor is present in territory of line/area plot but not directly over it, then // the fireOut of current plot was happening instead of the actual last plot. if (l) { // store the index of the hovered DS and plot mouseTracker._lastDatasetIndex = hoveredInfo.datasetIndex; _lastPointIndex = mouseTracker._lastPointIndex = hoveredInfo.pointIndex; } // chartConfig.drawTrendRegion && chartComponents[group]._notifyGroup(true, e); for (j = 0; j < l; j += 1) { dataset && dataset._firePlotEvent && dataset._firePlotEvent(derivedEvensInfo.events[j], _lastPointIndex, e, hoveredInfo.datasetIndex); } } else if (hoveredVtrendline && hoveredVtrendline.tooltext) { // draw vtrendline toolltip iapi._drawTrendTooltip(hoveredVtrendline, e); } else if (hoveredTrendLine && hoveredTrendLine.tooltext) { // draw trendline tooltip iapi._drawTrendTooltip(hoveredTrendLine, e); } else if (iapi.config.currentTrendToolTip) { // hide trendline toolip if not hovering over any trendline or vtrendline toolTipController.hide(iapi.config.currentTrendToolTip); } }; ScatterBase.prototype._setCategories = function _setCategories() { var iapi = this, dataObj = iapi.getFromEnv('dataSource'), chartAttr = dataObj.chart, xAxis = iapi.getChildren('xAxis'), xAxisLabelMode = (0, _lib.pluck)(chartAttr.xaxislabelmode, 'categories'), categoriesArr = dataObj.categories, categories = categoriesArr && categoriesArr[0] && categoriesArr[0].category; xAxis[0].setAxisConfig({ xAxisLabelMode: 'categories' }); if (xAxisLabelMode !== 'auto' && xAxisLabelMode !== 'mixed' && categories && categories.length > 0) { xAxis[0].setTickValues(categories); } else if (xAxisLabelMode !== 'auto') { xAxis[0].setTickValues(categories); xAxis[0].setAxisConfig({ xAxisLabelMode: 'mixed' }); } else { // setTickValues is called for auto mode to set ticks in axis config // at the time of render/re-render xAxis[0].setTickValues(categories); xAxis[0].setAxisConfig({ xAxisLabelMode: 'auto' }); } }; /** * allocate space for canvas * @param {Object} dimensions contains left, right, top, bottom co-ordinate (relative) */ ScatterBase.prototype._allocateSpace = function _allocateSpace(dimensions) { var iapi = this, canvas = iapi.getChildren('canvas'), canvasConfig = canvas && canvas[0].config, config = iapi.config, canvasHeight = config.canvasHeight, canvasWidth = config.canvasWidth, availableHeight = config.availableHeight, availableWidth = config.availableWidth; config.canvasLeft += dimensions.left || 0; config.canvasTop += dimensions.top || 0; canvasWidth = config.canvasWidth = Math.max(canvasWidth - ((dimensions.left || 0) + (dimensions.right || 0)), 0); canvasHeight = config.canvasHeight = Math.max(canvasHeight - ((dimensions.top || 0) + (dimensions.bottom || 0)), 0); config.availableHeight = Math.max(availableHeight - ((dimensions.top || 0) + (dimensions.bottom || 0)), 0); config.availableWidth = Math.max(availableWidth - ((dimensions.left || 0) + (dimensions.right || 0)), 0); config.canvasRight = config.canvasLeft + canvasWidth; config.canvasBottom = config.canvasTop + canvasHeight; if (canvasConfig) { canvasConfig.canvasPaddingLeft = Math.max(canvasConfig.canvasPaddingLeft, dimensions.paddingLeft || 0); canvasConfig.canvasPaddingRight = Math.max(canvasConfig.canvasPaddingRight, dimensions.paddingRight || 0); canvasConfig.canvasPaddingTop = Math.max(canvasConfig.canvasPaddingTop, dimensions.paddingTop || 0); canvasConfig.canvasPaddingBottom = Math.max(canvasConfig.canvasPaddingBottom, dimensions.paddingBottom || 0); } canvas[0].setDimension({ top: config.canvasTop, left: config.canvasLeft, width: config.canvasWidth, height: config.canvasHeight }); }; /** * function to calculate post space management calculations * calculations like axis dimenetion set, allocate space for xaxis labels, * canvas padding etc. */ ScatterBase.prototype._postSpaceManagement = function _postSpaceManagement() { var iapi = this, config = iapi.config, components = iapi.getChildren(), xAxis = components.xAxis && components.xAxis[0], legend = components.legend && components.legend[0], xDepth = config.xDepth, i, canvas, canvasArr = iapi.getChildren('canvas'); iapi.setAxisDimention(); xAxis && iapi._allocateXAxisLabelSpace(xAxis); xAxis && xAxis.shiftLabels(-xDepth, 0); legend && legend.postSpaceManager(); for (i = 0; i < (canvasArr && canvasArr.length); i++) { canvas = canvasArr[i]; // function for adjusting value padding depending upon data and axis labels. canvas.setCanvasPadding(); } // Re-set the dimension after setting the canvas padding iapi.setAxisDimention(); iapi.allocateDimensionOfChartMenuBar(); }; /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ ScatterBase.prototype._checkInvalidSpecificData = function _checkInvalidSpecificData() { var jsonData = this.getFromEnv('dataSource'), datasetsJSON = jsonData.dataset; if (!datasetsJSON) { return true; } }; /* * Gets the starting index and difference information for data hiding. */ // _getDiff (DataDiff, currDataLength) { // return { // diff: DataDiff, // startIndex: currDataLength // }; // } return ScatterBase; }(_mscolumn2d2['default']); exports['default'] = ScatterBase; /***/ }), /* 535 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _index = __webpack_require__(536); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ // import { convertColor } from '../lib/lib-graphics'; var BLANKSTRING = '', PXSTRING = 'px', DASH_DEF = 'none', NORMALSTRING = 'normal', POSITION_START = _lib.preDefStr.POSITION_START, POSITION_TOP = _lib.preDefStr.POSITION_TOP, POSITION_BOTTOM = _lib.preDefStr.POSITION_BOTTOM, POSITION_END = _lib.preDefStr.POSITION_END; (0, _dependencyManager.addDep)({ name: 'quadrantAnimation', type: 'animationRule', extension: _index2['default'] }); /** * Creates Quadrant class needed for XY charts */ var Quadrant = function (_ComponentInterface) { _inherits(Quadrant, _ComponentInterface); /** * Constructor function of Quadrant class */ function Quadrant() { _classCallCheck(this, Quadrant); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); var quadrant = _this; quadrant.pIndex = 1; quadrant.components = {}; quadrant.conf = {}; quadrant.graphics = {}; return _this; } /** * Sets the type of the component * @return {string} type */ Quadrant.prototype.getType = function getType() { return 'canvas'; }; /** * Sets the name of the component * @return {string} name */ Quadrant.prototype.getName = function getName() { return 'quadrant'; }; /** * Quadrant configuration parser */ Quadrant.prototype.configure = function configure() { var borderColor, borderPadding, borderRadius, backgroundColor, borderDash, fontBdrColor, bgColor, borderThickness, tlConfig, trConfig, blConfig, brConfig, quadrantLabelTL, quadrantLabelTR, quadrantLabelBL, quadrantLabelBR, quadrantXVal, quadrantYVal, quadrantLineColor, quadrantLineThickness, quadrantLineDashLen, quadrantLineIsDashed, quadrantLineDashGap, dashStyle, drawQuadrant, quadrant = this, quadrantConfig = quadrant.conf, chart = quadrant.getFromEnv('chart'), chartConfig = chart.config, chartAttr = chart.getFromEnv('dataSource').chart, canvas = chart.getChildren('canvas')[0], canvasConf = canvas.config, inCanvasStyle = chartConfig.dataLabelStyle, smartLabel = chart.getFromEnv('smartLabel'); drawQuadrant = quadrantConfig.enabled = (0, _lib.pluckNumber)(chartAttr.drawquadrant, 0); if (drawQuadrant) { // Quadrant related properties // maximum allowed values for the axes and drawing occurs only when the values are whitin this range. quadrantXVal = (0, _lib.pluckNumber)(chartAttr.quadrantxval); quadrantYVal = (0, _lib.pluckNumber)(chartAttr.quadrantyval); quadrantLineColor = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.quadrantlinecolor, canvasConf.canvasBorderColor), (0, _lib.pluck)(chartAttr.quadrantlinealpha, chartAttr.quadrantlinealpha, _lib.HUNDREDSTRING)); quadrantLineThickness = (0, _lib.pluckNumber)(chartAttr.quadrantlinethickness, canvasConf.canvasBorderThickness); quadrantLineIsDashed = (0, _lib.pluckNumber)(chartAttr.quadrantlinedashed, chartAttr.quadrantlineisdashed, 0); quadrantLineDashLen = (0, _lib.pluckNumber)(chartAttr.quadrantlinedashlen, 4); quadrantLineDashGap = (0, _lib.pluckNumber)(chartAttr.quadrantlinedashgap, 2); dashStyle = quadrantLineIsDashed ? (0, _lib.getDashStyle)(quadrantLineDashLen, quadrantLineDashGap) : DASH_DEF; quadrantConfig.xVal = quadrantXVal; quadrantConfig.yVal = quadrantYVal; quadrantConfig.quadrantLineColor = quadrantLineColor; quadrantConfig.quadrantLineThickness = quadrantLineThickness; quadrantConfig.dashStyle = dashStyle; // pluck the text for quadrant labels quadrantLabelTL = (0, _lib.getValidValue)(chartAttr.quadrantlabeltl, BLANKSTRING); quadrantLabelTR = (0, _lib.getValidValue)(chartAttr.quadrantlabeltr, BLANKSTRING); quadrantLabelBL = (0, _lib.getValidValue)(chartAttr.quadrantlabelbl, BLANKSTRING); quadrantLabelBR = (0, _lib.getValidValue)(chartAttr.quadrantlabelbr, BLANKSTRING); quadrantConfig.quadrantLabelPadding = (0, _lib.pluckNumber)(chartAttr.quadrantlabelpadding, 3); // Draw the quadrant labels. smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle(inCanvasStyle); if (quadrantLabelTL !== BLANKSTRING) { fontBdrColor = (0, _lib.getFirstValue)(chartAttr.quadrantlabeltlbordercolor, chartAttr.quadrantlabelbordercolor, BLANKSTRING); bgColor = (0, _lib.pluck)(chartAttr.quadrantlabeltlbgcolor, chartAttr.quadrantlabelbgcolor); borderThickness = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderthickness, chartAttr.quadrantlabelborderthickness, 1); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderalpha, chartAttr.quadrantlabelborderalpha, chartAttr.quadrantlabeltlalpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; tlConfig = quadrantConfig.tlConfig; if (!tlConfig) { tlConfig = quadrantConfig.tlConfig = { enabled: true, styleObj: {} }; } tlConfig.label = quadrantLabelTL; tlConfig.styleObj.fontSize = (0, _lib.pluck)((0, _lib.pluckNumber)(chartAttr.quadrantlabeltlfontsize, chartAttr.quadrantlabelfontsize), parseInt(inCanvasStyle.fontSize, 10)) + PXSTRING; tlConfig.styleObj.lineHeight = inCanvasStyle.lineHeight; tlConfig.styleObj.fontFamily = (0, _lib.pluck)(chartAttr.quadrantlabeltlfont, chartAttr.quadrantlabelfont, inCanvasStyle.fontFamily); tlConfig.styleObj.color = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.quadrantlabeltlfontcolor, chartAttr.quadrantlabelfontcolor, inCanvasStyle.color), (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlfontalpha, chartAttr.quadrantlabelfontalpha, 100)); tlConfig.styleObj.fontWeight = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlfontbold, chartAttr.quadrantlabelfontbold) ? 'bold' : NORMALSTRING; tlConfig.styleObj.fontStyle = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlfontitalic, chartAttr.quadrantlabelfontitalic) ? 'italic' : NORMALSTRING; // sets the line height (0, _lib.setLineHeight)(tlConfig.styleObj); borderColor = fontBdrColor; borderPadding = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderpadding, chartAttr.quadrantlabelborderpadding, 2); borderRadius = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderradius, chartAttr.quadrantlabelborderradius, 0); backgroundColor = bgColor ? (0, _lib.convertColor)(bgColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlbgalpha, chartAttr.quadrantlabelbgalpha, chartAttr.quadrantlabeltlalpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; borderDash = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderdashed, chartAttr.quadrantlabelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderdashlen, chartAttr.quadrantlabelborderdashlen, 4), (0, _lib.pluckNumber)(chartAttr.quadrantlabeltlborderdashgap, chartAttr.quadrantlabelborderdashgap, 2)) : DASH_DEF; tlConfig['text-bound'] = [backgroundColor, borderColor, borderThickness, borderPadding, borderRadius, borderDash]; } else { quadrantConfig.tlConfig && (quadrantConfig.tlConfig.label = quadrantLabelTL); } if (quadrantLabelTR !== BLANKSTRING) { fontBdrColor = (0, _lib.getFirstValue)(chartAttr.quadrantlabeltrbordercolor, chartAttr.quadrantlabelbordercolor, BLANKSTRING); bgColor = (0, _lib.pluck)(chartAttr.quadrantlabeltrbgcolor, chartAttr.quadrantlabelbgcolor); borderThickness = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderthickness, chartAttr.quadrantlabelborderthickness, 1); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderalpha, chartAttr.quadrantlabelborderalpha, chartAttr.quadrantlabeltralpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; trConfig = quadrantConfig.trConfig; if (!trConfig) { trConfig = quadrantConfig.trConfig = { enabled: true, styleObj: {} }; } trConfig.label = (0, _lib.getValidValue)(chartAttr.quadrantlabeltr, BLANKSTRING); trConfig.styleObj.fontSize = (0, _lib.pluck)((0, _lib.pluckNumber)(chartAttr.quadrantlabeltrfontsize, chartAttr.quadrantlabelfontsize), parseInt(inCanvasStyle.fontSize, 10)) + PXSTRING; trConfig.styleObj.lineHeight = inCanvasStyle.lineHeight; trConfig.styleObj.fontFamily = (0, _lib.pluck)(chartAttr.quadrantlabeltrfont, chartAttr.quadrantlabelfont, inCanvasStyle.fontFamily); trConfig.styleObj.color = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.quadrantlabeltrfontcolor, chartAttr.quadrantlabelfontcolor, inCanvasStyle.color), (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrfontalpha, chartAttr.quadrantrabelfontalpha, 100)); trConfig.styleObj.fontWeight = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrfontbold, chartAttr.quadrantlabelfontbold) ? 'bold' : NORMALSTRING; trConfig.styleObj.fontStyle = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrfontitalic, chartAttr.quadrantlabelfontitalic) ? 'italic' : NORMALSTRING; // sets the line height (0, _lib.setLineHeight)(trConfig.styleObj); borderColor = fontBdrColor; borderPadding = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderpadding, chartAttr.quadrantlabelborderpadding, 2); borderRadius = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderradius, chartAttr.quadrantlabelborderradius, 0); backgroundColor = bgColor ? (0, _lib.convertColor)(bgColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrbgalpha, chartAttr.quadrantlabelbgalpha, chartAttr.quadrantlabeltralpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; borderDash = (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderdashed, chartAttr.quadrantlabelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderdashlen, chartAttr.quadrantlabelborderdashlen, 4), (0, _lib.pluckNumber)(chartAttr.quadrantlabeltrborderdashgap, chartAttr.quadrantlabelborderdashgap, 2)) : DASH_DEF; trConfig['text-bound'] = [backgroundColor, borderColor, borderThickness, borderPadding, borderRadius, borderDash]; } else { quadrantConfig.trConfig && (quadrantConfig.trConfig.label = quadrantLabelTR); } if (quadrantLabelBL !== BLANKSTRING) { fontBdrColor = (0, _lib.getFirstValue)(chartAttr.quadrantlabelblbordercolor, chartAttr.quadrantlabelbordercolor, BLANKSTRING); bgColor = (0, _lib.pluck)(chartAttr.quadrantlabelblbgcolor, chartAttr.quadrantlabelbgcolor); borderThickness = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderthickness, chartAttr.quadrantlabelborderthickness, 1); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderalpha, chartAttr.quadrantlabelborderalpha, chartAttr.quadrantlabelblalpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; blConfig = quadrantConfig.blConfig; if (!blConfig) { blConfig = quadrantConfig.blConfig = { enabled: true, styleObj: {} }; } blConfig.label = quadrantLabelBL; blConfig.styleObj.fontSize = (0, _lib.pluck)((0, _lib.pluckNumber)(chartAttr.quadrantlabelblfontsize, chartAttr.quadrantlabelfontsize), parseInt(inCanvasStyle.fontSize, 10)) + PXSTRING; blConfig.styleObj.lineHeight = inCanvasStyle.lineHeight; blConfig.styleObj.fontFamily = (0, _lib.pluck)(chartAttr.quadrantlabelblfont, chartAttr.quadrantlabelfont, inCanvasStyle.fontFamily); blConfig.styleObj.color = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.quadrantlabelblfontcolor, chartAttr.quadrantlabelfontcolor, inCanvasStyle.color), (0, _lib.pluckNumber)(chartAttr.quadrantlabelblfontalpha, chartAttr.quadrantlabelfontalpha, 100)); blConfig.styleObj.fontWeight = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblfontbold, chartAttr.quadrantlabelfontbold) ? 'bold' : NORMALSTRING; blConfig.styleObj.fontStyle = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblfontitalic, chartAttr.quadrantlabelfontitalic) ? 'italic' : NORMALSTRING; // set line height (0, _lib.setLineHeight)(blConfig.styleObj); borderColor = fontBdrColor; borderPadding = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderpadding, chartAttr.quadrantlabelborderpadding, 2); borderRadius = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderradius, chartAttr.quadrantlabelborderradius, 0); backgroundColor = bgColor ? (0, _lib.convertColor)(bgColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabelblbgalpha, chartAttr.quadrantlabelbgalpha, chartAttr.quadrantlabelblalpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; borderDash = (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderdashed, chartAttr.quadrantlabelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderdashlen, chartAttr.quadrantlabelborderdashlen, 4), (0, _lib.pluckNumber)(chartAttr.quadrantlabelblborderdashgap, chartAttr.quadrantlabelborderdashgap, 2)) : DASH_DEF; blConfig['text-bound'] = [backgroundColor, borderColor, borderThickness, borderPadding, borderRadius, borderDash]; } else { quadrantConfig.blConfig && (quadrantConfig.blConfig.label = quadrantLabelBL); } if (quadrantLabelBR !== BLANKSTRING) { fontBdrColor = (0, _lib.getFirstValue)(chartAttr.quadrantlabelbrbordercolor, chartAttr.quadrantlabelbordercolor, BLANKSTRING); bgColor = (0, _lib.pluck)(chartAttr.quadrantlabelbrbgcolor, chartAttr.quadrantlabelbgcolor); borderThickness = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderthickness, chartAttr.quadrantlabelborderthickness, 1); fontBdrColor = fontBdrColor ? (0, _lib.convertColor)(fontBdrColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderalpha, chartAttr.quadrantlabelborderalpha, chartAttr.quadrantlabelbralpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; brConfig = quadrantConfig.brConfig; if (!brConfig) { brConfig = quadrantConfig.brConfig = { enabled: true, styleObj: {} }; } brConfig.label = (0, _lib.getValidValue)(chartAttr.quadrantlabelbr, BLANKSTRING); brConfig.styleObj.fontSize = (0, _lib.pluck)((0, _lib.pluckNumber)(chartAttr.quadrantlabelbrfontsize, chartAttr.quadrantlabelfontsize), parseInt(inCanvasStyle.fontSize, 10)) + PXSTRING; brConfig.styleObj.lineHeight = inCanvasStyle.lineHeight; brConfig.styleObj.fontFamily = (0, _lib.pluck)(chartAttr.quadrantlabelbrfont, chartAttr.quadrantlabelfont, inCanvasStyle.fontFamily); brConfig.styleObj.color = (0, _lib.convertColor)((0, _lib.pluck)(chartAttr.quadrantlabelbrfontcolor, chartAttr.quadrantlabelfontcolor, inCanvasStyle.color), (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrfontalpha, chartAttr.quadrantrabelfontalpha, 100)); brConfig.styleObj.fontWeight = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrfontbold, chartAttr.quadrantlabelfontbold) ? 'bold' : NORMALSTRING; brConfig.styleObj.fontStyle = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrfontitalic, chartAttr.quadrantlabelfontitalic) ? 'italic' : NORMALSTRING; // set the line height (0, _lib.setLineHeight)(brConfig.styleObj); backgroundColor = bgColor ? (0, _lib.convertColor)(bgColor, (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrbgalpha, chartAttr.quadrantlabelbgalpha, chartAttr.quadrantlabelbralpha, chartAttr.quadrantlabelalpha, 100)) : BLANKSTRING; borderColor = fontBdrColor; borderPadding = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderpadding, chartAttr.quadrantlabelborderpadding, 2); borderRadius = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderradius, chartAttr.quadrantlabelborderradius, 0); borderDash = (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderdashed, chartAttr.quadrantlabelborderdashed, 0) ? (0, _lib.getDashStyle)((0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderdashlen, chartAttr.quadrantlabelborderdashlen, 4), (0, _lib.pluckNumber)(chartAttr.quadrantlabelbrborderdashgap, chartAttr.quadrantlabelborderdashgap, 2)) : DASH_DEF; brConfig['text-bound'] = [backgroundColor, borderColor, borderThickness, borderPadding, borderRadius, borderDash]; } else { quadrantConfig.brConfig && (quadrantConfig.brConfig.label = quadrantLabelBR); } } }; /** * Calculates coordinates before drawing * @return {Object} instance of class Quadrant */ Quadrant.prototype._preDraw = function _preDraw() { var quadrantXVal, quadrantYVal, labelWidthPart1, labelWidthPart2, labelHeightPart1, labelHeightPart2, FALSE = false, quadrant = this, quadrantConfig = quadrant.conf, chart = quadrant.getFromEnv('chart'), xAxis = chart.getChildren('xAxis')[0], yAxis = chart.getChildren('yAxis')[0], xAxisLimit = xAxis.getLimit(), yAxisLimit = yAxis.getLimit(), xMax = xAxisLimit.max, yMax = yAxisLimit.max, xMin = xAxisLimit.min, yMin = yAxisLimit.min, chartConfig = chart.config, canvasWidth = chartConfig.canvasWidth, canvasHeight = chartConfig.canvasHeight, quadrantLabelPadding = quadrantConfig.quadrantLabelPadding, tlConfig = quadrantConfig.tlConfig, trConfig = quadrantConfig.trConfig, blConfig = quadrantConfig.blConfig, brConfig = quadrantConfig.brConfig; quadrantXVal = quadrantConfig.xVal || (quadrantConfig.xVal = (xMin + xMax) / 2); quadrantYVal = quadrantConfig.yVal || (quadrantConfig.yVal = (yMin + yMax) / 2); if (quadrantYVal >= yMin && quadrantYVal <= yMax && quadrantXVal >= xMin && quadrantXVal <= xMax) { labelWidthPart1 = canvasWidth / (xMax - xMin) * (quadrantXVal - xMin); labelWidthPart2 = canvasWidth - labelWidthPart1; labelHeightPart2 = canvasHeight / (yMax - yMin) * (quadrantYVal - yMin); labelHeightPart1 = canvasHeight - labelHeightPart2; // remove the padding amount and compute the available dimensions. labelWidthPart1 -= quadrantLabelPadding; labelWidthPart2 -= quadrantLabelPadding; labelHeightPart1 -= quadrantLabelPadding; labelHeightPart2 -= quadrantLabelPadding; if (labelHeightPart1 < 0 || labelWidthPart1 < 0) { tlConfig.enabled = FALSE; } if (labelHeightPart1 < 0 || labelWidthPart2 < 0) { trConfig.enabled = FALSE; } if (labelHeightPart2 < 0 || labelWidthPart1 < 0) { blConfig.enabled = FALSE; } if (labelHeightPart2 < 0 || labelWidthPart1 < 0) { brConfig.enabled = FALSE; } } else { quadrantConfig.enabled = FALSE; } return quadrant; }; /** * Creates Containers where the self graphics are appended */ Quadrant.prototype._createGroups = function _createGroups() { var quadrant = this, chart = quadrant.getFromEnv('chart'), animationManager = chart.getFromEnv('animationManager'), quadrantContainer = chart.getChildren('canvas')[0].getChildContainer('quadrantGroup'), quadrantChildContainer, quadrantChildContainerCheck = quadrant.getContainer('quadrantChildContainer'), quadrantLineGroup = quadrant.getContainer('quadrantLineGroup'), quadrantTLGroup = quadrant.getContainer('quadrantTLGroup'), quadrantTRGroup = quadrant.getContainer('quadrantTRGroup'), quadrantBLGroup = quadrant.getContainer('quadrantBLGroup'), quadrantBRGroup = quadrant.getContainer('quadrantBRGroup'); quadrantChildContainer = animationManager.setAnimation({ el: quadrantChildContainerCheck || 'group', attr: { name: 'quadrant-child-container' }, container: quadrantContainer, component: quadrant, label: 'group' }); if (!quadrantChildContainerCheck) { quadrant.addContainer('quadrantChildContainer', quadrantChildContainer); } quadrant.addContainer('quadrantLineGroup', animationManager.setAnimation({ el: quadrantLineGroup || 'group', attr: { name: 'quadrantLineGroup' }, container: quadrantChildContainer, component: quadrant, label: 'group' })); quadrant.addContainer('quadrantTLGroup', animationManager.setAnimation({ el: quadrantTLGroup || 'group', attr: { name: 'quadrantTLGroup' }, container: quadrantChildContainer, component: quadrant, label: 'group' })); quadrant.addContainer('quadrantTRGroup', animationManager.setAnimation({ el: quadrantTRGroup || 'group', attr: { name: 'quadrantTRGroup' }, container: quadrantChildContainer, component: quadrant, label: 'group' })); quadrant.addContainer('quadrantBLGroup', animationManager.setAnimation({ el: quadrantBLGroup || 'group', attr: { name: 'quadrantBLGroup' }, container: quadrantChildContainer, component: quadrant, label: 'group' })); quadrant.addContainer('quadrantBRGroup', animationManager.setAnimation({ el: quadrantBRGroup || 'group', attr: { name: 'quadrantBRGroup' }, container: quadrantChildContainer, component: quadrant, label: 'group' })); }; /** * Draws the graphics of Quadrant component */ Quadrant.prototype.draw = function draw() { var quadrant = this._preDraw(), // do the pre-draw calculations. quadrantConfig = quadrant.conf, chart = quadrant.getFromEnv('chart'), chartConfig = chart.config, reverseXAxis = chartConfig.reverseXAxis, smartText, defaultObj = { wrtVisible: true }, smartLabel = quadrant.getFromEnv('smartLabel'), animationManager = quadrant.getFromEnv('animationManager'), graphics = quadrant.graphics, tlLabel = graphics.tlLabel, trLabel = graphics.trLabel, blLabel = graphics.blLabel, brLabel = graphics.brLabel, textDirection = chartConfig.textDirection, xAxis = chart.getChildren('xAxis')[0], yAxis = chart.getChildren('yAxis')[0], quadrantChildContainer, quadrantLineGroup, quadrantTLGroup, quadrantTRGroup, quadrantBLGroup, quadrantBRGroup, tlConfig = quadrantConfig.tlConfig || {}, trConfig = quadrantConfig.trConfig || {}, blConfig = quadrantConfig.blConfig || {}, brConfig = quadrantConfig.brConfig || {}, // quadrant labels quadrantLabelTL = tlConfig.enabled && tlConfig.label, quadrantLabelTR = trConfig.enabled && trConfig.label, quadrantLabelBL = blConfig.enabled && blConfig.label, quadrantLabelBR = brConfig.enabled && brConfig.label, offsetLeft = chartConfig.canvasLeft, offsetTop = chartConfig.canvasTop, padding = quadrantConfig.quadrantLabelPadding, xAxisLimit = xAxis.getLimit(), yAxisLimit = yAxis.getLimit(), xAxisMax = reverseXAxis ? xAxisLimit.min : xAxisLimit.max, xAxisMin = reverseXAxis ? xAxisLimit.max : xAxisLimit.min, yAxisMax = yAxisLimit.max, yAxisMin = yAxisLimit.min, // max and min values of axes in pixels. xMin = xAxis.getPixel(xAxisMin, defaultObj) + padding, xMax = xAxis.getPixel(xAxisMax, defaultObj) - padding, yMin = yAxis.getPixel(yAxisMin, defaultObj) - padding, yMax = yAxis.getPixel(yAxisMax, defaultObj) + padding, quadXPos = xAxis.getPixel(quadrantConfig.xVal, defaultObj), quadYPos = yAxis.getPixel(quadrantConfig.yVal, defaultObj), quadLeftWidth = quadXPos - xMin, quadRightWidth = xMax - quadXPos, quadTopHeight = quadYPos - yMax, quadBottomHeight = yMin - quadYPos, horizontalQuadLine = graphics.horizontalQuadLine, verticalQuadLine = graphics.verticalQuadLine, hookFnHide = function hookFnHide() { this.hide(); }; quadrant._createGroups(); quadrantChildContainer = quadrant.getContainer('quadrantChildContainer'); quadrantLineGroup = quadrant.getContainer('quadrantLineGroup'); quadrantTLGroup = quadrant.getContainer('quadrantTLGroup'); quadrantTRGroup = quadrant.getContainer('quadrantTRGroup'); quadrantBLGroup = quadrant.getContainer('quadrantBLGroup'); quadrantBRGroup = quadrant.getContainer('quadrantBRGroup'); if (quadrantConfig.enabled) { quadrantChildContainer.show(); // drawing the lines. graphics.horizontalQuadLine = animationManager.setAnimation({ el: horizontalQuadLine || 'path', container: quadrantLineGroup, attr: { path: 'M' + offsetLeft + ' ' + quadYPos + 'h' + chartConfig.canvasWidth, stroke: quadrantConfig.quadrantLineColor, 'stroke-dasharray': quadrantConfig.dashStyle, 'stroke-width': quadrantConfig.quadrantLineThickness, 'stroke-linecap': 'butt' }, component: quadrant, label: 'path' }); graphics.verticalQuadLine = animationManager.setAnimation({ el: verticalQuadLine || 'path', container: quadrantLineGroup, attr: { path: 'M' + quadXPos + ' ' + offsetTop + 'v' + chartConfig.canvasHeight, stroke: quadrantConfig.quadrantLineColor, 'stroke-width': quadrantConfig.quadrantLineThickness, 'stroke-dasharray': quadrantConfig.dashStyle, 'stroke-linecap': 'butt' }, component: quadrant, label: 'path' }); // draw the labels of the quadrant along with applying the cosmetics and trim using smartLabel if (quadrantLabelTL) { smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); smartLabel.setStyle(quadrantConfig.tlConfig.styleObj); smartText = smartLabel.getSmartText(quadrantLabelTL, quadLeftWidth, quadTopHeight); // Create tlLabel if not present tlLabel = graphics.tlLabel = animationManager.setAnimation({ el: tlLabel || 'text', attr: { 'text-anchor': POSITION_START, 'vertical-align': POSITION_TOP, x: xMin, y: yMax, text: smartText.text, direction: textDirection, 'text-bound': quadrantConfig.tlConfig['text-bound'] }, container: quadrantTLGroup, component: quadrant, label: 'text' }); tlLabel.css(quadrantConfig.tlConfig.styleObj); } else { tlLabel && animationManager.setAnimation({ el: tlLabel, callback: hookFnHide, component: this, label: 'text' }); } if (quadrantLabelTR) { smartLabel.setStyle(quadrantConfig.trConfig.styleObj); smartText = smartLabel.getSmartText(quadrantLabelTR, quadRightWidth, quadTopHeight); // Create trLabel if not present trLabel = graphics.trLabel = animationManager.setAnimation({ el: trLabel || 'text', attr: { 'text-anchor': POSITION_END, 'vertical-align': POSITION_TOP, direction: textDirection, x: xMax, y: yMax, text: smartText.text, 'text-bound': quadrantConfig.trConfig['text-bound'] }, container: quadrantTRGroup, component: quadrant, label: 'text' }); trLabel.css(quadrantConfig.trConfig.styleObj); } else { trLabel && animationManager.setAnimation({ el: trLabel, callback: hookFnHide, component: this, label: 'text' }); } if (quadrantLabelBL) { smartLabel.setStyle(quadrantConfig.blConfig.styleObj); smartText = smartLabel.getSmartText(quadrantLabelBL, quadLeftWidth, quadBottomHeight); // Create blLabel if not present blLabel = graphics.blLabel = animationManager.setAnimation({ el: blLabel || 'text', attr: { 'text-anchor': POSITION_START, 'vertical-align': POSITION_BOTTOM, direction: textDirection, x: xMin, y: yMin, text: smartText.text, 'text-bound': quadrantConfig.blConfig['text-bound'] }, container: quadrantBLGroup, component: quadrant, label: 'text' }); blLabel.css(quadrantConfig.blConfig.styleObj); } else { blLabel && animationManager.setAnimation({ el: blLabel, callback: hookFnHide, component: this, label: 'text' }); } if (quadrantLabelBR) { smartLabel.setStyle(quadrantConfig.brConfig.styleObj); smartText = smartLabel.getSmartText(quadrantLabelBR, quadRightWidth, quadBottomHeight); // Create brLabel if not present brLabel = graphics.brLabel = animationManager.setAnimation({ el: brLabel || 'text', attr: { 'text-anchor': POSITION_END, 'vertical-align': POSITION_BOTTOM, direction: textDirection, x: xMax, y: yMin, text: smartText.text, 'text-bound': quadrantConfig.brConfig['text-bound'] }, container: quadrantBRGroup, component: quadrant, label: 'text' }); brLabel.css(quadrantConfig.brConfig.styleObj); } else { brLabel && animationManager.setAnimation({ el: brLabel, callback: hookFnHide, component: this, label: 'text' }); } } else { // quadrantContainer && chart.getChildren('canvas')[0].removeChildContainer('quadrantGroup'); quadrantChildContainer && animationManager.setAnimation({ el: quadrantChildContainer, component: quadrant, doNotRemove: true, callback: function callback() { this.hide(); }, label: 'group' }); } }; return Quadrant; }(_componentInterface.ComponentInterface); exports['default'] = Quadrant; /***/ }), /* 536 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = { 'initial.canvas.quadrant': function initialCanvasQuadrant() { return { 'path.appearing': function pathAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'axis' }]; }, 'text.appearing': function textAppearing() { return [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'plot' }]; } }; } }; /***/ }), /* 537 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var canvas = chart.getChildren('canvas')[0], axisRefVisualCartesian = canvas.getChildren('axisRefVisualCartesian')[0], zoomObj = { zoomable: true, pannable: true }, config = chart._feedAxesRawData(), yAxis = void 0, xAxis = void 0, redraw = function redraw(e) { var sender = e.sender; axisRefVisualCartesian.addexplicitDrawItems(sender.getId(), sender); axisRefVisualCartesian.asyncDraw(); }; (0, _lib.componentFactory)(chart, _numeric2['default'], 'yAxis', 1, config.yAxisConf); (0, _lib.componentFactory)(chart, _numeric2['default'], 'xAxis', 1, config.xAxisConf); yAxis = chart.getChildren('yAxis')[0]; xAxis = chart.getChildren('xAxis')[0]; yAxis.setLinkedItem('canvas', canvas); xAxis.setLinkedItem('canvas', canvas); axisRefVisualCartesian.setLinkedItem(yAxis.getId(), yAxis); axisRefVisualCartesian.setLinkedItem(xAxis.getId(), xAxis); axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, xAxis); axisRefVisualCartesian.addExtEventListener('visiblerangeset', redraw, yAxis); canvas.attachAxis(xAxis, false, chart.zoomX ? zoomObj : {}); canvas.attachAxis(yAxis, true, chart.zoomY ? zoomObj : {}); chart._setCategories(); }; var _lib = __webpack_require__(125); var _numeric = __webpack_require__(377); var _numeric2 = _interopRequireDefault(_numeric); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 538 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _line = __webpack_require__(449); var _line2 = _interopRequireDefault(_line); var _lib = __webpack_require__(125); var _dependencyManager = __webpack_require__(132); var _kdtree = __webpack_require__(539); var _kdtree2 = _interopRequireDefault(_kdtree); var _index = __webpack_require__(540); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var math = Math, mathMax = math.max, mathMin = math.min, mathRound = math.round; var UNDEF, COMMA = ',', NONE = 'none', COMMASTRING = ',', PLOTGRADIENTCOLOR = 'plotGradientColor', SHOWSHADOW = 'showShadow', // math = Math, // mathPow = math.pow, // Function that produce the point color getPointColor = function getPointColor(color, alpha) { var colorObj, innerColor, outerColor; color = (0, _lib.getFirstColor)(color); alpha = (0, _lib.getFirstAlpha)(alpha); innerColor = (0, _lib.getLightColor)(color, 70); outerColor = (0, _lib.getDarkColor)(color, 50); colorObj = { FCcolor: { gradientUnits: 'objectBoundingBox', cx: 0.4, cy: 0.4, r: '100%', color: innerColor + COMMASTRING + outerColor, alpha: alpha + COMMASTRING + alpha, ratio: _lib.BGRATIOSTRING, radialGradient: true } }; return colorObj; }; (0, _dependencyManager.addDep)({ name: 'scatterAnimation', type: 'animationRule', extension: _index2['default'] }); var ScatterDataset = function (_LineDataset) { _inherits(ScatterDataset, _LineDataset); function ScatterDataset() { _classCallCheck(this, ScatterDataset); return _possibleConstructorReturn(this, _LineDataset.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ ScatterDataset.prototype.getType = function getType() { return 'dataset'; }; /** * Handle K-D Tree related tasks to ensure smooth hover experience. */ ScatterDataset.prototype.setupHoverTracker = function setupHoverTracker() { var dataset = this, // Search data to store data in separate array that will be used in KdTree search Algorithm searchDataArr = dataset.config.searchDataArr = [], dsComponents = dataset.components, dataStore = dsComponents.data, anchorProps = {}, i, j, ii, xPos, yPos, dataObj, plotConfig, skippingInfo = dataset.getSkippingInfo && dataset.getSkippingInfo(), plotDrawArray = skippingInfo && skippingInfo.draw || [], plotDrawArrayLength = plotDrawArray.length, skippingApplied = skippingInfo && skippingInfo.skippingApplied; ii = dataStore.length; if (skippingApplied) { ii = plotDrawArrayLength; } for (j = 0; j < ii; j++) { i = plotDrawArray[j] || [j]; dataObj = dataStore[i]; if (dataObj) { plotConfig = dataObj.config; xPos = plotConfig._Px; yPos = plotConfig._Py; anchorProps = plotConfig.anchorProps; // Pushing object to custom array that will be required for K-D Tree Search Algorithm // (in integer format) searchDataArr.push({ x: xPos, y: yPos, index: i, data: dataObj, r: anchorProps.radius || 0 }); } } // Building KdTree with the x and y positions of all the plots. this.config.dataTree = new _kdtree2['default']().buildKdTree(searchDataArr); }; /** * Returns the name of this component * * @return {string} The name of this component */ ScatterDataset.prototype.getName = function getName() { return 'scatter'; }; /* * Parses all the attributes for dataset level and set level * Called from init function of scatter class */ ScatterDataset.prototype.configureAttributes = function configureAttributes(datasetJSON) { if (!datasetJSON) { return false; } this.trimData(datasetJSON); this.config.JSONData = datasetJSON; var plotBorderDash, parentYAxis, enableAnimation, defaultShadow, dataSet = this, chart = dataSet.getFromEnv('chart'), conf = dataSet.config, JSONData = conf.JSONData, areaAlpha = chart.areaAlpha, // chart level JSON format chartAttr = chart.getFromEnv('dataSource').chart, colorM = dataSet.getFromEnv('color-manager'), showplotborder = (0, _lib.pluckNumber)(JSONData.showplotborder, chartAttr.showplotborder || 1), plotFillColor = colorM.getPlotColor(dataSet.index), usePlotGradientColor, lineDashed = conf.lineDashed = (0, _lib.pluckNumber)(JSONData.linedashed, JSONData.dashed, chartAttr.linedashed, 0), isLineSet = dataSet.isLineSet; conf.plotColor = plotFillColor; defaultShadow = (0, _lib.pluckNumber)(chart.defaultPlotShadow, colorM.getColor(SHOWSHADOW)); conf.xAxisLabelMode = (0, _lib.pluck)(chartAttr.xaxislabelmode, 'categories'); conf.toolTipSepChar = (0, _lib.pluck)(chartAttr.tooltipsepchar, ', '); conf.defaultValuePadding = { left: 0, right: 0 }; // Functional attributes configuration // ParentYAxis is always 1 for lineset if (isLineSet) { conf.parentYAxis = parentYAxis = 1; } else { conf.parentYAxis = parentYAxis = (0, _lib.pluck)(JSONData.parentyaxis && JSONData.parentyaxis.toLowerCase(), 'p') === 's' ? 1 : 0; } dataSet.config.yAxis = dataSet.getFromEnv('yAxis')[parentYAxis]; conf.connectNullData = (0, _lib.pluckNumber)(chartAttr.connectnulldata, 0); conf.seriesname = (0, _lib.parseUnsafeString)(JSONData.seriesname); conf.includeinlegend = (0, _lib.pluckNumber)(JSONData.includeinlegend, conf.seriesname ? 1 : 0); // Animation related attributes configuration conf.enableAnimation = enableAnimation = (0, _lib.pluckNumber)(chartAttr.animation, chartAttr.defaultanimation, 1); conf.animation = !enableAnimation ? false : { duration: (0, _lib.pluckNumber)(chartAttr.animationduration, 1) * 1000 }; conf.transposeanimation = (0, _lib.pluckNumber)(chartAttr.transposeanimation, enableAnimation); conf.transposeanimduration = (0, _lib.pluckNumber)(chartAttr.transposeanimduration, 0.2) * 1000; // Value related configurations conf.showvalues = (0, _lib.pluckNumber)(JSONData.showvalues, chartAttr.showvalues); conf.valuePadding = (0, _lib.pluckNumber)(chartAttr.valuepadding, 2); conf.valuePosition = (0, _lib.pluck)(JSONData.valueposition, chartAttr.valueposition, 'auto'); // Tooltip related attributes conf.showTooltip = (0, _lib.pluckNumber)(chartAttr.showtooltip, 1); conf.seriesNameInTooltip = (0, _lib.pluckNumber)(chartAttr.seriesnameintooltip, 1); // Regression Line cosmetics // conf.showRegressionLine = pluckNumber(JSONData.showregressionline, chartAttr.showregressionline, 0); // Data Plot cosmetics attributes configuration parsing conf.plotFillColor = conf.plotfillcolor = (0, _lib.pluck)(JSONData.color, chartAttr.plotfillcolor, plotFillColor); conf.plotFillAngle = conf.plotFillAngle = (0, _lib.pluck)(chartAttr.plotfillangle, 270); conf.plotFillAlpha = conf.plotfillalpha = (0, _lib.pluck)(JSONData.alpha, chartAttr.plotfillalpha, areaAlpha, '70'); usePlotGradientColor = (0, _lib.pluckNumber)(chartAttr.useplotgradientcolor, 1); conf.plotGradientColor = conf.plotgradientcolor = usePlotGradientColor !== 0 ? (0, _lib.getDefinedColor)(chartAttr.plotgradientcolor, colorM.getColor(PLOTGRADIENTCOLOR)) : ''; conf.fillColor = conf.fillcolor = { color: conf.plotfillcolor + (conf.plotgradientcolor ? COMMA + conf.plotgradientcolor : _lib.BLANKSTRING), alpha: conf.plotfillalpha, angle: conf.plotFillAngle }; conf.plotBorderAlpha = conf.plotborderalpha = showplotborder ? (0, _lib.pluck)(JSONData.plotborderalpha, chartAttr.plotborderalpha, JSONData.alpha, '95') : 0; conf.plotBorderColor = conf.plotbordercolor = (0, _lib.pluck)(JSONData.plotbordercolor, chartAttr.plotbordercolor, chartAttr.areabordercolor, '666666'); conf.dashed = plotBorderDash = (0, _lib.pluckNumber)(JSONData.dashed, chartAttr.plotborderdashed); conf.plotBorderDashLen = conf.plotborderdashlen = (0, _lib.pluck)(JSONData.plotborderdashlen, chartAttr.plotborderdashlen, 5); conf.plotBorderDashGap = conf.plotborderdashgap = (0, _lib.pluck)(JSONData.plotborderdashgap, chartAttr.plotborderdashgap, 4); conf.plotBorderThickness = conf.plotborderthickness = (0, _lib.pluckNumber)(JSONData.plotborderthickness, chartAttr.plotborderthickness, 1); conf.plotBorderDashStyle = conf.plotborderdashstyle = plotBorderDash ? (0, _lib.getDashStyle)(conf.plotborderdashlen, conf.plotborderdashgap) : 'none'; conf.showHoverEffect = conf.showhovereffect = (0, _lib.pluckNumber)(chartAttr.plothovereffect, chartAttr.anchorhovereffect, chartAttr.showhovereffect, UNDEF); conf.rotateValues = (0, _lib.pluckNumber)(chartAttr.rotatevalues) ? 270 : 0; // Line configuration attributes parsing conf.drawLine = (0, _lib.pluckNumber)(JSONData.drawline, chartAttr.drawlines, 0); conf.lineThickness = conf.linethickness = (0, _lib.pluckNumber)(JSONData.linethickness, chartAttr.linethickness, 2); conf.lineDashLen = conf.linedashlen = (0, _lib.pluckNumber)(JSONData.linedashlen, chartAttr.linedashlen, 5); conf.lineDashGap = conf.linedashgap = (0, _lib.pluckNumber)(JSONData.linedashgap, chartAttr.linedashgap, 4); conf.lineAlpha = conf.linealpha = (0, _lib.pluckNumber)(JSONData.linealpha, chartAttr.linealpha, JSONData.alpha, _lib.HUNDREDSTRING); conf.lineColor = conf.linecolor = (0, _lib.pluck)(JSONData.linecolor, chartAttr.linecolor, JSONData.color, conf.plotColor); conf.lineDashStyle = conf.linedashstyle = (0, _lib.getDashStyle)(conf.linedashlen, conf.linedashgap); conf.lineDashStyle = conf.linedashstyle = lineDashed ? conf.linedashstyle : NONE; // todo remove if not applicable in scatter chart. conf.shadow = { opacity: (0, _lib.pluckNumber)(chartAttr.showshadow, defaultShadow) ? conf.linealpha / 100 : 0 }; // Anchor cosmetics attributes in dataset level // Whether to draw the Anchors or not. conf.drawanchors = (0, _lib.pluckNumber)(JSONData.drawanchors, JSONData.showanchors, chartAttr.drawanchors, chartAttr.showanchors); conf.anchorbgcolor = (0, _lib.getFirstColor)((0, _lib.pluck)(JSONData.anchorbgcolor, chartAttr.anchorbgcolor, colorM.getColor('anchorBgColor'))); conf.anchorbordercolor = (0, _lib.getFirstColor)((0, _lib.pluck)(JSONData.anchorbordercolor, JSONData.color, chartAttr.anchorbordercolor, conf.linecolor)); conf.anchorradius = (0, _lib.pluckNumber)(JSONData.anchorradius, chartAttr.anchorradius, 3); conf.anchoralpha = (0, _lib.pluck)(JSONData.anchoralpha, JSONData.alpha, chartAttr.anchoralpha, _lib.HUNDREDSTRING); conf.anchorbgalpha = (0, _lib.pluck)(JSONData.anchorbgalpha, JSONData.alpha, chartAttr.anchorbgalpha, _lib.HUNDREDSTRING); conf.anchorborderthickness = (0, _lib.pluck)(JSONData.anchorborderthickness, chartAttr.anchorborderthickness, 1); // We first look into dataset then chart obj and then default value. conf.anchorsides = (0, _lib.pluckNumber)(JSONData.anchorsides, chartAttr.anchorsides, conf.index + 3); // Anchor image cosmetics attributes conf.anchorimageurl = (0, _lib.pluck)(JSONData.anchorimageurl, chartAttr.anchorimageurl); conf.anchorimagealpha = (0, _lib.pluckNumber)(JSONData.anchorimagealpha, chartAttr.anchorimagealpha, 100); conf.anchorimagescale = (0, _lib.pluckNumber)(JSONData.anchorimagescale, chartAttr.anchorimagescale, 100); conf.anchorimagepadding = (0, _lib.pluckNumber)(JSONData.anchorimagepadding, chartAttr.anchorimagepadding, 1); conf.anchorstartangle = (0, _lib.pluckNumber)(JSONData.anchorstartangle, chartAttr.anchorstartangle, 90); conf.anchorshadow = (0, _lib.pluckNumber)(JSONData.anchorshadow, chartAttr.anchorshadow, 0); conf.plotToolText = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(JSONData.plottooltext, chartAttr.plottooltext))); dataSet.setState('visible', (0, _lib.pluckNumber)(JSONData.visible, !Number(JSONData.initiallyhidden), 1) === 1); dataSet._setConfigure(); chart.config.hasLegend !== false && chart.config.showLegend && dataSet._addLegend(); dataSet.setState('dirty', true); }; /** * calculate min and max position to scroll */ ScatterDataset.prototype.calculateScrollRange = function calculateScrollRange() { var dataSet = this, dsConfig = dataSet.config, chart = dataSet.getFromEnv('chart'), xAxis = dataSet.getFromEnv('xAxis'), hasScroll = chart.hasScroll, dataStore = dataSet.components.data, dsLen = dataStore.length; dsConfig.scrollMinVal = hasScroll ? mathMax(mathRound(xAxis.getVisibleConfig().minValue) - 1, 0) : 0; dsConfig.scrollMaxVal = hasScroll ? mathMin(mathRound(xAxis.getVisibleConfig().maxValue) + 2, dsLen) : dsLen; // Since panning and data skipping are not applicable for scatter and bubble charts, the labels' // minimum and maximum index to be drawn is the same as the plots' minimum and maximum index. dsConfig.scrollMinValForLabel = dsConfig.scrollMinVal; dsConfig.scrollMaxValForLabel = dsConfig.scrollMaxVal; }; /** * Sets the configurations for the set level attributes. */ ScatterDataset.prototype._setConfigure = function _setConfigure() { var i, config, dataObj, setData, setValue, toolText, toolTipValue, macroIndices, parserConfig, formatedVal, formatedValX, setDisplayValue, infMin = -Infinity, infMax = +Infinity, yMax = infMin, yMin = infMax, xMin = infMax, xMax = infMin, dataSet = this, dataStore = dataSet.components.data || (dataSet.components.data = []), chart = dataSet.getFromEnv('chart'), conf = dataSet.config, JSONData = conf.JSONData, // chart level JSON format chartAttr = chart.getFromEnv('dataSource').chart, setDataArr = JSONData.data || [], dataSetLen = setDataArr.length, numberFormatter = dataSet.getFromEnv('number-formatter'), yAxisName = (0, _lib.parseUnsafeString)(chartAttr.yaxisname), xAxisName = (0, _lib.parseUnsafeString)(chartAttr.xaxisname), lineDashed = conf.lineDashed, lineDashStyle = conf.linedashstyle, parentYAxis = conf.parentYAxis, tooltipSepChar = conf.toolTipSepChar, seriesname = conf.seriesname; conf.imageCount = 0; // Iterate through all set level data for (i = 0; i < dataSetLen; i += 1) { setData = setDataArr[i]; dataObj = dataStore[i] || (dataStore[i] = {}); config = dataObj.config || (dataObj.config = {}); // The set data is given: {x: , y : } config.setValue = setValue = { x: numberFormatter.getCleanValue(setData.x), y: numberFormatter.getCleanValue(setData.y) }; if (setValue.x !== null && setValue.y !== null) { if (setValue.x > xMax) { xMax = setValue.x; conf.rightMostData = dataObj; } if (setValue.x < xMin) { xMin = setValue.x; conf.leftMostData = dataObj; } if (setValue.y > yMax) { yMax = setValue.y; conf.topMostData = dataObj; } if (setValue.y < yMin) { yMin = setValue.y; conf.bottomMostData = dataObj; } } // update the regression calulations. // conf.showRegressionLine && pointValueWatcher(setValue.x, setValue.y, conf.regressionObj); config._x = setValue.x; config._y = setValue.y; config.setLink = (0, _lib.pluck)(setData.link); // Parsing the anchor properties for set level config.anchorProps = this._parseAnchorProperties(i); config.showValue = (0, _lib.pluckNumber)(setData.showvalue, conf.showvalues); // Dashed, color and alpha configuration in set level is only for line chart config.dashed = (0, _lib.pluckNumber)(setData.dashed, lineDashed); config.color = (0, _lib.pluck)(setData.color, conf.linecolor); config.alpha = (0, _lib.pluck)(setData.alpha, conf.linealpha); config.dashStyle = config.dashed ? lineDashStyle : 'none'; config.toolTipValue = toolTipValue = numberFormatter.dataLabels(setValue.y, parentYAxis); config.setDisplayValue = setDisplayValue = (0, _lib.parseUnsafeString)(setData.displayvalue); formatedVal = config.formatedVal = (0, _lib.pluck)(setData.toolTipValue, numberFormatter.dataLabels(setValue.y, parentYAxis)); formatedValX = numberFormatter.xAxis(setValue.x); config.displayValue = (0, _lib.pluck)(setDisplayValue, toolTipValue); config.setTooltext = (0, _lib.getValidValue)((0, _lib.parseUnsafeString)((0, _lib.pluck)(setData.tooltext, conf.plotToolText))); // Initial tooltext parsing if (!conf.showTooltip) { toolText = false; } else if (config.setTooltext !== UNDEF) { macroIndices = [4, 5, 6, 7, 8, 9, 10, 11]; parserConfig = { yaxisName: yAxisName, xaxisName: xAxisName, yDataValue: formatedVal, xDataValue: formatedValX }; toolText = (0, _lib.parseTooltext)(config.setTooltext, macroIndices, parserConfig, setData, chartAttr, JSONData); } else { // determine the default tooltext then. if (formatedVal === null) { toolText = false; } else { toolText = seriesname ? seriesname + tooltipSepChar : _lib.BLANKSTRING; toolText += setValue.x ? formatedValX + tooltipSepChar : _lib.BLANKSTRING; toolText += toolTipValue; } } config.toolText = toolText; if (!dataObj) { dataObj = dataStore[i] = { graphics: {} }; } else if (!dataObj.graphics) { dataStore[i].graphics = {}; } // parse the hover cosmetics. config.hoverEffects = this._parseHoverEffectOptions(dataObj, setData); config.anchorProps.isAnchorHoverRadius = config.hoverEffects.anchorRadius; } conf.xMax = xMax; conf.xMin = xMin; conf.yMin = yMin; conf.yMax = yMax; dataSet.ErrorValueConfigure && dataSet.ErrorValueConfigure(); }; /* * Using kdtree algo for searching */ ScatterDataset.prototype._getHoveredPlot = function _getHoveredPlot(x, y) { var res = this.config.dataTree.getNeighbour({ x: x, y: y }, true); // searching neighbour from Kdtree with basic search flag on if (res) { return { pointIndex: res.index || res.i, hovered: true, pointObj: res.data }; } }; /** * drawPlots: Function to draw anchor elements or columns in case of column chart */ ScatterDataset.prototype.drawPlots = function drawPlots() { _LineDataset.prototype.drawPlots.call(this); this.setupHoverTracker(); }; /** * API to find out the maximum and minimum values of regressionline path. * * @returns {Object} xMax, xMin, yMax, yMin * @memberof ScatterDataset */ ScatterDataset.prototype.getRegressionPoints = function getRegressionPoints() { var dataset = this, regression = dataset.getChildren('regression'), regressionPoints, xMax = -Infinity, xMin = Infinity, yMax = -Infinity, yMin = Infinity, i, j, k, line, points, regLineLength, regPointsLength; if (!regression || !regression.length || regression[0].getState('removed')) { return; } regressionPoints = regression[0]._config.regressionPoints || []; regLineLength = regressionPoints.length; for (i = 0; i < regLineLength; i++) { line = regressionPoints[i]; for (j = 0; j < line.length; j++) { points = line[j] || []; regPointsLength = points.length; for (k = 0; k < regPointsLength; k++) { xMax = Math.max(xMax, points[k].x); xMin = Math.min(xMin, points[k].x); yMax = Math.max(yMax, points[k].y); yMin = Math.min(yMin, points[k].y); } } } return { max: yMax, min: yMin, xMax: xMax, xMin: xMin }; }; ScatterDataset.prototype.getDataLimits = function getDataLimits() { var dataset = this, conf = dataset.config, chart = dataset.getFromEnv('chart'), chartConfig = chart.config, max = conf.yMax, min = conf.yMin, xMax = conf.xMax, xMin = conf.xMin, infMin = -Infinity, infMax = +Infinity, transposeAxis = chartConfig.transposeAxis, regressionPoints = dataset.getRegressionPoints(); if (dataset.getState('visible') === false && transposeAxis) { max = infMin; min = infMax; xMax = infMin; xMin = infMax; } if (regressionPoints) { max = Math.max(max, regressionPoints.max); min = Math.min(min, regressionPoints.min); xMax = Math.max(xMax, regressionPoints.xMax); xMin = Math.min(xMin, regressionPoints.xMin); } return { max: max, min: min, xMax: xMax, xMin: xMin }; }; ScatterDataset.prototype.getAxisValuePadding = function getAxisValuePadding() { return this.config.defaultValuePadding; }; /** * This functions calculate the space required for a dataset and return that to the chart * @return {Object} dimention */ ScatterDataset.prototype.getCanvasPadding = function getCanvasPadding() { var dataset = this, conf = dataset.config || (dataset.config = {}), components = dataset.components || {}, chartConfig = dataset.getFromEnv('chartConfig'), rotateValues = chartConfig.rotatevalues, xAxis = dataset.getFromEnv('xAxis'), yAxis = dataset.getFromEnv('yAxis'), reversexaxis = xAxis.config.isReverse, dataLabelStyle = dataset.getFromEnv('dataLabelStyle'), data = components.data || [], dataLen = data.length, firstData = conf.leftMostData || data[0], lastData = conf.rightMostData || data[data.length - 1], topMostData = conf.topMostData, bottomMostData = conf.bottomMostData, radiusLimit = mathMin(chartConfig.canvasHeight, chartConfig.canvasWidth) / 8, sqrtMaxZ, startValue = xAxis.getValue(0), firstDataChangeFlag = 1, secondDataChangeFlag = 1, radiusFactor, configAttr, configAttrFirst, configAttrLast, dataConf, anchorRadius, zMax = chartConfig.zMax, sqrtBubbleZ, minPoint, bubbleScale = conf.bubbleScale, i, xReduced, xReducedFirst, xReducedLast, label, bubbleRadius, bubbleRadiusVal, labelDimEnd = {}, labelDimStart = {}, anchorSpace = 0, labelSpace = 0, showValue, xAxisRange = xAxis.config.axisRange, xAxisMin = xAxisRange.min, xAxisMax = xAxisRange.max, yAxisRange = yAxis.config.axisRange, yAxisMin = yAxisRange.min, yAxisMax = yAxisRange.max, startPixel = xAxis.getPixel(xAxisMin), endPixel = xAxis.getPixel(xAxisMax), SmartLabel = dataset.getFromEnv('smartLabel'), returnDimension = { paddingLeft: 0, paddingRight: 0 }, labelWidth = 0, yReduced; sqrtMaxZ = Math.sqrt(zMax); radiusFactor = radiusLimit / sqrtMaxZ; for (i = 0; i < dataLen; i++) { configAttr = data[i].config; configAttrFirst = firstData.config; configAttrLast = lastData.config; // finding the radius of the current point sqrtBubbleZ = Math.sqrt(configAttr.z); bubbleRadius = Math.round(sqrtBubbleZ * radiusFactor) * bubbleScale || 0; bubbleRadiusVal = xAxis.getValue(bubbleRadius) - startValue; xReduced = configAttr.x - bubbleRadiusVal / 2; // finding the radius of the firstData if (firstDataChangeFlag === 1) { sqrtBubbleZ = Math.sqrt(configAttrFirst.z); bubbleRadius = Math.round(sqrtBubbleZ * radiusFactor) * bubbleScale || 0; bubbleRadiusVal = xAxis.getValue(bubbleRadius) - startValue; xReducedFirst = configAttrFirst.x - bubbleRadiusVal / 2; } // finding the radius of the lastData if (secondDataChangeFlag === 1) { sqrtBubbleZ = Math.sqrt(configAttrLast.z); bubbleRadius = Math.round(sqrtBubbleZ * radiusFactor) * bubbleScale || 0; bubbleRadiusVal = xAxis.getValue(bubbleRadius) - startValue; xReducedLast = configAttrLast.x - bubbleRadiusVal / 2; } firstDataChangeFlag = 0; secondDataChangeFlag = 0; if (xReducedFirst > xReduced) { firstData = data[i]; firstDataChangeFlag = 1; } if (xReducedLast < xReduced) { lastData = data[i]; secondDataChangeFlag = 1; } } if (firstData) { dataConf = firstData.config; anchorRadius = dataConf.anchorProps.radius; showValue = dataConf.showValue; if (showValue) { label = dataConf.displayValue; SmartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); SmartLabel.setStyle(dataLabelStyle); labelDimStart = SmartLabel.getOriSize(label); labelWidth = rotateValues ? labelDimStart.height : labelDimStart.width; } if (dataConf.setValue !== null) { xReduced = xAxis.getPixel(dataConf.setValue.x); if (reversexaxis) { minPoint = xReduced - labelWidth * 0.5; labelSpace = endPixel - minPoint; } else { minPoint = xReduced - labelWidth * 0.5; labelSpace = startPixel - minPoint; } if (!reversexaxis && xReduced - anchorRadius <= startPixel || reversexaxis && xReduced - anchorRadius <= endPixel) { anchorSpace = reversexaxis ? endPixel - (xReduced - anchorRadius) : startPixel - (xReduced - anchorRadius); } else { anchorSpace = 0; } } returnDimension.paddingLeft = mathMax(labelSpace, anchorSpace); } if (lastData) { dataConf = lastData.config; showValue = dataConf.showValue; anchorRadius = dataConf.anchorProps.radius; if (showValue) { label = dataConf.displayValue; SmartLabel.setStyle(dataLabelStyle); labelDimEnd = SmartLabel.getOriSize(label); labelWidth = rotateValues ? labelDimEnd.height : labelDimEnd.width; } if (dataConf.setValue !== null) { xReduced = xAxis.getPixel(dataConf.setValue.x); minPoint = xReduced - startPixel + labelWidth * 0.5; labelSpace = minPoint - endPixel + startPixel; if (reversexaxis) { labelSpace = minPoint; } if (!reversexaxis && xReduced + anchorRadius >= endPixel || reversexaxis && xReduced + anchorRadius >= startPixel) { anchorSpace = reversexaxis ? xReduced + anchorRadius - startPixel : xReduced + anchorRadius - endPixel; } else { anchorSpace = 0; } } returnDimension.paddingRight = mathMax(labelSpace, anchorSpace); } if (topMostData) { dataConf = topMostData.config; anchorRadius = dataConf.anchorProps.radius || 0; yAxisMax = yAxis.getPixel(yAxisMax); if (dataConf.setValue !== null) { yReduced = yAxis.getPixel(dataConf.setValue.y); anchorSpace = (0, _lib.pluckNumber)(anchorRadius, 0) + (0, _lib.pluckNumber)(dataConf.anchorProps.borderThickness, 0) / 2; } if (yAxisMax - (yReduced - anchorSpace) > 0) { returnDimension.paddingTop = yAxisMax - (yReduced - anchorSpace); } else { returnDimension.paddingTop = 0; } } if (bottomMostData) { dataConf = bottomMostData.config; anchorRadius = dataConf.anchorProps.radius || 0; yAxisMin = yAxis.getPixel(yAxisMin); if (dataConf.setValue !== null) { yReduced = yAxis.getPixel(dataConf.setValue.y); anchorSpace = (0, _lib.pluckNumber)(anchorRadius, 0) + (0, _lib.pluckNumber)(dataConf.anchorProps.borderThickness, 0) / 2; } if (yReduced + anchorSpace - yAxisMin > 0) { returnDimension.paddingBottom = yReduced + anchorSpace - yAxisMin; } else { returnDimension.paddingBottom = 0; } } return returnDimension; }; // Function to register datasets in the internal data store of legend class. ScatterDataset.prototype._addLegend = function _addLegend() { var symbolColor, mFillColor, mLineColor, dataset = this, chart = dataset.getFromEnv('chart'), conf = dataset.config, config, legendItem, legend = chart.getChildren('legend')[0], drawAnchors = (0, _lib.pluckNumber)(conf.drawanchors, 1), marker = { fillColor: getPointColor(conf.anchorbgcolor, _lib.HUNDREDSTRING), lineColor: { FCcolor: { color: conf.anchorbordercolor, alpha: conf.anchoralpha } }, lineWidth: conf.anchorborderthickness }, item3dlighting = legend.config.symbol3DLighting; if (item3dlighting) { if (marker.fillcolor && marker.fillcolor.FCcolor) { symbolColor = (0, _lib.extend2)({}, marker.fillcolor); symbolColor.FCcolor.alpha = '100'; } else { symbolColor = (0, _lib.pluck)(marker.fillColor); } } else { symbolColor = { FCcolor: { color: (0, _lib.pluck)((mFillColor = marker.fillColor) && (mFillColor.FCcolor && mFillColor.FCcolor.color.split(COMMA)[0] || mFillColor)), angle: 0, ratio: '0', alpha: '100' } }; } config = { enabled: conf.includeInLegend, type: dataset.type, drawLine: (0, _lib.pluck)(conf.drawLine, true), anchorSide: drawAnchors ? conf.anchorsides : 0, label: (0, _lib.getFirstValue)(dataset.config.JSONData.seriesname) }; if (conf.includeinlegend) { legendItem = legend.getItem(dataset.config.legendItemId); if (!legendItem) { dataset.config.legendItemId = legend.createItem(dataset); legendItem = legend.getItem(dataset.config.legendItemId); dataset.addExtEventListener('fc-click', function () { legendItem.itemClickFn(); }, legendItem); } else { legendItem.configure({ style: legend.config.itemStyle, hiddenStyle: legend.config.itemHiddenStyle, datasetVisible: legend.config.datasetVisible, hoverStyle: legend.config.itemHoverStyle }); } legendItem.configure(config); legendItem.setStateCosmetics('default', { symbol: { fill: (0, _lib.toRaphaelColor)(symbolColor), rawFillColor: conf.anchorbgcolor, rawStrokeColor: conf.lineColor, stroke: (0, _lib.toRaphaelColor)((0, _lib.pluck)((mLineColor = marker.lineColor) && (mLineColor.FCcolor && mLineColor.FCcolor.color.split(COMMA)[0] || mLineColor))), 'stroke-width': conf.anchorborderthickness } }); // check if dataset is initiallyhidden if (!dataset.getState('visible')) { legendItem.setLegendState('hidden'); } else { // remove hidden state of legend item is dataset is not hidden legendItem.removeLegendState('hidden'); } } else if (dataset.config.legendItemId) { legend.disposeItem(dataset.config.legendItemId); } }; ScatterDataset.prototype.getDSGroupdef = function getDSGroupdef() { return UNDEF; }; /** * function to Remove data plots if the number of current data plots/categories * is more than the existing ones. * @param {Object} datasetJSON JSON for dataset configurations */ ScatterDataset.prototype.trimData = function trimData(datasetJSON) { if (!this.config.JSONData) { return; } var dataSet = this, config = dataSet.config, context = config && config.context, prevCatlen = context && context.prevCatlen, xAxis = dataSet.getFromEnv('xAxis'), currCatLen = xAxis.getTicksLen(), catDiff = prevCatlen - currCatLen, prevData = config.JSONData, prevDataLength = prevData.data && prevData.data.length, currDataLength = datasetJSON.data && datasetJSON.data.length || 0, dataDiff = prevDataLength - currDataLength, diff = void 0, startIndex = void 0; if (catDiff > dataDiff) { diff = catDiff; startIndex = currCatLen; } else { diff = dataDiff; startIndex = currDataLength; } // Removing data plots if the number of current data plots/categories // is more than the existing ones. if (diff > 0) { this.removeData(startIndex, diff, false); } }; return ScatterDataset; }(_line2['default']); exports['default'] = ScatterDataset; /***/ }), /* 539 */ /***/ (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"); } } /** ! * @license FusionCharts JavaScript Library - KDtree * Copyright FusionCharts Technologies LLP * License Information at * * @version //? write(JSON.parse(require('fs').readFileSync('./package.json')).version); */ /* ? // metascript to check license status for creditLabel var licenseActive = (!global.licensed + ' &&'); */ /** * @private * @module fusioncharts.renderer.javascript.kdtree * @export fusioncharts.kdtree.js */ /* * compareFunction : An optional argument for Array.Prototype.sort(). Used to change the default sorting order. * @param a {Object} and @param b {Object} - two elements being compared during the sort. */ // sorts the Array w.r.t to 'x' property of the array elements in an ascending order. var UNDEF, isWithinCircle = function isWithinCircle(x, y, cx, cy, r) { return Math.pow(cx - x, 2) + Math.pow(cy - y, 2) <= Math.pow(r, 2); }, mathPI = Math.PI, mathCos = Math.cos, mathSin = Math.sin, mathMax = Math.max, mathMin = Math.min, deg2rad = mathPI / 180, rad = function rad(deg) { return deg % 360 * deg2rad; }, orientation = function orientation(p1x, p1y, q1x, q1y, p2x, p2y) { var A = q1y - p1y, B = p2x - q1x, C = q1x - p1x, D = p2y - q1y, val1, val2, val; val1 = A * B; val2 = C * D; if (isNaN(val1)) { val1 = 0; } if (isNaN(val2)) { val2 = 0; } val = val1 - val2; if (val === 0) { return 0; // colinear } return val > 0 ? 1 : 2; }, onSegment = function onSegment(p1x, p1y, q1x, q1y, p2x, p2y) { if (q1x <= mathMax(p1x, p2x) && q1x >= mathMin(p1x, p2x) && q1y <= mathMax(p1y, p2y) && q1y >= mathMin(p1y, p2y)) { return true; } return false; }, doIntersect = function doIntersect(p1x, p1y, q1x, q1y, p2x, p2y, q2x, q2y) { // Find the four orientations needed for general and // special cases var o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y), o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y), o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y), o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y); // General case if (o1 !== o2 && o3 !== o4) { return true; } // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 === 0 && onSegment(p1x, p1y, p2x, p2y, q1x, q1y)) { return true; } // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 === 0 && onSegment(p1x, p1y, q2x, q2y, q1x, q1y)) { return true; } // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 === 0 && onSegment(p2x, p2y, p1x, p1y, q2x, q2y)) { return true; } // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 === 0 && onSegment(p2x, p2y, q1x, q1y, q2x, q2y)) { return true; } return false; // Doesn't fall in any of the above cases }, isWithinPolygon = function isWithinPolygon(x, y, cx, cy, r, sides, startAngle) { var i, extreme = Infinity, angle, count = 0, p1x, p2x, p2y, p1y, inangle, inside = false; if (isWithinCircle(x, y, cx, cy, r) && sides >= 3) { angle = startAngle === UNDEF ? mathPI * 0.5 : rad(startAngle); inangle = 2 * mathPI / sides; p1x = cx + r * mathCos(-angle); p1y = cy + r * mathSin(-angle); for (i = 0; i < sides; i++) { angle += inangle; p2x = cx + r * mathCos(-angle); p2y = cy + r * mathSin(-angle); if (doIntersect(p1x, p1y, p2x, p2y, x, y, extreme, y)) { if (orientation(p1x, p1y, x, y, p2x, p2y) === 0) { return onSegment(p1x, p1y, x, y, p2x, p2y); } count++; } p1x = p2x; p1y = p2y; } inside = count % 2 !== 0; } return inside; }, /* * If two points are very closely spreaded, the point that was parsed later is given preference and returned hence. * This is important when two plots are very near, the tooltip and hover effects of the one that comes avobe is being displayed * @param p1 {Object} - The first point being compared. * @param p2 {Object} - The second point being compared in close vicinity of the first point (p1). * @return {Object} - The point that occurs later in the JSON data gets the preference. */ _compair2closest = function _compair2closest(p1, p2) { if (!p1 || p1 && p2 && p2.i > p1.i) { return p2; } return p1; }; function kdTreeAbs(arr) { 'use strict'; // Max radius will be tolerance var tolerance = arr && arr[0] && arr[0].r || 5, i, max = Math.max, floor = Math.floor, sqrt = Math.sqrt, min = Math.min, log = Math.log, exp = Math.exp, pow = Math.pow, _quickselectX, _quickselectY; function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } _quickselectX = function quickselectX(arr, k, left, right) { var n, m, z, s, sd, newLeft, newRight, t, i, j; while (right > left) { if (right - left > 600) { n = right - left + 1; m = k - left + 1; z = log(n); s = 0.5 * exp(2 * z / 3); sd = 0.5 * sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); newLeft = max(left, floor(k - m * s / n + sd)); newRight = min(right, floor(k + (n - m) * s / n + sd)); _quickselectX(arr, k, newLeft, newRight); } t = arr[k]; i = left; j = right; swap(arr, left, k); if (arr[right].x > t.x) { swap(arr, left, right); } while (i < j) { swap(arr, i, j); i++; j--; while (arr[i].x < t.x) { i++; } while (arr[j].x > t.x) { j--; } } if (arr[left].x === t.x) { swap(arr, left, j); } else { j++; swap(arr, j, right); } if (j <= k) { left = j + 1; } if (k <= j) { right = j - 1; } } }; _quickselectY = function quickselectY(arr, k, left, right) { var n, m, z, s, sd, newLeft, newRight, t, i, j; while (right > left) { if (right - left > 600) { n = right - left + 1; m = k - left + 1; z = log(n); s = 0.5 * exp(2 * z / 3); sd = 0.5 * sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); newLeft = max(left, floor(k - m * s / n + sd)); newRight = min(right, floor(k + (n - m) * s / n + sd)); _quickselectY(arr, k, newLeft, newRight); } t = arr[k]; i = left; j = right; swap(arr, left, k); if (arr[right].y > t.y) { swap(arr, left, right); } while (i < j) { swap(arr, i, j); i++; j--; while (arr[i].y < t.y) { i++; } while (arr[j].y > t.y) { j--; } } if (arr[left].y === t.y) { swap(arr, left, j); } else { j++; swap(arr, j, right); } if (j <= k) { left = j + 1; } if (k <= j) { right = j - 1; } } }; arr = arr || []; // Find tolerance as the max radius // of the element for (i = arr.length; i--;) { if (arr[i].r > tolerance) { tolerance = arr[i].r; } // Setting the index arr[i].i = i; arr[i].x = +arr[i].x; arr[i].y = +arr[i].y; } // KdTree Definition below function buildKdTree(arr, left, right, isY) { var ob = {}, mid, access = isY ? 'y' : 'x'; if (left === right) { ob.point = arr[left]; return ob; } if (right - left === 1) { if (arr[left][access] > arr[right][access]) { ob.point = arr[left]; ob.left = { point: arr[right] }; } else { ob.point = arr[right]; ob.left = { point: arr[left] }; } return ob; } mid = left + right >> 1; if (isY) { _quickselectY(arr, mid, left, right); } else { _quickselectX(arr, mid, left, right); } ob.point = arr[mid]; ob.left = buildKdTree(arr, left, mid - 1, !isY); ob.right = buildKdTree(arr, mid + 1, right, !isY); return ob; } return { tree: arr.length === 0 ? {} : buildKdTree(arr, 0, arr.length - 1, false), search: function search(x, y, type, options) { // Actual search logic var tree = this.tree, res, x1 = x - tolerance, x2 = x + tolerance, y1 = y - tolerance, y2 = y + tolerance, lastHovered = false, lastDist = 0, searchX, searchY; options = options || {}; // Calculate distance between two points function calcDist(x, y, p, q) { return sqrt(pow(x - p, 2) + pow(y - q, 2)); } // Check a point is in range w.r.t // to given range function inRange(a, b) { if (type === 'circle') { return calcDist(a, b, x, y) <= x1; } return a >= x1 && a <= x2 && b >= y1 && b <= y2; } function inRangeApply(a, r1, r2) { return a >= r1 && a <= r2; } // Helper function for search // to apply data if found function apply(ob) { var currentHovered = inRangeApply(x, ob.x1, ob.x2) && inRangeApply(y, ob.y1, ob.y2), currentDist = calcDist(x, y, ob.point.x, ob.point.y); if (!res) { res = ob; lastHovered = currentHovered; lastDist = currentDist; return; } if (currentHovered) { if (lastHovered) { if (ob.point.i > res.point.i) { res = ob; lastHovered = currentHovered; lastDist = currentDist; } } else { res = ob; lastHovered = currentHovered; lastDist = currentDist; } } else { if (!lastHovered) { if (currentDist < lastDist) { res = ob; lastHovered = currentHovered; lastDist = currentDist; } } } } function defineSearchArea(rx, ry) { if (type === 'circle') { // Defining box again x1 = rx; } else { x1 = x - rx || 0; x2 = x + rx || 0; y1 = y - ry || 0; y2 = y + ry || 0; } } // X and Y searching different for // maintaing performance searchY = function searchY(ob) { var rx, ry; // Not found if (!ob || !ob.point) { return; } rx = options.rx || ob.point.r; ry = options.ry || ob.point.r; // defining search area defineSearchArea(rx, ry); // If match found return if (inRange(ob.point.x, ob.point.y)) { apply(ob); } // If smaller x1 go left if (y1 <= ob.point.y) { searchX(ob.left); } // If bigger x2 goto right if (y2 >= ob.point.y) { searchX(ob.right); } }; searchX = function searchX(ob) { var rx, ry; // Not found if (!ob || !ob.point) { return; } rx = options.rx || ob.point.r; ry = options.ry || ob.point.r; // defining search area defineSearchArea(rx, ry); // If match found return if (inRange(ob.point.x, ob.point.y)) { apply(ob); } // If smaller x1 go left if (x1 <= ob.point.x) { searchY(ob.left); } // If bigger x2 goto right if (x2 >= ob.point.x) { searchY(ob.right); } }; searchX(tree); // Return point otherwise UNDEF value return res && res.point || res; } }; } /* * The entire data of the dataset is converted to a tree like structure(namely kdTree). * This is very useful to traverse and extract details(e.g. for a tooltip) from a million array elements especially * to extract information of the hovered plot on each mouseMove. * @constructor */ var KdTree = function () { function KdTree(shape) { _classCallCheck(this, KdTree); var kdTreeObj = this; kdTreeObj.configure(shape); } KdTree.prototype.configure = function configure(shape) { var kdTreeObj = this; kdTreeObj.validatorFn = shape ? kdTreeObj.shapeValidator() : kdTreeObj.defaultValidator(); }; /* * Check Function: To determine if the mouseMove Point and the point to be searched are within limits * @param mousePoint {Object} - point extracted from the mouseMove. * @return {Function} - Returns if the setElem is in limit wrt the mouseMoved point. */ KdTree.prototype.defaultValidator = function defaultValidator() { var kdTreeObj = this; return function (setElem) { var mousePoint = kdTreeObj.mousePoint; // Refer to the 2-D distance formula for two points // @returns {Boolean} - If the calculated distances are within the limits. return !!(setElem && Math.pow((setElem.x - mousePoint.x) / kdTreeObj.xLimit, 2) + Math.pow((setElem.y - mousePoint.y) / kdTreeObj.yLimit, 2) <= 1); }; }; KdTree.prototype.shapeValidator = function shapeValidator() { var kdTreeObj = this; return function (setElem) { var mousePoint = kdTreeObj.mousePoint, shapeInfo = setElem && setElem.shapeInfo, inside = false, type, innerradius, r, x = mousePoint.x, y = mousePoint.y, sides, startAngle, x1, x2, y1, y2; type = shapeInfo && shapeInfo.type; switch (type) { case 'circle': r = shapeInfo.radius; inside = isWithinCircle(x, y, setElem.x, setElem.y, r); break; case 'arc': innerradius = shapeInfo.innerradius; r = shapeInfo.radius; inside = !isWithinCircle(x, y, setElem.x, setElem.y, innerradius) && isWithinCircle(x, y, setElem.x, setElem.y, r); break; case 'polygon': r = shapeInfo.radius; startAngle = shapeInfo.startAngle; sides = shapeInfo.sides; inside = isWithinPolygon(x, y, setElem.x, setElem.y, r, sides, startAngle); break; case 'rect': case 'rectangle': x1 = setElem.x; y1 = setElem.y; x2 = x1 + (shapeInfo.width || 0); y2 = y1 + (shapeInfo.height || 0); inside = x >= x1 && x <= x2 && y >= y1 && y <= y2; break; case 'default': inside = false; break; } return inside; }; }; /* * Builds the tree structure from the data points provided. * @param points {Array} - The set level elements belonging to a particular dataset * Updates the tree structure in the tree property of the current instance. */ KdTree.prototype.buildKdTree = function buildKdTree(points) { /* * _buildKdTree is for the internal use to build the tree recursively. * @param points {Array} - The set level elements. * @param isX {Boolean} - isX determines the sorting order. Initially setting the isX = false ensures that * the initial sorting order of the array is w.r.t to y - axis */ this.kdTree = kdTreeAbs(points); this.tree = this.kdTree.tree; return this; }; /* * Returns the nearest point to the point given. * @param point {Object} - the point of reference in whose neighbour the point required is to be returned * @return {Object} - The neighbouring point w.r.t to the point is hunted and returned once within limits */ KdTree.prototype.getNeighbour = function getNeighbour(point, basicSearch, type) { var kDTreeObj = this, // Instance of the kdTree class specific to indivual dataset instance. tree = kDTreeObj.tree, // refer to the created tree like structure for that dataset instance. // limitBox - set the limiting boundaries for the neighbour hunt of the given point. limitBox = { x1: point.x - kDTreeObj.xLimit, x2: point.x + kDTreeObj.xLimit, y1: point.y - kDTreeObj.yLimit, y2: point.y + kDTreeObj.yLimit }, // function specific to a paricular point that retruns Boolean if the neighbour searched is within limits validatorFn = kDTreeObj.validatorFn; kDTreeObj.mousePoint = point; // If basic search is on will use the search function from the // abstract implementation of kdTree if (basicSearch) { return this.kdTree && this.kdTree.search(point.x, point.y, type, point.options); } // When the renderring turns heavy, probably then the tree is not yet build. // Proceed further only if the tree exists. if (tree) { // search the nearest points within limits and return it. return kDTreeObj._searchBtwnLimit(limitBox, tree, true, validatorFn); } }; /* * Search and return the nearest neighbouring point in the pre defined limits. * @param limitBox {Object} - Boundary conditions for the tolerance for the neighbourhood search. * @param tree {Object} - The tree within which the point is needed to be searched, * @param isX {Boolean} - Flag representative of the axis. This gets swapped everytime the function is called recursively * @param validatorFn {Function} - Returns if the point is within the limits. * @return returnPoint {Object} - neighbouring point. */ KdTree.prototype._searchBtwnLimit = function _searchBtwnLimit(limitBox, tree, isX, validatorFn) { var point, returnPoint, kdTreeObj = this, axis = isX ? 'x' : 'y', // get the lower and upper limits in accordance to the axis being referenced. lowerLimit = isX ? limitBox.x1 : limitBox.y1, upperLimit = isX ? limitBox.x2 : limitBox.y2; // Proceed further only when tree is defined point = tree && tree.point && tree.point[axis]; if (point === UNDEF) { return; } // point1 is within limit; if (validatorFn(tree.point)) { // In case of two closely spaced points, they are chosen preferably using _compair2closest() returnPoint = tree.point; } // search the left side if required if (point >= lowerLimit && tree.left) { // if left is available then search on left returnPoint = _compair2closest(returnPoint, kdTreeObj._searchBtwnLimit(limitBox, tree.left, !isX, validatorFn)); } // search the right side if required if (point <= upperLimit && tree.right) { // if left is available then search on left returnPoint = _compair2closest(returnPoint, kdTreeObj._searchBtwnLimit(limitBox, tree.right, !isX, validatorFn)); } return returnPoint; }; /* * Sets the tolerance limit for kdTree search after every zoom level * @param xLimit {Number} - The limiting tolerance in the x-axis * @param yLimit {Number} - The limiting tolerance in the y-axis */ KdTree.prototype._setSearchLimit = function _setSearchLimit(xLimit, yLimit) { var kdTree = this; // sets the x and y limits. kdTree.xLimit = xLimit; kdTree.yLimit = yLimit; }; return KdTree; }(); // reset the constructor KdTree.prototype.constructor = KdTree; exports['default'] = KdTree; /***/ }), /* 540 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _index = __webpack_require__(452); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { '*.dataset.scatter': _index2['default']['*.dataset.line'] }; /***/ }), /* 541 */, /* 542 */, /* 543 */, /* 544 */, /* 545 */, /* 546 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports._checkInvalidSpecificData = undefined; var _mscartesian = __webpack_require__(459); var _mscartesian2 = _interopRequireDefault(_mscartesian); var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _cartesianStack = __webpack_require__(525); var _cartesianStack2 = _interopRequireDefault(_cartesianStack); var _msstackedcolumnDataset = __webpack_require__(547); var _msstackedcolumnDataset2 = _interopRequireDefault(_msstackedcolumnDataset); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ var __checkInvalidSpecificData = function __checkInvalidSpecificData() { var jsonData = this.getFromEnv('dataSource'), datasetsJSON = jsonData.dataset, categories = jsonData.categories, i = void 0; if (!datasetsJSON || !categories) { return true; } if (i = datasetsJSON.length) { while (i--) { if (!datasetsJSON[i].dataset) { return true; } } } }; var MSStackedColumn2D = function (_MSCartesian) { _inherits(MSStackedColumn2D, _MSCartesian); /** * constructor fn */ function MSStackedColumn2D() { _classCallCheck(this, MSStackedColumn2D); var _this = _possibleConstructorReturn(this, _MSCartesian.call(this)); _this.registerFactory('dataset', _msstackedcolumnDataset2['default'], ['vCanvas']); return _this; } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSStackedColumn2D.getName = function getName() { return 'MSStackedColumn2D'; }; /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ MSStackedColumn2D.prototype._checkInvalidSpecificData = function _checkInvalidSpecificData() { return __checkInvalidSpecificData.call(this); }; /** * Sets the name of the component * @return {string} name */ MSStackedColumn2D.prototype.getName = function getName() { return 'MSStackedColumn2D'; }; MSStackedColumn2D.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSCartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Multi-series Stacked Column Chart'; config.defaultDatasetType = 'column'; config.isstacked = true; config.enablemousetracking = true; }; /** * This method return the dataset definations for this charts * @return {Object} return column dataset */ MSStackedColumn2D.prototype.getDSdef = function getDSdef() { return _column2['default']; }; /** This method return the dataset-group definations for this charts **/ MSStackedColumn2D.prototype.getDSGroupdef = function getDSGroupdef() { return _cartesianStack2['default']; }; return MSStackedColumn2D; }(_mscartesian2['default']); exports['default'] = MSStackedColumn2D; exports._checkInvalidSpecificData = __checkInvalidSpecificData; /***/ }), /* 547 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var jsonData = chart.getFromEnv('dataSource'), pDatasetsJSON = jsonData.dataset, pLength = pDatasetsJSON && pDatasetsJSON.length, i = void 0, length = void 0, prevLength = 0, datasetsJSON = void 0, canvas = chart.getChildren('canvas')[0], vCanvas = canvas.getChildren('vCanvas')[0], indices = void 0, stackGroups = void 0, stackConf = [], stackGroupParent = void 0; if (!pDatasetsJSON) { chart.setChartMessage(); return; } (0, _lib.componentFactory)(vCanvas, _columnMultiseries2['default'], 'multiSeriesGroup_column'); stackGroupParent = vCanvas.getChildren('multiSeriesGroup_column')[0]; for (i = 0; i < pLength; i++) { stackConf.push(pDatasetsJSON[i].dataset); } (0, _lib.componentFactory)(stackGroupParent, chart.getDSGroupdef(), 'stackedGroup_column', pLength, stackConf); stackGroups = stackGroupParent.getChildren('stackedGroup_column'); for (i = 0; i < stackGroups.length; i++) { if (stackGroups[i].getState('removed') !== true) { datasetsJSON = pDatasetsJSON[i].dataset; if (!datasetsJSON) { chart.setChartMessage(); return; } length = datasetsJSON && datasetsJSON.length; indices = Array(length).fill(i * prevLength).map(function (n, j) { return n + j; }); (0, _lib.datasetFactory)(stackGroups[i], chart.getDSdef(), 'dataset_column', length, datasetsJSON, indices); prevLength = length; } } chart.config._lastDatasetIndex = indices[indices.length - 1]; }; var _lib = __webpack_require__(125); var _columnMultiseries = __webpack_require__(516); var _columnMultiseries2 = _interopRequireDefault(_columnMultiseries); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /***/ }), /* 548 */, /* 549 */, /* 550 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _area = __webpack_require__(450); var _area2 = _interopRequireDefault(_area); var _areabase = __webpack_require__(551); var _areabase2 = _interopRequireDefault(_areabase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ /** * Class for MSArea chart * @class MSArea * @extends {AreaBase} */ var MSArea = function (_AreaBase) { _inherits(MSArea, _AreaBase); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSArea.getName = function getName() { return 'MSArea'; }; /** Constructor method of Class MSArea to initialise values **/ function MSArea() { _classCallCheck(this, MSArea); var _this = _possibleConstructorReturn(this, _AreaBase.call(this)); _this.defaultPlotShadow = 0; return _this; } /** * Sets the name of the component * @return {string} name */ MSArea.prototype.getName = function getName() { return 'MSArea'; }; /** This method return the dataset definations for this chart * @return {Object} dataset * **/ MSArea.prototype.getDSdef = function getDSdef() { return _area2['default']; }; /** This method return the dataset-group definations for this chart * @return {undefined} **/ MSArea.prototype.getDSGroupdef = function getDSGroupdef() { return undefined; }; /** * Sets default configuration * @memberof MSArea */ MSArea.prototype.__setDefaultConfig = function __setDefaultConfig() { _AreaBase.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Multi-series Area Chart'; config.defaultDatasetType = 'area'; config.defaultcrosslinethickness = 1; }; return MSArea; }(_areabase2['default']); exports['default'] = MSArea; /***/ }), /* 551 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports._setDefaultConfig = undefined; var _mscolumn2d = __webpack_require__(518); var _mscolumn2d2 = _interopRequireDefault(_mscolumn2d); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var UNDEF = void 0, SEVENTYSTRING = _lib.preDefStr.SEVENTYSTRING, _setDefaultConfig = function _setDefaultConfig() { var config = this.config; // Anchor related attributes config.anchorborderthickness = 1; config.anchorimageurl = UNDEF; config.anchorimagepadding = 1; config.anchorsides = 1; config.anchoralpha = UNDEF; config.anchorbgalpha = _lib.HUNDREDSTRING; config.anchorimagealpha = _lib.HUNDREDSTRING; config.anchorimagescale = 100; config.anchorstartangle = 90; config.anchorshadow = 0; config.anchorbgcolor = UNDEF; config.anchorbordercolor = UNDEF; config.anchorradius = 3; config.showvalues = 1; config.plotfillalpha = SEVENTYSTRING; config.linedashlen = 5; config.linedashgap = 4; config.linedashed = UNDEF; config.linealpha = _lib.HUNDREDSTRING; config.linethickness = 2; config.drawfullareaborder = 1; config.connectnulldata = 0; }; /** * Base class for area chart. */ var AreaBase = function (_MSColumn2D) { _inherits(AreaBase, _MSColumn2D); function AreaBase() { _classCallCheck(this, AreaBase); return _possibleConstructorReturn(this, _MSColumn2D.apply(this, arguments)); } /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ AreaBase.getName = function getName() { return 'AreaBase'; }; /** * Parsing default chart configurations */ AreaBase.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSColumn2D.prototype.__setDefaultConfig.call(this); _setDefaultConfig.call(this); }; return AreaBase; }(_mscolumn2d2['default']); exports['default'] = AreaBase; exports._setDefaultConfig = _setDefaultConfig; /***/ }), /* 552 */, /* 553 */, /* 554 */, /* 555 */, /* 556 */, /* 557 */, /* 558 */, /* 559 */, /* 560 */, /* 561 */, /* 562 */, /* 563 */, /* 564 */, /* 565 */, /* 566 */, /* 567 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _msdybasecartesian = __webpack_require__(495); var _msdybasecartesian2 = _interopRequireDefault(_msdybasecartesian); var _msstackedcolumn2d = __webpack_require__(546); var _line = __webpack_require__(449); var _line2 = _interopRequireDefault(_line); var _column = __webpack_require__(432); var _column2 = _interopRequireDefault(_column); var _cartesianStack = __webpack_require__(525); var _cartesianStack2 = _interopRequireDefault(_cartesianStack); var _msstackedcolumnLineDataset = __webpack_require__(568); var _msstackedcolumnLineDataset2 = _interopRequireDefault(_msstackedcolumnLineDataset); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, SEVENTYSTRING = _lib.preDefStr.SEVENTYSTRING; var MSStackedColumn2DLineDy = function (_MSDyBaseCartesian) { _inherits(MSStackedColumn2DLineDy, _MSDyBaseCartesian); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSStackedColumn2DLineDy.getName = function getName() { return 'MSStackedColumn2DLineDy'; }; function MSStackedColumn2DLineDy() { _classCallCheck(this, MSStackedColumn2DLineDy); var _this = _possibleConstructorReturn(this, _MSDyBaseCartesian.call(this)); _this.stack100percent = 0; _this.hasLineSet = true; _this.lineset = true; _this.registerFactory('dataset', _msstackedcolumnLineDataset2['default'], ['vCanvas']); return _this; } /** * Sets the name of the component * @return {string} name */ MSStackedColumn2DLineDy.prototype.getName = function getName() { return 'MSStackedColumn2DLineDy'; }; MSStackedColumn2DLineDy.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSDyBaseCartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.sDefaultDatasetType = 'line'; config.friendlyName = 'Multi-series Dual Y-Axis Stacked Column and Line Chart'; config.defaultDatasetType = 'column'; config.isdual = true; config.haslineset = true; config.isstacked = true; config.enablemousetracking = true; // Anchor related attributes config.anchorborderthickness = 1; config.anchorimageurl = UNDEF; config.anchorimagepadding = 1; config.anchorsides = 1; config.anchoralpha = UNDEF; config.anchorbgalpha = _lib.HUNDREDSTRING; config.anchorimagealpha = _lib.HUNDREDSTRING; config.anchorimagescale = 100; config.anchorstartangle = 90; config.anchorshadow = 0; config.anchorbgcolor = UNDEF; config.anchorbordercolor = UNDEF; config.anchorradius = 3; config.showvalues = 1; config.plotfillalpha = SEVENTYSTRING; config.linedashlen = 5; config.linedashgap = 4; config.linedashed = UNDEF; config.linealpha = _lib.HUNDREDSTRING; config.linethickness = 2; config.drawfullareaborder = 1; config.connectnulldata = 0; }; /** * function to check if the chart specific data is proper is not * this fn is define for specific chart types * @return {boolean} if JSON data is valid or not */ MSStackedColumn2DLineDy.prototype._checkInvalidSpecificData = function _checkInvalidSpecificData() { return _msstackedcolumn2d._checkInvalidSpecificData.call(this); }; MSStackedColumn2DLineDy.prototype.getDSdef = function getDSdef(name) { return name === 'line' ? _line2['default'] : _column2['default']; }; MSStackedColumn2DLineDy.prototype.getDSGroupdef = function getDSGroupdef() { return _cartesianStack2['default']; }; return MSStackedColumn2DLineDy; }(_msdybasecartesian2['default']); exports['default'] = MSStackedColumn2DLineDy; /***/ }), /* 568 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { var jsonData = chart.getFromEnv('dataSource'), dataset = jsonData.dataset, lineSets = jsonData.lineset, linesetStartIndex = void 0, indices = void 0, canvas = chart.getChildren('canvas')[0], vCanvas = canvas.getChildren('vCanvas')[1]; if (!dataset && lineSets.length === 0) { chart.setChartMessage(); return; } (0, _msstackedcolumnDataset2['default'])(chart); linesetStartIndex = chart.config._lastDatasetIndex + 1; if (lineSets && lineSets.length) { indices = Array(lineSets.length).fill(linesetStartIndex).map(function (n, j) { return n + j; }); (0, _lib.datasetFactory)(vCanvas, chart.getDSdef('line'), 'dataset_line', lineSets.length, lineSets, indices); } else { removeLineSet(vCanvas); } }; var _msstackedcolumnDataset = __webpack_require__(547); var _msstackedcolumnDataset2 = _interopRequireDefault(_msstackedcolumnDataset); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var removeLineSet = function removeLineSet(component) { var lineSet = component.getChildren('dataset_line'), i = void 0; for (i = lineSet && lineSet.length - 1; i > -1; i--) { lineSet[i].remove(); } }; /** * function to create dataset, groupmaneger. * assign dataset to group manager. * @param {Object} chart Chart API **/ /***/ }), /* 569 */, /* 570 */, /* 571 */, /* 572 */, /* 573 */, /* 574 */, /* 575 */, /* 576 */, /* 577 */, /* 578 */, /* 579 */, /* 580 */, /* 581 */, /* 582 */, /* 583 */, /* 584 */, /* 585 */, /* 586 */, /* 587 */, /* 588 */, /* 589 */, /* 590 */, /* 591 */, /* 592 */, /* 593 */, /* 594 */, /* 595 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _areabase = __webpack_require__(551); var _areabase2 = _interopRequireDefault(_areabase); var _line = __webpack_require__(449); var _line2 = _interopRequireDefault(_line); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0; var MSLine = function (_AreaBase) { _inherits(MSLine, _AreaBase); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSLine.getName = function getName() { return 'MSLine'; }; function MSLine() { _classCallCheck(this, MSLine); var _this = _possibleConstructorReturn(this, _AreaBase.call(this)); _this.defaultPlotShadow = 1; _this.axisPaddingLeft = 0; _this.axisPaddingRight = 0; return _this; } /** * Sets the name of the component * @return {string} name */ MSLine.prototype.getName = function getName() { return 'MSLine'; }; MSLine.prototype.__setDefaultConfig = function __setDefaultConfig() { _AreaBase.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Multi-series Line Chart'; config.defaultDatasetType = 'line'; config.zeroplanethickness = 1; config.zeroplanealpha = 40; config.showzeroplaneontop = 0; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; }; // This method return the dataset definations for this charts MSLine.prototype.getDSdef = function getDSdef() { return _line2['default']; }; // This method return the dataset-group definations for this charts MSLine.prototype.getDSGroupdef = function getDSGroupdef() { return UNDEF; }; return MSLine; }(_areabase2['default']); exports['default'] = MSLine; /***/ }), /* 596 */, /* 597 */, /* 598 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _spline = __webpack_require__(599); var _spline2 = _interopRequireDefault(_spline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _spline2['default']; /***/ }), /* 599 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _spline = __webpack_require__(600); var _spline2 = _interopRequireDefault(_spline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _spline2['default']; /***/ }), /* 600 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _areabase = __webpack_require__(551); var _msspline = __webpack_require__(514); var _msspline2 = _interopRequireDefault(_msspline); var _sscartesian = __webpack_require__(359); var _sscartesian2 = _interopRequireDefault(_sscartesian); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var Spline = function (_SSCartesian) { _inherits(Spline, _SSCartesian); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ Spline.getName = function getName() { return 'Spline'; }; function Spline() { _classCallCheck(this, Spline); var _this = _possibleConstructorReturn(this, _SSCartesian.call(this)); _this.defaultPlotShadow = 1; return _this; } /** * Sets the name of the component * @return {string} name */ Spline.prototype.getName = function getName() { return 'Spline'; }; /** * parse defualt configuration of the chart */ Spline.prototype.__setDefaultConfig = function __setDefaultConfig() { _SSCartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Spline Chart'; config.singleseries = true; config.defaultDatasetType = 'msspline'; config.minimizetendency = 0; config.zeroplanethickness = 1; config.zeroplanealpha = 40; config.showzeroplaneontop = 0; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; _areabase._setDefaultConfig.call(this); }; Spline.prototype.getDSdef = function getDSdef() { return _msspline2['default']; }; return Spline; }(_sscartesian2['default']); exports['default'] = Spline; /***/ }), /* 601 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _splinearea = __webpack_require__(602); var _splinearea2 = _interopRequireDefault(_splinearea); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _splinearea2['default']; /***/ }), /* 602 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _spline = __webpack_require__(600); var _spline2 = _interopRequireDefault(_spline); var _areabase = __webpack_require__(551); var _mssplinearea = __webpack_require__(510); var _mssplinearea2 = _interopRequireDefault(_mssplinearea); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var SplineArea = function (_Spline) { _inherits(SplineArea, _Spline); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ SplineArea.getName = function getName() { return 'SplineArea'; }; function SplineArea() { _classCallCheck(this, SplineArea); var _this = _possibleConstructorReturn(this, _Spline.call(this)); _this.defaultPlotShadow = 0; return _this; } /** * Sets the name of the component * @return {string} name */ SplineArea.prototype.getName = function getName() { return 'SplineArea'; }; /** * parse defualt configuration of the chart */ SplineArea.prototype.__setDefaultConfig = function __setDefaultConfig() { _Spline.prototype.__setDefaultConfig.call(this); var config = this.config; _areabase._setDefaultConfig.call(this); config.friendlyName = 'Spline Area Chart'; config.singleseries = true; config.hasLegend = false; config.defaultDatasetType = 'mssplinearea'; config.anchoralpha = '100'; config.minimizetendency = 0; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; config.showzeroplaneontop = 1; }; SplineArea.prototype.getDSdef = function getDSdef() { return _mssplinearea2['default']; }; SplineArea.prototype.getDSGroupdef = function getDSGroupdef() { // this fn overrides }; return SplineArea; }(_spline2['default']); exports['default'] = SplineArea; /***/ }), /* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _msspline = __webpack_require__(604); var _msspline2 = _interopRequireDefault(_msspline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _msspline2['default']; /***/ }), /* 604 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _msspline = __webpack_require__(605); var _msspline2 = _interopRequireDefault(_msspline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _msspline2['default']; /***/ }), /* 605 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _areabase = __webpack_require__(551); var _msspline = __webpack_require__(514); var _msspline2 = _interopRequireDefault(_msspline); var _mscartesian = __webpack_require__(459); var _mscartesian2 = _interopRequireDefault(_mscartesian); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var MSSpline = function (_MSCartesian) { _inherits(MSSpline, _MSCartesian); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSSpline.getName = function getName() { return 'MSSpline'; }; function MSSpline() { _classCallCheck(this, MSSpline); var _this = _possibleConstructorReturn(this, _MSCartesian.call(this)); _this.defaultPlotShadow = 1; return _this; } /** * Sets the name of the component * @return {string} name */ MSSpline.prototype.getName = function getName() { return 'MSSpline'; }; /** * parse defualt configuration of the chart */ MSSpline.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSCartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Multi-series Spline Chart'; config.defaultDatasetType = 'msspline'; config.minimizetendency = 0; config.zeroplanethickness = 1; config.zeroplanealpha = 40; config.showzeroplaneontop = 0; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; _areabase._setDefaultConfig.call(this); }; MSSpline.prototype.getDSdef = function getDSdef() { return _msspline2['default']; }; MSSpline.prototype.getDSGroupdef = function getDSGroupdef() { // this fn overrides }; return MSSpline; }(_mscartesian2['default']); exports['default'] = MSSpline; /***/ }), /* 606 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _mssplinedy = __webpack_require__(607); var _mssplinedy2 = _interopRequireDefault(_mssplinedy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _mssplinedy2['default']; /***/ }), /* 607 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _areabase = __webpack_require__(551); var _msdybasecartesian = __webpack_require__(495); var _msdybasecartesian2 = _interopRequireDefault(_msdybasecartesian); var _msspline = __webpack_require__(514); var _msspline2 = _interopRequireDefault(_msspline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var MSSplineDy = function (_MSDyBaseCartesian) { _inherits(MSSplineDy, _MSDyBaseCartesian); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSSplineDy.getName = function getName() { return 'MSSplineDy'; }; function MSSplineDy() { _classCallCheck(this, MSSplineDy); var _this = _possibleConstructorReturn(this, _MSDyBaseCartesian.call(this)); _this.isDual = true; return _this; } /** * Sets the name of the component * @return {string} name */ MSSplineDy.prototype.getName = function getName() { return 'MSSplineDy'; }; /** * parse defualt configuration of the chart */ MSSplineDy.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSDyBaseCartesian.prototype.__setDefaultConfig.call(this); var config = this.config; config.friendlyName = 'Multi-series Dual Y-Axis Spline Chart'; config.defaultDatasetType = 'msspline'; config.minimizetendency = 0; config.zeroplanethickness = 1; config.zeroplanealpha = 40; config.showzeroplaneontop = 0; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; config.isdual = true; _areabase._setDefaultConfig.call(this); }; MSSplineDy.prototype.getDSdef = function getDSdef() { return _msspline2['default']; }; MSSplineDy.prototype.getDSGroupdef = function getDSGroupdef() {} // this fn overrides /** * function to return dataset type applicable for this chart * @param {string} name dataset type * @return {string} dataset type applicable for this chart */ ; MSSplineDy.prototype.getDSType = function getDSType() { return 'spline'; }; return MSSplineDy; }(_msdybasecartesian2['default']); exports['default'] = MSSplineDy; /***/ }), /* 608 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _mssplinearea = __webpack_require__(609); var _mssplinearea2 = _interopRequireDefault(_mssplinearea); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _mssplinearea2['default']; /***/ }), /* 609 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _msspline = __webpack_require__(605); var _msspline2 = _interopRequireDefault(_msspline); var _areabase = __webpack_require__(551); var _mssplinearea = __webpack_require__(510); var _mssplinearea2 = _interopRequireDefault(_mssplinearea); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var MSSplineArea = function (_MSSpline) { _inherits(MSSplineArea, _MSSpline); /** * Provides the name of the chart extension * * @static * @return {string} The name of the chart extension */ MSSplineArea.getName = function getName() { return 'MSSplineArea'; }; function MSSplineArea() { _classCallCheck(this, MSSplineArea); var _this = _possibleConstructorReturn(this, _MSSpline.call(this)); _this.friendlyName = 'Multi-series Spline Area Chart'; _this.defaultPlotShadow = 0; return _this; } /** * Sets the name of the component * @return {string} name */ MSSplineArea.prototype.getName = function getName() { return 'MSSplineArea'; }; /** * parse defualt configuration of the chart */ MSSplineArea.prototype.__setDefaultConfig = function __setDefaultConfig() { _MSSpline.prototype.__setDefaultConfig.call(this); var config = this.config; _areabase._setDefaultConfig.call(this); config.defaultDatasetType = 'mssplinearea'; config.minimizetendency = 0; config.zeroplanethickness = 2; config.zeroplanealpha = 80; config.showzeroplaneontop = 1; config.enablemousetracking = true; config.defaultcrosslinethickness = 1; }; MSSplineArea.prototype.getDSdef = function getDSdef() { return _mssplinearea2['default']; }; MSSplineArea.prototype.getDSGroupdef = function getDSGroupdef() { // this fn overrides }; return MSSplineArea; }(_msspline2['default']); exports['default'] = MSSplineArea; /***/ }), /* 610 */, /* 611 */, /* 612 */, /* 613 */, /* 614 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(618); /* harmony import */ var _internal_makeFlat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(621); /* harmony import */ var _internal_xchain__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(624); /* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(632); /** * `chain` maps a function over a list and concatenates the results. `chain` * is also known as `flatMap` in some libraries * * Dispatches to the `chain` method of the second argument, if present, * according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain). * * @func * @memberOf R * @since v0.3.0 * @category List * @sig Chain m => (a -> m b) -> m a -> m b * @param {Function} fn The function to map with * @param {Array} list The list to map over * @return {Array} The result of flat-mapping `list` with `fn` * @example * * var duplicate = n => [n, n]; * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] * * R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1] */ var chain = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/Object(_internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__["default"])(['fantasy-land/chain', 'chain'], _internal_xchain__WEBPACK_IMPORTED_MODULE_3__["default"], function chain(fn, monad) { if (typeof monad === 'function') { return function (x) { return fn(monad(x))(x); }; } return Object(_internal_makeFlat__WEBPACK_IMPORTED_MODULE_2__["default"])(false)(Object(_map__WEBPACK_IMPORTED_MODULE_4__["default"])(fn, monad)); })); /* harmony default export */ __webpack_exports__["default"] = (chain); /***/ }), /* 615 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _curry2; }); /* harmony import */ var _curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /* harmony import */ var _isPlaceholder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(617); /** * Optimized internal two-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curry2(fn) { return function f2(a, b) { switch (arguments.length) { case 0: return f2; case 1: return Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(a) ? f2 : Object(_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function (_b) { return fn(a, _b); }); default: return Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(a) && Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(b) ? f2 : Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(a) ? Object(_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function (_a) { return fn(_a, b); }) : Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(b) ? Object(_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function (_b) { return fn(a, _b); }) : fn(a, b); } }; } /***/ }), /* 616 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _curry1; }); /* harmony import */ var _isPlaceholder__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(617); /** * Optimized internal one-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curry1(fn) { return function f1(a) { if (arguments.length === 0 || Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_0__["default"])(a)) { return f1; } else { return fn.apply(this, arguments); } }; } /***/ }), /* 617 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _isPlaceholder; }); function _isPlaceholder(a) { return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true; } /***/ }), /* 618 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _dispatchable; }); /* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(619); /* harmony import */ var _isTransformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(620); /** * Returns a function that dispatches with different strategies based on the * object in list position (last argument). If it is an array, executes [fn]. * Otherwise, if it has a function with one of the given method names, it will * execute that function (functor case). Otherwise, if it is a transformer, * uses transducer [xf] to return a new transformer (transducer case). * Otherwise, it will default to executing [fn]. * * @private * @param {Array} methodNames properties to check for a custom implementation * @param {Function} xf transducer to initialize if object is transformer * @param {Function} fn default ramda implementation * @return {Function} A function that dispatches on object in list position */ function _dispatchable(methodNames, xf, fn) { return function () { if (arguments.length === 0) { return fn(); } var args = Array.prototype.slice.call(arguments, 0); var obj = args.pop(); if (!Object(_isArray__WEBPACK_IMPORTED_MODULE_0__["default"])(obj)) { var idx = 0; while (idx < methodNames.length) { if (typeof obj[methodNames[idx]] === 'function') { return obj[methodNames[idx]].apply(obj, args); } idx += 1; } if (Object(_isTransformer__WEBPACK_IMPORTED_MODULE_1__["default"])(obj)) { var transducer = xf.apply(null, args); return transducer(obj); } } return fn.apply(this, arguments); }; } /***/ }), /* 619 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Tests whether or not an object is an array. * * @private * @param {*} val The object to test. * @return {Boolean} `true` if `val` is an array, `false` otherwise. * @example * * _isArray([]); //=> true * _isArray(null); //=> false * _isArray({}); //=> false */ /* harmony default export */ __webpack_exports__["default"] = (Array.isArray || function _isArray(val) { return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]'; }); /***/ }), /* 620 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _isTransformer; }); function _isTransformer(obj) { return typeof obj['@@transducer/step'] === 'function'; } /***/ }), /* 621 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _makeFlat; }); /* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(622); /** * `_makeFlat` is a helper function that returns a one-level or fully recursive * function based on the flag passed in. * * @private */ function _makeFlat(recursive) { return function flatt(list) { var value, jlen, j; var result = []; var idx = 0; var ilen = list.length; while (idx < ilen) { if (Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_0__["default"])(list[idx])) { value = recursive ? flatt(list[idx]) : list[idx]; j = 0; jlen = value.length; while (j < jlen) { result[result.length] = value[j]; j += 1; } } else { result[result.length] = list[idx]; } idx += 1; } return result; }; } /***/ }), /* 622 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(619); /* harmony import */ var _isString__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(623); /** * Tests whether or not an object is similar to an array. * * @private * @category Type * @category List * @sig * -> Boolean * @param {*} x The object to test. * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. * @example * * _isArrayLike([]); //=> true * _isArrayLike(true); //=> false * _isArrayLike({}); //=> false * _isArrayLike({length: 10}); //=> false * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true */ var _isArrayLike = /*#__PURE__*/Object(_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function isArrayLike(x) { if (Object(_isArray__WEBPACK_IMPORTED_MODULE_1__["default"])(x)) { return true; } if (!x) { return false; } if (typeof x !== 'object') { return false; } if (Object(_isString__WEBPACK_IMPORTED_MODULE_2__["default"])(x)) { return false; } if (x.nodeType === 1) { return !!x.length; } if (x.length === 0) { return true; } if (x.length > 0) { return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); } return false; }); /* harmony default export */ __webpack_exports__["default"] = (_isArrayLike); /***/ }), /* 623 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _isString; }); function _isString(x) { return Object.prototype.toString.call(x) === '[object String]'; } /***/ }), /* 624 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _flatCat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(625); /* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(632); var _xchain = /*#__PURE__*/Object(_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function _xchain(f, xf) { return Object(_map__WEBPACK_IMPORTED_MODULE_2__["default"])(f, Object(_flatCat__WEBPACK_IMPORTED_MODULE_1__["default"])(xf)); }); /* harmony default export */ __webpack_exports__["default"] = (_xchain); /***/ }), /* 625 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _forceReduced__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(626); /* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(622); /* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(627); /* harmony import */ var _xfBase__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(631); var preservingReduced = function (xf) { return { '@@transducer/init': _xfBase__WEBPACK_IMPORTED_MODULE_3__["default"].init, '@@transducer/result': function (result) { return xf['@@transducer/result'](result); }, '@@transducer/step': function (result, input) { var ret = xf['@@transducer/step'](result, input); return ret['@@transducer/reduced'] ? Object(_forceReduced__WEBPACK_IMPORTED_MODULE_0__["default"])(ret) : ret; } }; }; var _flatCat = function _xcat(xf) { var rxf = preservingReduced(xf); return { '@@transducer/init': _xfBase__WEBPACK_IMPORTED_MODULE_3__["default"].init, '@@transducer/result': function (result) { return rxf['@@transducer/result'](result); }, '@@transducer/step': function (result, input) { return !Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_1__["default"])(input) ? Object(_reduce__WEBPACK_IMPORTED_MODULE_2__["default"])(rxf, result, [input]) : Object(_reduce__WEBPACK_IMPORTED_MODULE_2__["default"])(rxf, result, input); } }; }; /* harmony default export */ __webpack_exports__["default"] = (_flatCat); /***/ }), /* 626 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _forceReduced; }); function _forceReduced(x) { return { '@@transducer/value': x, '@@transducer/reduced': true }; } /***/ }), /* 627 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _reduce; }); /* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(622); /* harmony import */ var _xwrap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(628); /* harmony import */ var _bind__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(629); function _arrayReduce(xf, acc, list) { var idx = 0; var len = list.length; while (idx < len) { acc = xf['@@transducer/step'](acc, list[idx]); if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } idx += 1; } return xf['@@transducer/result'](acc); } function _iterableReduce(xf, acc, iter) { var step = iter.next(); while (!step.done) { acc = xf['@@transducer/step'](acc, step.value); if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } step = iter.next(); } return xf['@@transducer/result'](acc); } function _methodReduce(xf, acc, obj, methodName) { return xf['@@transducer/result'](obj[methodName](Object(_bind__WEBPACK_IMPORTED_MODULE_2__["default"])(xf['@@transducer/step'], xf), acc)); } var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; function _reduce(fn, acc, list) { if (typeof fn === 'function') { fn = Object(_xwrap__WEBPACK_IMPORTED_MODULE_1__["default"])(fn); } if (Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_0__["default"])(list)) { return _arrayReduce(fn, acc, list); } if (typeof list['fantasy-land/reduce'] === 'function') { return _methodReduce(fn, acc, list, 'fantasy-land/reduce'); } if (list[symIterator] != null) { return _iterableReduce(fn, acc, list[symIterator]()); } if (typeof list.next === 'function') { return _iterableReduce(fn, acc, list); } if (typeof list.reduce === 'function') { return _methodReduce(fn, acc, list, 'reduce'); } throw new TypeError('reduce: list must be array or iterable'); } /***/ }), /* 628 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _xwrap; }); var XWrap = /*#__PURE__*/function () { function XWrap(fn) { this.f = fn; } XWrap.prototype['@@transducer/init'] = function () { throw new Error('init not implemented on XWrap'); }; XWrap.prototype['@@transducer/result'] = function (acc) { return acc; }; XWrap.prototype['@@transducer/step'] = function (acc, x) { return this.f(acc, x); }; return XWrap; }(); function _xwrap(fn) { return new XWrap(fn); } /***/ }), /* 629 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_arity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(630); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(615); /** * Creates a function that is bound to a context. * Note: `R.bind` does not provide the additional argument-binding capabilities of * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). * * @func * @memberOf R * @since v0.6.0 * @category Function * @category Object * @sig (* -> *) -> {*} -> (* -> *) * @param {Function} fn The function to bind to context * @param {Object} thisObj The context to bind `fn` to * @return {Function} A function that will execute in the context of `thisObj`. * @see R.partial * @example * * var log = R.bind(console.log, console); * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3} * // logs {a: 2} * @symb R.bind(f, o)(a, b) = f.call(o, a, b) */ var bind = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_1__["default"])(function bind(fn, thisObj) { return Object(_internal_arity__WEBPACK_IMPORTED_MODULE_0__["default"])(fn.length, function () { return fn.apply(thisObj, arguments); }); }); /* harmony default export */ __webpack_exports__["default"] = (bind); /***/ }), /* 630 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _arity; }); function _arity(n, fn) { /* eslint-disable no-unused-vars */ switch (n) { case 0: return function () { return fn.apply(this, arguments); }; case 1: return function (a0) { return fn.apply(this, arguments); }; case 2: return function (a0, a1) { return fn.apply(this, arguments); }; case 3: return function (a0, a1, a2) { return fn.apply(this, arguments); }; case 4: return function (a0, a1, a2, a3) { return fn.apply(this, arguments); }; case 5: return function (a0, a1, a2, a3, a4) { return fn.apply(this, arguments); }; case 6: return function (a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); }; case 7: return function (a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); }; case 8: return function (a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); }; case 9: return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); }; case 10: return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); }; default: throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); } } /***/ }), /* 631 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = ({ init: function () { return this.xf['@@transducer/init'](); }, result: function (result) { return this.xf['@@transducer/result'](result); } }); /***/ }), /* 632 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(618); /* harmony import */ var _internal_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(633); /* harmony import */ var _internal_reduce__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(627); /* harmony import */ var _internal_xmap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(634); /* harmony import */ var _curryN__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(635); /* harmony import */ var _keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(637); /** * Takes a function and * a [functor](https://github.com/fantasyland/fantasy-land#functor), * applies the function to each of the functor's values, and returns * a functor of the same shape. * * Ramda provides suitable `map` implementations for `Array` and `Object`, * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`. * * Dispatches to the `map` method of the second argument, if present. * * Acts as a transducer if a transformer is given in list position. * * Also treats functions as functors and will compose them together. * * @func * @memberOf R * @since v0.1.0 * @category List * @sig Functor f => (a -> b) -> f a -> f b * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @see R.transduce, R.addIndex * @example * * var double = x => x * 2; * * R.map(double, [1, 2, 3]); //=> [2, 4, 6] * * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6} * @symb R.map(f, [a, b]) = [f(a), f(b)] * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) } * @symb R.map(f, functor_o) = functor_o.map(f) */ var map = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/Object(_internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__["default"])(['fantasy-land/map', 'map'], _internal_xmap__WEBPACK_IMPORTED_MODULE_4__["default"], function map(fn, functor) { switch (Object.prototype.toString.call(functor)) { case '[object Function]': return Object(_curryN__WEBPACK_IMPORTED_MODULE_5__["default"])(functor.length, function () { return fn.call(this, functor.apply(this, arguments)); }); case '[object Object]': return Object(_internal_reduce__WEBPACK_IMPORTED_MODULE_3__["default"])(function (acc, key) { acc[key] = fn(functor[key]); return acc; }, {}, Object(_keys__WEBPACK_IMPORTED_MODULE_6__["default"])(functor)); default: return Object(_internal_map__WEBPACK_IMPORTED_MODULE_2__["default"])(fn, functor); } })); /* harmony default export */ __webpack_exports__["default"] = (map); /***/ }), /* 633 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _map; }); function _map(fn, functor) { var idx = 0; var len = functor.length; var result = Array(len); while (idx < len) { result[idx] = fn(functor[idx]); idx += 1; } return result; } /***/ }), /* 634 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _xfBase__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(631); var XMap = /*#__PURE__*/function () { function XMap(f, xf) { this.xf = xf; this.f = f; } XMap.prototype['@@transducer/init'] = _xfBase__WEBPACK_IMPORTED_MODULE_1__["default"].init; XMap.prototype['@@transducer/result'] = _xfBase__WEBPACK_IMPORTED_MODULE_1__["default"].result; XMap.prototype['@@transducer/step'] = function (result, input) { return this.xf['@@transducer/step'](result, this.f(input)); }; return XMap; }(); var _xmap = /*#__PURE__*/Object(_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function _xmap(f, xf) { return new XMap(f, xf); }); /* harmony default export */ __webpack_exports__["default"] = (_xmap); /***/ }), /* 635 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_arity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(630); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(616); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(615); /* harmony import */ var _internal_curryN__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(636); /** * Returns a curried equivalent of the provided function, with the specified * arity. The curried function has two unusual capabilities. First, its * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the * following are equivalent: * * - `g(1)(2)(3)` * - `g(1)(2, 3)` * - `g(1, 2)(3)` * - `g(1, 2, 3)` * * Secondly, the special placeholder value [`R.__`](#__) may be used to specify * "gaps", allowing partial application of any combination of arguments, * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), * the following are equivalent: * * - `g(1, 2, 3)` * - `g(_, 2, 3)(1)` * - `g(_, _, 3)(1)(2)` * - `g(_, _, 3)(1, 2)` * - `g(_, 2)(1)(3)` * - `g(_, 2)(1, 3)` * - `g(_, 2)(_, 3)(1)` * * @func * @memberOf R * @since v0.5.0 * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {Number} length The arity for the returned function. * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curry * @example * * var sumArgs = (...args) => R.sum(args); * * var curriedAddFourNumbers = R.curryN(4, sumArgs); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4); //=> 10 */ var curryN = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_2__["default"])(function curryN(length, fn) { if (length === 1) { return Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_1__["default"])(fn); } return Object(_internal_arity__WEBPACK_IMPORTED_MODULE_0__["default"])(length, Object(_internal_curryN__WEBPACK_IMPORTED_MODULE_3__["default"])(length, [], fn)); }); /* harmony default export */ __webpack_exports__["default"] = (curryN); /***/ }), /* 636 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _curryN; }); /* harmony import */ var _arity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(630); /* harmony import */ var _isPlaceholder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(617); /** * Internal curryN function. * * @private * @category Function * @param {Number} length The arity of the curried function. * @param {Array} received An array of arguments received thus far. * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curryN(length, received, fn) { return function () { var combined = []; var argsIdx = 0; var left = length; var combinedIdx = 0; while (combinedIdx < received.length || argsIdx < arguments.length) { var result; if (combinedIdx < received.length && (!Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(received[combinedIdx]) || argsIdx >= arguments.length)) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; argsIdx += 1; } combined[combinedIdx] = result; if (!Object(_isPlaceholder__WEBPACK_IMPORTED_MODULE_1__["default"])(result)) { left -= 1; } combinedIdx += 1; } return left <= 0 ? fn.apply(this, combined) : Object(_arity__WEBPACK_IMPORTED_MODULE_0__["default"])(left, _curryN(length, combined, fn)); }; } /***/ }), /* 637 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /* harmony import */ var _internal_has__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(638); /* harmony import */ var _internal_isArguments__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(639); // cover IE < 9 keys issues var hasEnumBug = ! /*#__PURE__*/{ toString: null }.propertyIsEnumerable('toString'); var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // Safari bug var hasArgsEnumBug = /*#__PURE__*/function () { 'use strict'; return arguments.propertyIsEnumerable('length'); }(); var contains = function contains(list, item) { var idx = 0; while (idx < list.length) { if (list[idx] === item) { return true; } idx += 1; } return false; }; /** * Returns a list containing the names of all the enumerable own properties of * the supplied object. * Note that the order of the output array is not guaranteed to be consistent * across different JS platforms. * * @func * @memberOf R * @since v0.1.0 * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties. * @see R.keysIn, R.values * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ var _keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? function keys(obj) { return Object(obj) !== obj ? [] : Object.keys(obj); } : function keys(obj) { if (Object(obj) !== obj) { return []; } var prop, nIdx; var ks = []; var checkArgsLength = hasArgsEnumBug && Object(_internal_isArguments__WEBPACK_IMPORTED_MODULE_2__["default"])(obj); for (prop in obj) { if (Object(_internal_has__WEBPACK_IMPORTED_MODULE_1__["default"])(prop, obj) && (!checkArgsLength || prop !== 'length')) { ks[ks.length] = prop; } } if (hasEnumBug) { nIdx = nonEnumerableProps.length - 1; while (nIdx >= 0) { prop = nonEnumerableProps[nIdx]; if (Object(_internal_has__WEBPACK_IMPORTED_MODULE_1__["default"])(prop, obj) && !contains(ks, prop)) { ks[ks.length] = prop; } nIdx -= 1; } } return ks; }; var keys = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(_keys); /* harmony default export */ __webpack_exports__["default"] = (keys); /***/ }), /* 638 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _has; }); function _has(prop, obj) { return Object.prototype.hasOwnProperty.call(obj, prop); } /***/ }), /* 639 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _has__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(638); var toString = Object.prototype.toString; var _isArguments = function () { return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } : function _isArguments(x) { return Object(_has__WEBPACK_IMPORTED_MODULE_0__["default"])('callee', x); }; }; /* harmony default export */ __webpack_exports__["default"] = (_isArguments); /***/ }), /* 640 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(641); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(616); /* harmony import */ var _curryN__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(635); /** * Creates a new list iteration function from an existing one by adding two new * parameters to its callback function: the current index, and the entire list. * * This would turn, for instance, [`R.map`](#map) function into one that * more closely resembles `Array.prototype.map`. Note that this will only work * for functions in which the iteration callback function is the first * parameter, and where the list is the last parameter. (This latter might be * unimportant if the list parameter is not used.) * * @func * @memberOf R * @since v0.15.0 * @category Function * @category List * @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *) * @param {Function} fn A list iteration function that does not pass index or list to its callback * @return {Function} An altered list iteration function that passes (item, index, list) to its callback * @example * * var mapIndexed = R.addIndex(R.map); * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']); * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] */ var addIndex = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_1__["default"])(function addIndex(fn) { return Object(_curryN__WEBPACK_IMPORTED_MODULE_2__["default"])(fn.length, function () { var idx = 0; var origFn = arguments[0]; var list = arguments[arguments.length - 1]; var args = Array.prototype.slice.call(arguments, 0); args[0] = function () { var result = origFn.apply(this, Object(_internal_concat__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments, [idx, list])); idx += 1; return result; }; return fn.apply(this, args); }); }); /* harmony default export */ __webpack_exports__["default"] = (addIndex); /***/ }), /* 641 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _concat; }); /** * Private `concat` function to merge two array-like objects. * * @private * @param {Array|Arguments} [set1=[]] An array-like object. * @param {Array|Arguments} [set2=[]] An array-like object. * @return {Array} A new, merged array. * @example * * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] */ function _concat(set1, set2) { set1 = set1 || []; set2 = set2 || []; var idx; var len1 = set1.length; var len2 = set2.length; var result = []; idx = 0; while (idx < len1) { result[result.length] = set1[idx]; idx += 1; } idx = 0; while (idx < len2) { result[result.length] = set2[idx]; idx += 1; } return result; } /***/ }), /* 642 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /** * Creates a new list out of the two supplied by creating each possible pair * from the lists. * * @func * @memberOf R * @since v0.1.0 * @category List * @sig [a] -> [b] -> [[a,b]] * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The list made by combining each possible pair from * `as` and `bs` into pairs (`[a, b]`). * @example * * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] * @symb R.xprod([a, b], [c, d]) = [[a, c], [a, d], [b, c], [b, d]] */ var xprod = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...) var idx = 0; var ilen = a.length; var j; var jlen = b.length; var result = []; while (idx < ilen) { j = 0; while (j < jlen) { result[result.length] = [a[idx], b[j]]; j += 1; } idx += 1; } return result; }); /* harmony default export */ __webpack_exports__["default"] = (xprod); /***/ }), /* 643 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_clone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(644); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(616); /** * Creates a deep copy of the value which may contain (nested) `Array`s and * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are * assigned by reference rather than copied * * Dispatches to a `clone` method if present. * * @func * @memberOf R * @since v0.1.0 * @category Object * @sig {*} -> {*} * @param {*} value The object or array to clone * @return {*} A deeply cloned copy of `val` * @example * * var objects = [{}, {}, {}]; * var objectsClone = R.clone(objects); * objects === objectsClone; //=> false * objects[0] === objectsClone[0]; //=> false */ var clone = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_1__["default"])(function clone(value) { return value != null && typeof value.clone === 'function' ? value.clone() : Object(_internal_clone__WEBPACK_IMPORTED_MODULE_0__["default"])(value, [], [], true); }); /* harmony default export */ __webpack_exports__["default"] = (clone); /***/ }), /* 644 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _clone; }); /* harmony import */ var _cloneRegExp__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(645); /* harmony import */ var _type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(646); /** * Copies an object. * * @private * @param {*} value The value to be copied * @param {Array} refFrom Array containing the source references * @param {Array} refTo Array containing the copied source references * @param {Boolean} deep Whether or not to perform deep cloning. * @return {*} The copied value. */ function _clone(value, refFrom, refTo, deep) { var copy = function copy(copiedValue) { var len = refFrom.length; var idx = 0; while (idx < len) { if (value === refFrom[idx]) { return refTo[idx]; } idx += 1; } refFrom[idx + 1] = value; refTo[idx + 1] = copiedValue; for (var key in value) { copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key]; } return copiedValue; }; switch (Object(_type__WEBPACK_IMPORTED_MODULE_1__["default"])(value)) { case 'Object': return copy({}); case 'Array': return copy([]); case 'Date': return new Date(value.valueOf()); case 'RegExp': return Object(_cloneRegExp__WEBPACK_IMPORTED_MODULE_0__["default"])(value); default: return value; } } /***/ }), /* 645 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _cloneRegExp; }); function _cloneRegExp(pattern) { return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '')); } /***/ }), /* 646 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /** * Gives a single-word string description of the (native) type of a value, * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not * attempt to distinguish user Object types any further, reporting them all as * 'Object'. * * @func * @memberOf R * @since v0.8.0 * @category Type * @sig (* -> {*}) -> String * @param {*} val The value to test * @return {String} * @example * * R.type({}); //=> "Object" * R.type(1); //=> "Number" * R.type(false); //=> "Boolean" * R.type('s'); //=> "String" * R.type(null); //=> "Null" * R.type([]); //=> "Array" * R.type(/[A-z]/); //=> "RegExp" * R.type(() => {}); //=> "Function" * R.type(undefined); //=> "Undefined" */ var type = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function type(val) { return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); }); /* harmony default export */ __webpack_exports__["default"] = (type); /***/ }), /* 647 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(648); /* harmony import */ var _uniqBy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(650); /** * Returns a new list containing only one copy of each element in the original * list. [`R.equals`](#equals) is used to determine equality. * * @func * @memberOf R * @since v0.1.0 * @category List * @sig [a] -> [a] * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * R.uniq([1, 1, 2, 1]); //=> [1, 2] * R.uniq([1, '1']); //=> [1, '1'] * R.uniq([[42], [42]]); //=> [[42]] */ var uniq = /*#__PURE__*/Object(_uniqBy__WEBPACK_IMPORTED_MODULE_1__["default"])(_identity__WEBPACK_IMPORTED_MODULE_0__["default"]); /* harmony default export */ __webpack_exports__["default"] = (uniq); /***/ }), /* 648 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /* harmony import */ var _internal_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(649); /** * A function that does nothing but return the parameter supplied to it. Good * as a default or placeholder function. * * @func * @memberOf R * @since v0.1.0 * @category Function * @sig a -> a * @param {*} x The value to return. * @return {*} The input value, `x`. * @example * * R.identity(1); //=> 1 * * var obj = {}; * R.identity(obj) === obj; //=> true * @symb R.identity(a) = a */ var identity = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(_internal_identity__WEBPACK_IMPORTED_MODULE_1__["default"]); /* harmony default export */ __webpack_exports__["default"] = (identity); /***/ }), /* 649 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _identity; }); function _identity(x) { return x; } /***/ }), /* 650 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_Set__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(651); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(615); /** * Returns a new list containing only one copy of each element in the original * list, based upon the value returned by applying the supplied function to * each list element. Prefers the first item if the supplied function produces * the same value on two items. [`R.equals`](#equals) is used for comparison. * * @func * @memberOf R * @since v0.16.0 * @category List * @sig (a -> b) -> [a] -> [a] * @param {Function} fn A function used to produce a value to use during comparisons. * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] */ var uniqBy = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_1__["default"])(function uniqBy(fn, list) { var set = new _internal_Set__WEBPACK_IMPORTED_MODULE_0__["default"](); var result = []; var idx = 0; var appliedItem, item; while (idx < list.length) { item = list[idx]; appliedItem = fn(item); if (set.add(appliedItem)) { result.push(item); } idx += 1; } return result; }); /* harmony default export */ __webpack_exports__["default"] = (uniqBy); /***/ }), /* 651 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _contains__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(652); var _Set = /*#__PURE__*/function () { function _Set() { /* globals Set */ this._nativeSet = typeof Set === 'function' ? new Set() : null; this._items = {}; } // until we figure out why jsdoc chokes on this // @param item The item to add to the Set // @returns {boolean} true if the item did not exist prior, otherwise false // _Set.prototype.add = function (item) { return !hasOrAdd(item, true, this); }; // // @param item The item to check for existence in the Set // @returns {boolean} true if the item exists in the Set, otherwise false // _Set.prototype.has = function (item) { return hasOrAdd(item, false, this); }; // // Combines the logic for checking whether an item is a member of the set and // for adding a new item to the set. // // @param item The item to check or add to the Set instance. // @param shouldAdd If true, the item will be added to the set if it doesn't // already exist. // @param set The set instance to check or add to. // @return {boolean} true if the item already existed, otherwise false. // return _Set; }(); function hasOrAdd(item, shouldAdd, set) { var type = typeof item; var prevSize, newSize; switch (type) { case 'string': case 'number': // distinguish between +0 and -0 if (item === 0 && 1 / item === -Infinity) { if (set._items['-0']) { return true; } else { if (shouldAdd) { set._items['-0'] = true; } return false; } } // these types can all utilise the native Set if (set._nativeSet !== null) { if (shouldAdd) { prevSize = set._nativeSet.size; set._nativeSet.add(item); newSize = set._nativeSet.size; return newSize === prevSize; } else { return set._nativeSet.has(item); } } else { if (!(type in set._items)) { if (shouldAdd) { set._items[type] = {}; set._items[type][item] = true; } return false; } else if (item in set._items[type]) { return true; } else { if (shouldAdd) { set._items[type][item] = true; } return false; } } case 'boolean': // set._items['boolean'] holds a two element array // representing [ falseExists, trueExists ] if (type in set._items) { var bIdx = item ? 1 : 0; if (set._items[type][bIdx]) { return true; } else { if (shouldAdd) { set._items[type][bIdx] = true; } return false; } } else { if (shouldAdd) { set._items[type] = item ? [false, true] : [true, false]; } return false; } case 'function': // compare functions for reference equality if (set._nativeSet !== null) { if (shouldAdd) { prevSize = set._nativeSet.size; set._nativeSet.add(item); newSize = set._nativeSet.size; return newSize === prevSize; } else { return set._nativeSet.has(item); } } else { if (!(type in set._items)) { if (shouldAdd) { set._items[type] = [item]; } return false; } if (!Object(_contains__WEBPACK_IMPORTED_MODULE_0__["default"])(item, set._items[type])) { if (shouldAdd) { set._items[type].push(item); } return false; } return true; } case 'undefined': if (set._items[type]) { return true; } else { if (shouldAdd) { set._items[type] = true; } return false; } case 'object': if (item === null) { if (!set._items['null']) { if (shouldAdd) { set._items['null'] = true; } return false; } return true; } /* falls through */ default: // reduce the search size of heterogeneous sets by creating buckets // for each type. type = Object.prototype.toString.call(item); if (!(type in set._items)) { if (shouldAdd) { set._items[type] = [item]; } return false; } // scan through all previously applied items if (!Object(_contains__WEBPACK_IMPORTED_MODULE_0__["default"])(item, set._items[type])) { if (shouldAdd) { set._items[type].push(item); } return false; } return true; } } // A simple Set type that honours R.equals semantics /* harmony default export */ __webpack_exports__["default"] = (_Set); /***/ }), /* 652 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _contains; }); /* harmony import */ var _indexOf__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(653); function _contains(a, list) { return Object(_indexOf__WEBPACK_IMPORTED_MODULE_0__["default"])(list, a, 0) >= 0; } /***/ }), /* 653 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _indexOf; }); /* harmony import */ var _equals__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(654); function _indexOf(list, a, idx) { var inf, item; // Array.prototype.indexOf doesn't exist below IE9 if (typeof list.indexOf === 'function') { switch (typeof a) { case 'number': if (a === 0) { // manually crawl the list to distinguish between +0 and -0 inf = 1 / a; while (idx < list.length) { item = list[idx]; if (item === 0 && 1 / item === inf) { return idx; } idx += 1; } return -1; } else if (a !== a) { // NaN while (idx < list.length) { item = list[idx]; if (typeof item === 'number' && item !== item) { return idx; } idx += 1; } return -1; } // non-zero numbers can utilise Set return list.indexOf(a, idx); // all these types can utilise Set case 'string': case 'boolean': case 'function': case 'undefined': return list.indexOf(a, idx); case 'object': if (a === null) { // null can utilise Set return list.indexOf(a, idx); } } } // anything else not covered above, defer to R.equals while (idx < list.length) { if (Object(_equals__WEBPACK_IMPORTED_MODULE_0__["default"])(list[idx], a)) { return idx; } idx += 1; } return -1; } /***/ }), /* 654 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _internal_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(655); /** * Returns `true` if its arguments are equivalent, `false` otherwise. Handles * cyclical data structures. * * Dispatches symmetrically to the `equals` methods of both arguments, if * present. * * @func * @memberOf R * @since v0.15.0 * @category Relation * @sig a -> b -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * R.equals(1, 1); //=> true * R.equals(1, '1'); //=> false * R.equals([1, 2, 3], [1, 2, 3]); //=> true * * var a = {}; a.v = a; * var b = {}; b.v = b; * R.equals(a, b); //=> true */ var equals = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function equals(a, b) { return Object(_internal_equals__WEBPACK_IMPORTED_MODULE_1__["default"])(a, b, [], []); }); /* harmony default export */ __webpack_exports__["default"] = (equals); /***/ }), /* 655 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _equals; }); /* harmony import */ var _arrayFromIterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(656); /* harmony import */ var _containsWith__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(657); /* harmony import */ var _functionName__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(658); /* harmony import */ var _has__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(638); /* harmony import */ var _identical__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(659); /* harmony import */ var _keys__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(637); /* harmony import */ var _type__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(646); /** * private _uniqContentEquals function. * That function is checking equality of 2 iterator contents with 2 assumptions * - iterators lengths are the same * - iterators values are unique * * false-positive result will be returned for comparision of, e.g. * - [1,2,3] and [1,2,3,4] * - [1,1,1] and [1,2,3] * */ function _uniqContentEquals(aIterator, bIterator, stackA, stackB) { var a = Object(_arrayFromIterator__WEBPACK_IMPORTED_MODULE_0__["default"])(aIterator); var b = Object(_arrayFromIterator__WEBPACK_IMPORTED_MODULE_0__["default"])(bIterator); function eq(_a, _b) { return _equals(_a, _b, stackA.slice(), stackB.slice()); } // if *a* array contains any element that is not included in *b* return !Object(_containsWith__WEBPACK_IMPORTED_MODULE_1__["default"])(function (b, aItem) { return !Object(_containsWith__WEBPACK_IMPORTED_MODULE_1__["default"])(eq, aItem, b); }, b, a); } function _equals(a, b, stackA, stackB) { if (Object(_identical__WEBPACK_IMPORTED_MODULE_4__["default"])(a, b)) { return true; } var typeA = Object(_type__WEBPACK_IMPORTED_MODULE_6__["default"])(a); if (typeA !== Object(_type__WEBPACK_IMPORTED_MODULE_6__["default"])(b)) { return false; } if (a == null || b == null) { return false; } if (typeof a['fantasy-land/equals'] === 'function' || typeof b['fantasy-land/equals'] === 'function') { return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) && typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a); } if (typeof a.equals === 'function' || typeof b.equals === 'function') { return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a); } switch (typeA) { case 'Arguments': case 'Array': case 'Object': if (typeof a.constructor === 'function' && Object(_functionName__WEBPACK_IMPORTED_MODULE_2__["default"])(a.constructor) === 'Promise') { return a === b; } break; case 'Boolean': case 'Number': case 'String': if (!(typeof a === typeof b && Object(_identical__WEBPACK_IMPORTED_MODULE_4__["default"])(a.valueOf(), b.valueOf()))) { return false; } break; case 'Date': if (!Object(_identical__WEBPACK_IMPORTED_MODULE_4__["default"])(a.valueOf(), b.valueOf())) { return false; } break; case 'Error': return a.name === b.name && a.message === b.message; case 'RegExp': if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) { return false; } break; } var idx = stackA.length - 1; while (idx >= 0) { if (stackA[idx] === a) { return stackB[idx] === b; } idx -= 1; } switch (typeA) { case 'Map': if (a.size !== b.size) { return false; } return _uniqContentEquals(a.entries(), b.entries(), stackA.concat([a]), stackB.concat([b])); case 'Set': if (a.size !== b.size) { return false; } return _uniqContentEquals(a.values(), b.values(), stackA.concat([a]), stackB.concat([b])); case 'Arguments': case 'Array': case 'Object': case 'Boolean': case 'Number': case 'String': case 'Date': case 'Error': case 'RegExp': case 'Int8Array': case 'Uint8Array': case 'Uint8ClampedArray': case 'Int16Array': case 'Uint16Array': case 'Int32Array': case 'Uint32Array': case 'Float32Array': case 'Float64Array': case 'ArrayBuffer': break; default: // Values of other types are only equal if identical. return false; } var keysA = Object(_keys__WEBPACK_IMPORTED_MODULE_5__["default"])(a); if (keysA.length !== Object(_keys__WEBPACK_IMPORTED_MODULE_5__["default"])(b).length) { return false; } var extendedStackA = stackA.concat([a]); var extendedStackB = stackB.concat([b]); idx = keysA.length - 1; while (idx >= 0) { var key = keysA[idx]; if (!(Object(_has__WEBPACK_IMPORTED_MODULE_3__["default"])(key, b) && _equals(b[key], a[key], extendedStackA, extendedStackB))) { return false; } idx -= 1; } return true; } /***/ }), /* 656 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _arrayFromIterator; }); function _arrayFromIterator(iter) { var list = []; var next; while (!(next = iter.next()).done) { list.push(next.value); } return list; } /***/ }), /* 657 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _containsWith; }); function _containsWith(pred, x, list) { var idx = 0; var len = list.length; while (idx < len) { if (pred(x, list[idx])) { return true; } idx += 1; } return false; } /***/ }), /* 658 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _functionName; }); function _functionName(f) { // String(x => x) evaluates to "x => x", so the pattern may not match. var match = String(f).match(/^function (\w*)/); return match == null ? '' : match[1]; } /***/ }), /* 659 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /** * Returns true if its arguments are identical, false otherwise. Values are * identical if they reference the same memory. `NaN` is identical to `NaN`; * `0` and `-0` are not identical. * * @func * @memberOf R * @since v0.15.0 * @category Relation * @sig a -> a -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * var o = {}; * R.identical(o, o); //=> true * R.identical(1, 1); //=> true * R.identical(1, '1'); //=> false * R.identical([], []); //=> false * R.identical(0, -0); //=> false * R.identical(NaN, NaN); //=> true */ var identical = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function identical(a, b) { // SameValue algorithm if (a === b) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return a !== 0 || 1 / a === 1 / b; } else { // Step 6.a: NaN == NaN return a !== a && b !== b; } }); /* harmony default export */ __webpack_exports__["default"] = (identical); /***/ }), /* 660 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /** * Creates a new object out of a list of keys and a list of values. * Key/value pairing is truncated to the length of the shorter of the two lists. * Note: `zipObj` is equivalent to `pipe(zip, fromPairs)`. * * @func * @memberOf R * @since v0.3.0 * @category List * @sig [String] -> [*] -> {String: *} * @param {Array} keys The array that will be properties on the output object. * @param {Array} values The list of values on the output object. * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`. * @example * * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} */ var zipObj = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function zipObj(keys, values) { var idx = 0; var len = Math.min(keys.length, values.length); var out = {}; while (idx < len) { out[keys[idx]] = values[idx]; idx += 1; } return out; }); /* harmony default export */ __webpack_exports__["default"] = (zipObj); /***/ }), /* 661 */, /* 662 */, /* 663 */, /* 664 */, /* 665 */, /* 666 */, /* 667 */, /* 668 */, /* 669 */, /* 670 */, /* 671 */, /* 672 */, /* 673 */, /* 674 */, /* 675 */, /* 676 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_assign__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(677); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(615); /** * Create a new object with the own properties of the first object merged with * the own properties of the second object. If a key exists in both objects, * the value from the second object will be used. * * @func * @memberOf R * @since v0.1.0 * @category Object * @sig {k: v} -> {k: v} -> {k: v} * @param {Object} l * @param {Object} r * @return {Object} * @see R.mergeDeepRight, R.mergeWith, R.mergeWithKey * @example * * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); * //=> { 'name': 'fred', 'age': 40 } * * var resetToDefault = R.merge(R.__, {x: 0}); * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} * @symb R.merge({ x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: 5, z: 3 } */ var merge = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_1__["default"])(function merge(l, r) { return Object(_internal_assign__WEBPACK_IMPORTED_MODULE_0__["default"])({}, l, r); }); /* harmony default export */ __webpack_exports__["default"] = (merge); /***/ }), /* 677 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _objectAssign__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(678); /* harmony default export */ __webpack_exports__["default"] = (typeof Object.assign === 'function' ? Object.assign : _objectAssign__WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /* 678 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _objectAssign; }); /* harmony import */ var _has__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(638); // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign function _objectAssign(target) { if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); var idx = 1; var length = arguments.length; while (idx < length) { var source = arguments[idx]; if (source != null) { for (var nextKey in source) { if (Object(_has__WEBPACK_IMPORTED_MODULE_0__["default"])(nextKey, source)) { output[nextKey] = source[nextKey]; } } } idx += 1; } return output; } /***/ }), /* 679 */, /* 680 */, /* 681 */, /* 682 */, /* 683 */, /* 684 */, /* 685 */, /* 686 */, /* 687 */, /* 688 */, /* 689 */, /* 690 */, /* 691 */, /* 692 */, /* 693 */, /* 694 */, /* 695 */, /* 696 */, /* 697 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry1__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(616); /** * Transposes the rows and columns of a 2D list. * When passed a list of `n` lists of length `x`, * returns a list of `x` lists of length `n`. * * * @func * @memberOf R * @since v0.19.0 * @category List * @sig [[a]] -> [[a]] * @param {Array} list A 2D list * @return {Array} A 2D list * @example * * R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] * R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] * * // If some of the rows are shorter than the following rows, their elements are skipped: * R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] * @symb R.transpose([[a], [b], [c]]) = [a, b, c] * @symb R.transpose([[a, b], [c, d]]) = [[a, c], [b, d]] * @symb R.transpose([[a, b], [c]]) = [[a, c], [b]] */ var transpose = /*#__PURE__*/Object(_internal_curry1__WEBPACK_IMPORTED_MODULE_0__["default"])(function transpose(outerlist) { var i = 0; var result = []; while (i < outerlist.length) { var innerlist = outerlist[i]; var j = 0; while (j < innerlist.length) { if (typeof result[j] === 'undefined') { result[j] = []; } result[j].push(innerlist[j]); j += 1; } i += 1; } return result; }); /* harmony default export */ __webpack_exports__["default"] = (transpose); /***/ }), /* 698 */, /* 699 */, /* 700 */, /* 701 */, /* 702 */, /* 703 */, /* 704 */, /* 705 */, /* 706 */, /* 707 */, /* 708 */, /* 709 */, /* 710 */, /* 711 */, /* 712 */, /* 713 */, /* 714 */, /* 715 */, /* 716 */, /* 717 */, /* 718 */, /* 719 */, /* 720 */, /* 721 */, /* 722 */, /* 723 */, /* 724 */, /* 725 */, /* 726 */, /* 727 */, /* 728 */, /* 729 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _constant = __webpack_require__(402); var _constant2 = _interopRequireDefault(_constant); var _continuous = __webpack_require__(400); var _continuous2 = _interopRequireDefault(_continuous); var _pair = __webpack_require__(730); var _pair2 = _interopRequireDefault(_pair); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var deinterpolate = function deinterpolate(min, max) { return (max = Math.log(max / min)) ? function (ratio) { return Math.log(ratio / min) / max; } : (0, _constant2['default'])(max); }, reinterpolate = function reinterpolate(min, max) { return min < 0 ? function (ratio) { return -Math.pow(-max, ratio) * Math.pow(-min, 1 - ratio); } : function (ratio) { return Math.pow(max, ratio) * Math.pow(min, 1 - ratio); }; }, pow10 = function pow10(x) { if (isFinite(x)) { return +('1e' + x); } else if (x < 0) { return 0; } else { return x; } }, powp = function powp(base) { if (base === 10) { return pow10; } else if (base === Math.E) { return Math.exp; } else { return function (x) { return Math.pow(base, x); }; } }, logp = function logp(base) { if (base === Math.E) { return Math.log; } else if (base === 10) { return Math.log10; } else if (base === 2) { return Math.log2; } else { return function (x) { return Math.log(x) / Math.log(base); }; } }, reflect = function reflect(f) { return function (x) { return -f(-x); }; }; var ScaleLog = function (_ScaleContinuous) { _inherits(ScaleLog, _ScaleContinuous); function ScaleLog() { var _this; _classCallCheck(this, ScaleLog); (_this = _possibleConstructorReturn(this, _ScaleContinuous.call(this, deinterpolate, reinterpolate)), _this).setDomain([1, 10]); _this.base = 10; _this.logs = logp(_this.base); _this.pows = powp(_this.base); return _this; } ScaleLog.prototype._rescaleLog = function _rescaleLog() { this.logs = logp(this.base); this.pows = powp(this.base); if (this.getDomain()[0] < 0) { this.logs = reflect(this.logs); this.pows = reflect(this.pows); } return this; }; ScaleLog.prototype.setBase = function setBase() { var base = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; this.base = Number(base); return this._rescaleLog(); }; ScaleLog.prototype.getBase = function getBase() { return this.base; }; ScaleLog.prototype.setDomain = function setDomain() { var domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [1, 10]; _ScaleContinuous.prototype.setDomain.call(this, domain); return this._rescaleLog(); }; ScaleLog.prototype.nice = function nice() { var _getDomain = this.getDomain(), val1 = _getDomain[0], val2 = _getDomain[1], base = this.base, minLog, maxLog; // If the minValue and the maxValue are same then there is a rendering problem // To avoid the rendering problem set the minValue to little higher value if (val1 === val2) { val1 -= val1 / 100; } minLog = Math.log(val1) / Math.log(base); maxLog = Math.log(val2) / Math.log(base); if (minLog % 1 || maxLog % 1) { if (val1 <= val2) { val1 = this.pows(Math.floor(minLog)); val2 = this.pows(Math.ceil(maxLog)); } else { val1 = this.pows(Math.ceil(minLog)); val2 = this.pows(Math.floor(maxLog)); } this.setDomain([val1, val2]); } return this; }; ScaleLog.prototype.tickFormat = function tickFormat(count, specifier) { var _this2 = this; var base = this.base, // can this be estimated quicker? k = Math.max(1, base * count / this.ticks().length); if (specifier == null) specifier = base === 10 ? '.0e' : ','; if (typeof specifier !== 'function') specifier = this._localeConverter.formatter(specifier); if (count === Infinity) return function (d) { return specifier.format(d); }; if (count == null) count = 10; return function (d) { var i = d / _this2.pows(Math.round(_this2.logs(d))); if (i * base < base - 0.5) i *= base; return i <= k ? specifier.format(d) : ''; }; }; ScaleLog.prototype.ticks = function ticks() { var _getDomain2 = this.getDomain(), min = _getDomain2[0], max = _getDomain2[1], maxLogY, isReverse = 1, minLogY, iniValue, checkValue, counter = 0, divLines = [], divLineValue, r, i, base = this.base; if (min <= 0 || max <= 0) { return divLines; } if (min > max) { var _getDomain3 = this.getDomain(); max = _getDomain3[0]; min = _getDomain3[1]; isReverse = 0; } // for base greater than one if (base > 1) { maxLogY = Math.ceil(Math.log(max) / Math.log(base)); minLogY = Math.floor(Math.log(min) / Math.log(base)); iniValue = maxLogY; checkValue = minLogY; } else if (base > 0 && base < 1) { maxLogY = Math.floor(Math.log(max) / Math.log(base)); minLogY = Math.ceil(Math.log(min) / Math.log(base)); iniValue = minLogY; checkValue = maxLogY; } r = maxLogY; for (i = iniValue; i >= checkValue; --i) { // Select the major divLines // Conditions for major div lines: // 1. If y-axis is inverted and div value is not the very first one // (the lowest one coinciding with x-axis) // OR // 2. If y-axis is not inverted and div value is not the very last one // (the lowest one coinciding with x-axis) // if ((invertYAxis && r != maxLogY) || !(invertYAxis || i == checkValue)) { // Get the numerical value of div line by getting power of base. divLineValue = this.pows(r); // Create the div line object // conditional to avoid plot of major divLines and their axis labels beyond plot area if (min <= divLineValue && max >= divLineValue) { divLines[counter++] = divLineValue; } // Update counter corresponding to next major divLine w.r.t. base value if (base > 1) { r--; } else { r++; } } return this.majorTicks = isReverse ? divLines.reverse() : divLines; }; ScaleLog.prototype.copy = function copy() { return (0, _continuous.copyScale)(this, new ScaleLog().setBase(this.base)); }; /** * Api to create minor ticks * @param {Number} numMinorTicks is the no of minor ticks will be craeted between two major ticks * @param {Array} majorTicks a set of major ticks if ticks has not been created from scale * @returns {Array} of minor ticks */ ScaleLog.prototype.minorTicks = function minorTicks(numMinorTicks) { var majorTicks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.majorTicks || this.ticks(); var base = this.base, tickPairs = (0, _pair2['default'])(majorTicks), i = void 0, minorTicks = [], baseWithRespectTo10 = Math.log(base) / Math.log(10), d = base > 1 ? -1 : 1, maxLogY = void 0, subInterval = void 0, slabInterval = void 0, divLineValue = void 0; numMinorTicks = Number(numMinorTicks) || baseWithRespectTo10 % 1 ? 4 : 8; tickPairs.forEach(function (_ref) { var min = _ref[0], max = _ref[1]; // for base greater than one if (base > 1) { maxLogY = Math.ceil(Math.log(max) / Math.log(base)); } else if (base > 0 && base < 1) { maxLogY = Math.floor(Math.log(max) / Math.log(base)); } // Multiplication factor // For base <1, powers go in negative -0.1 is 10^-1, 0.001 is 10 ^ -3 and so on. // Numeric interval between two succesive major divLines (variable) slabInterval = Math.pow(base, maxLogY) - Math.pow(base, maxLogY + d); // Numeric interval between two succesive minor divLines (variable) in between 2 // successive major divLines subInterval = slabInterval / (numMinorTicks + 1); for (i = 1; i <= numMinorTicks; ++i) { // Get the numeric value for minor div line // By adding the sub-interval to power of base (of major div line) divLineValue = Math.pow(base, maxLogY + d) + subInterval * i; if (min <= divLineValue && max >= divLineValue) { minorTicks.push(divLineValue); } } }); return minorTicks; }; ScaleLog.prototype.contextTicks = function contextTicks() { return this.contextTicksArr || []; }; ScaleLog.prototype.getType = function getType() { return 'log'; }; return ScaleLog; }(_continuous2['default']); exports['default'] = ScaleLog; /***/ }), /* 730 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; function pair(a, b) { return [a, b]; } function toPairs(arr, reducer) { if (reducer === null || typeof reducer === 'undefined') reducer = pair; var i = 0, n = arr.length - 1, p = arr[0], pairs = new Array(n < 0 ? 0 : n); while (i < n) { pairs[i] = reducer(p, p = arr[++i]); } return pairs; } exports['default'] = toPairs; /***/ }), /* 731 */, /* 732 */, /* 733 */, /* 734 */, /* 735 */, /* 736 */, /* 737 */, /* 738 */, /* 739 */, /* 740 */ /***/ (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; }; /***/ }), /* 741 */, /* 742 */, /* 743 */, /* 744 */, /* 745 */, /* 746 */, /* 747 */, /* 748 */, /* 749 */, /* 750 */, /* 751 */, /* 752 */, /* 753 */, /* 754 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(618); /* harmony import */ var _internal_xall__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(755); /** * Returns `true` if all elements of the list match the predicate, `false` if * there are any that don't. * * Dispatches to the `all` method of the second argument, if present. * * Acts as a transducer if a transformer is given in list position. * * @func * @memberOf R * @since v0.1.0 * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {Boolean} `true` if the predicate is satisfied by every element, `false` * otherwise. * @see R.any, R.none, R.transduce * @example * * var equals3 = R.equals(3); * R.all(equals3)([3, 3, 3, 3]); //=> true * R.all(equals3)([3, 3, 1, 3]); //=> false */ var all = /*#__PURE__*/Object(_internal_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/Object(_internal_dispatchable__WEBPACK_IMPORTED_MODULE_1__["default"])(['all'], _internal_xall__WEBPACK_IMPORTED_MODULE_2__["default"], function all(fn, list) { var idx = 0; while (idx < list.length) { if (!fn(list[idx])) { return false; } idx += 1; } return true; })); /* harmony default export */ __webpack_exports__["default"] = (all); /***/ }), /* 755 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _curry2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(615); /* harmony import */ var _reduced__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(756); /* harmony import */ var _xfBase__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(631); var XAll = /*#__PURE__*/function () { function XAll(f, xf) { this.xf = xf; this.f = f; this.all = true; } XAll.prototype['@@transducer/init'] = _xfBase__WEBPACK_IMPORTED_MODULE_2__["default"].init; XAll.prototype['@@transducer/result'] = function (result) { if (this.all) { result = this.xf['@@transducer/step'](result, true); } return this.xf['@@transducer/result'](result); }; XAll.prototype['@@transducer/step'] = function (result, input) { if (!this.f(input)) { this.all = false; result = Object(_reduced__WEBPACK_IMPORTED_MODULE_1__["default"])(this.xf['@@transducer/step'](result, false)); } return result; }; return XAll; }(); var _xall = /*#__PURE__*/Object(_curry2__WEBPACK_IMPORTED_MODULE_0__["default"])(function _xall(f, xf) { return new XAll(f, xf); }); /* harmony default export */ __webpack_exports__["default"] = (_xall); /***/ }), /* 756 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _reduced; }); function _reduced(x) { return x && x['@@transducer/reduced'] ? x : { '@@transducer/value': x, '@@transducer/reduced': true }; } /***/ }), /* 757 */, /* 758 */, /* 759 */, /* 760 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(297); __webpack_require__(78); __webpack_require__(298); __webpack_require__(761); __webpack_require__(762); __webpack_require__(763); __webpack_require__(764); module.exports = __webpack_require__(7).Map; /***/ }), /* 761 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var strong = __webpack_require__(302); var validate = __webpack_require__(308); var MAP = 'Map'; // 23.1 Map Objects module.exports = __webpack_require__(309)(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); /***/ }), /* 762 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(5); $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(313)('Map') }); /***/ }), /* 763 */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of __webpack_require__(316)('Map'); /***/ }), /* 764 */ /***/ (function(module, exports, __webpack_require__) { // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from __webpack_require__(318)('Map'); /***/ }), /* 765 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.create = exports.createGenerateClassName = exports.sheets = exports.RuleList = exports.SheetsManager = exports.SheetsRegistry = exports.toCssValue = exports.getDynamicStyles = undefined; var _getDynamicStyles = __webpack_require__(766); Object.defineProperty(exports, 'getDynamicStyles', { enumerable: true, get: function get() { return _interopRequireDefault(_getDynamicStyles)['default']; } }); var _toCssValue = __webpack_require__(767); Object.defineProperty(exports, 'toCssValue', { enumerable: true, get: function get() { return _interopRequireDefault(_toCssValue)['default']; } }); var _SheetsRegistry = __webpack_require__(768); Object.defineProperty(exports, 'SheetsRegistry', { enumerable: true, get: function get() { return _interopRequireDefault(_SheetsRegistry)['default']; } }); var _SheetsManager = __webpack_require__(769); Object.defineProperty(exports, 'SheetsManager', { enumerable: true, get: function get() { return _interopRequireDefault(_SheetsManager)['default']; } }); var _RuleList = __webpack_require__(771); Object.defineProperty(exports, 'RuleList', { enumerable: true, get: function get() { return _interopRequireDefault(_RuleList)['default']; } }); var _sheets = __webpack_require__(782); Object.defineProperty(exports, 'sheets', { enumerable: true, get: function get() { return _interopRequireDefault(_sheets)['default']; } }); var _createGenerateClassName = __webpack_require__(783); Object.defineProperty(exports, 'createGenerateClassName', { enumerable: true, get: function get() { return _interopRequireDefault(_createGenerateClassName)['default']; } }); var _Jss = __webpack_require__(786); var _Jss2 = _interopRequireDefault(_Jss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a new instance of Jss. */ var create = exports.create = function create(options) { return new _Jss2['default'](options); }; /** * A global Jss instance. */ exports['default'] = create(); /***/ }), /* 766 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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['default'] = getDynamicStyles; /** * Extracts a styles object with only props that contain function values. */ function getDynamicStyles(styles) { var to = null; for (var key in styles) { var value = styles[key]; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (type === 'function') { if (!to) to = {}; to[key] = value; } else if (type === 'object' && value !== null && !Array.isArray(value)) { var extracted = getDynamicStyles(value); if (extracted) { if (!to) to = {}; to[key] = extracted; } } } return to; } /***/ }), /* 767 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = toCssValue; var join = function join(value, by) { var result = ''; for (var i = 0; i < value.length; i++) { // Remove !important from the value, it will be readded later. if (value[i] === '!important') break; if (result) result += by; result += value[i]; } return result; }; /** * Converts array values to string. * * `margin: [['5px', '10px']]` > `margin: 5px 10px;` * `border: ['1px', '2px']` > `border: 1px, 2px;` * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;` * `color: ['red', !important]` > `color: red !important;` */ function toCssValue(value) { var ignoreImportant = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!Array.isArray(value)) return value; var cssValue = ''; // Support space separated values via `[['5px', '10px']]`. if (Array.isArray(value[0])) { for (var i = 0; i < value.length; i++) { if (value[i] === '!important') break; if (cssValue) cssValue += ', '; cssValue += join(value[i], ' '); } } else cssValue = join(value, ', '); // Add !important, because it was ignored. if (!ignoreImportant && value[value.length - 1] === '!important') { cssValue += ' !important'; } return cssValue; } /***/ }), /* 768 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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"); } } /** * Sheets registry to access them all at one place. */ var SheetsRegistry = function () { function SheetsRegistry() { _classCallCheck(this, SheetsRegistry); this.registry = []; } _createClass(SheetsRegistry, [{ key: 'add', /** * Register a Style Sheet. */ value: function add(sheet) { var registry = this.registry; var index = sheet.options.index; if (registry.indexOf(sheet) !== -1) return; if (registry.length === 0 || index >= this.index) { registry.push(sheet); return; } // Find a position. for (var i = 0; i < registry.length; i++) { if (registry[i].options.index > index) { registry.splice(i, 0, sheet); return; } } } /** * Reset the registry. */ }, { key: 'reset', value: function reset() { this.registry = []; } /** * Remove a Style Sheet. */ }, { key: 'remove', value: function remove(sheet) { var index = this.registry.indexOf(sheet); this.registry.splice(index, 1); } /** * Convert all attached sheets to a CSS string. */ }, { key: 'toString', value: function toString(options) { return this.registry.filter(function (sheet) { return sheet.attached; }).map(function (sheet) { return sheet.toString(options); }).join('\n'); } }, { key: 'index', /** * Current highest index number. */ get: function get() { return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index; } }]); return SheetsRegistry; }(); exports['default'] = SheetsRegistry; /***/ }), /* 769 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); 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"); } } /** * SheetsManager is like a WeakMap which is designed to count StyleSheet * instances and attach/detach automatically. */ var SheetsManager = function () { function SheetsManager() { _classCallCheck(this, SheetsManager); this.sheets = []; this.refs = []; this.keys = []; } _createClass(SheetsManager, [{ key: 'get', value: function get(key) { var index = this.keys.indexOf(key); return this.sheets[index]; } }, { key: 'add', value: function add(key, sheet) { var sheets = this.sheets, refs = this.refs, keys = this.keys; var index = sheets.indexOf(sheet); if (index !== -1) return index; sheets.push(sheet); refs.push(0); keys.push(key); return sheets.length - 1; } }, { key: 'manage', value: function manage(key) { var index = this.keys.indexOf(key); var sheet = this.sheets[index]; if (this.refs[index] === 0) sheet.attach(); this.refs[index]++; if (!this.keys[index]) this.keys.splice(index, 0, key); return sheet; } }, { key: 'unmanage', value: function unmanage(key) { var index = this.keys.indexOf(key); if (index === -1) { // eslint-ignore-next-line no-console (0, _warning2['default'])(false, "SheetsManager: can't find sheet to unmanage"); return; } if (this.refs[index] > 0) { this.refs[index]--; if (this.refs[index] === 0) this.sheets[index].detach(); } } }, { key: 'size', get: function get() { return this.keys.length; } }]); return SheetsManager; }(); exports['default'] = SheetsManager; /***/ }), /* 770 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }), /* 771 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _createRule = __webpack_require__(772); var _createRule2 = _interopRequireDefault(_createRule); var _linkRule = __webpack_require__(780); var _linkRule2 = _interopRequireDefault(_linkRule); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _escape = __webpack_require__(781); var _escape2 = _interopRequireDefault(_escape); 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"); } } /** * Contains rules objects and allows adding/removing etc. * Is used for e.g. by `StyleSheet` or `ConditionalRule`. */ var RuleList = function () { // Original styles object. function RuleList(options) { var _this = this; _classCallCheck(this, RuleList); this.map = {}; this.raw = {}; this.index = []; this.update = function (name, data) { var _options = _this.options, plugins = _options.jss.plugins, sheet = _options.sheet; if (typeof name === 'string') { plugins.onUpdate(data, _this.get(name), sheet); } else { for (var index = 0; index < _this.index.length; index++) { plugins.onUpdate(name, _this.index[index], sheet); } } }; this.options = options; this.classes = options.classes; } /** * Create and register rule. * * Will not render after Style Sheet was rendered the first time. */ // Used to ensure correct rules order. // Rules registry for access by .get() method. // It contains the same rule registered by name and by selector. _createClass(RuleList, [{ key: 'add', value: function add(name, decl, options) { var _options2 = this.options, parent = _options2.parent, sheet = _options2.sheet, jss = _options2.jss, Renderer = _options2.Renderer, generateClassName = _options2.generateClassName; options = _extends({ classes: this.classes, parent: parent, sheet: sheet, jss: jss, Renderer: Renderer, generateClassName: generateClassName }, options); if (!options.selector && this.classes[name]) { options.selector = '.' + (0, _escape2['default'])(this.classes[name]); } this.raw[name] = decl; var rule = (0, _createRule2['default'])(name, decl, options); var className = void 0; if (!options.selector && rule instanceof _StyleRule2['default']) { className = generateClassName(rule, sheet); rule.selector = '.' + (0, _escape2['default'])(className); } this.register(rule, className); var index = options.index === undefined ? this.index.length : options.index; this.index.splice(index, 0, rule); return rule; } /** * Get a rule. */ }, { key: 'get', value: function get(name) { return this.map[name]; } /** * Delete a rule. */ }, { key: 'remove', value: function remove(rule) { this.unregister(rule); this.index.splice(this.indexOf(rule), 1); } /** * Get index of a rule. */ }, { key: 'indexOf', value: function indexOf(rule) { return this.index.indexOf(rule); } /** * Run `onProcessRule()` plugins on every rule. */ }, { key: 'process', value: function process() { var plugins = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop // we end up with very hard-to-track-down side effects. this.index.slice(0).forEach(plugins.onProcessRule, plugins); } /** * Register a rule in `.map` and `.classes` maps. */ }, { key: 'register', value: function register(rule, className) { this.map[rule.key] = rule; if (rule instanceof _StyleRule2['default']) { this.map[rule.selector] = rule; if (className) this.classes[rule.key] = className; } } /** * Unregister a rule. */ }, { key: 'unregister', value: function unregister(rule) { delete this.map[rule.key]; if (rule instanceof _StyleRule2['default']) { delete this.map[rule.selector]; delete this.classes[rule.key]; } } /** * Update the function values with a new data. */ }, { key: 'link', /** * Link renderable rules with CSSRuleList. */ value: function link(cssRules) { var map = this.options.sheet.renderer.getUnescapedKeysMap(this.index); for (var i = 0; i < cssRules.length; i++) { var cssRule = cssRules[i]; var _key = this.options.sheet.renderer.getKey(cssRule); if (map[_key]) _key = map[_key]; var rule = this.map[_key]; if (rule) (0, _linkRule2['default'])(rule, cssRule); } } /** * Convert rules to a CSS string. */ }, { key: 'toString', value: function toString(options) { var str = ''; var sheet = this.options.sheet; var link = sheet ? sheet.options.link : false; for (var index = 0; index < this.index.length; index++) { var rule = this.index[index]; var css = rule.toString(options); // No need to render an empty rule. if (!css && !link) continue; if (str) str += '\n'; str += css; } return str; } }]); return RuleList; }(); exports['default'] = RuleList; /***/ }), /* 772 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = createRule; var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _cloneStyle = __webpack_require__(775); var _cloneStyle2 = _interopRequireDefault(_cloneStyle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Create a rule instance. */ function createRule() { var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'unnamed'; var decl = arguments[1]; var options = arguments[2]; var jss = options.jss; var declCopy = (0, _cloneStyle2['default'])(decl); var rule = jss.plugins.onCreateRule(name, declCopy, options); if (rule) return rule; // It is an at-rule and it has no instance. if (name[0] === '@') { (0, _warning2['default'])(false, '[JSS] Unknown at-rule %s', name); } return new _StyleRule2['default'](name, declCopy, options); } /***/ }), /* 773 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _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 _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); var _toCss = __webpack_require__(774); var _toCss2 = _interopRequireDefault(_toCss); var _toCssValue = __webpack_require__(767); var _toCssValue2 = _interopRequireDefault(_toCssValue); 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 StyleRule = function () { function StyleRule(key, style, options) { _classCallCheck(this, StyleRule); this.type = 'style'; this.isProcessed = false; var sheet = options.sheet, Renderer = options.Renderer, selector = options.selector; this.key = key; this.options = options; this.style = style; if (selector) this.selectorText = selector; this.renderer = sheet ? sheet.renderer : new Renderer(); } /** * Set selector string. * Attention: use this with caution. Most browsers didn't implement * selectorText setter, so this may result in rerendering of entire Style Sheet. */ _createClass(StyleRule, [{ key: 'prop', /** * Get or set a style property. */ value: function prop(name, value) { // It's a getter. if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed. if (this.style[name] === value) return this; value = this.options.jss.plugins.onChangeValue(value, name, this); var isEmpty = value == null || value === false; var isDefined = name in this.style; // Value is empty and wasn't defined before. if (isEmpty && !isDefined) return this; // We are going to remove this value. var remove = isEmpty && isDefined; if (remove) delete this.style[name];else this.style[name] = value; // Renderable is defined if StyleSheet option `link` is true. if (this.renderable) { if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, value); return this; } var sheet = this.options.sheet; if (sheet && sheet.attached) { (0, _warning2['default'])(false, 'Rule is not linked. Missing sheet option "link: true".'); } return this; } /** * Apply rule to an element inline. */ }, { key: 'applyTo', value: function applyTo(renderable) { var json = this.toJSON(); for (var prop in json) { this.renderer.setProperty(renderable, prop, json[prop]); }return this; } /** * Returns JSON representation of the rule. * Fallbacks are not supported. * Useful for inline styles. */ }, { key: 'toJSON', value: function toJSON() { var json = {}; for (var prop in this.style) { var value = this.style[prop]; if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = (0, _toCssValue2['default'])(value); } return json; } /** * Generates a CSS string. */ }, { key: 'toString', value: function toString(options) { var sheet = this.options.sheet; var link = sheet ? sheet.options.link : false; var opts = link ? _extends({}, options, { allowEmpty: true }) : options; return (0, _toCss2['default'])(this.selector, this.style, opts); } }, { key: 'selector', set: function set(selector) { if (selector === this.selectorText) return; this.selectorText = selector; if (!this.renderable) return; var hasChanged = this.renderer.setSelector(this.renderable, selector); // If selector setter is not implemented, rerender the rule. if (!hasChanged && this.renderable) { var renderable = this.renderer.replaceRule(this.renderable, this); if (renderable) this.renderable = renderable; } } /** * Get selector string. */ , get: function get() { return this.selectorText; } }]); return StyleRule; }(); exports['default'] = StyleRule; /***/ }), /* 774 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = toCss; var _toCssValue = __webpack_require__(767); var _toCssValue2 = _interopRequireDefault(_toCssValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Indent a string. * http://jsperf.com/array-join-vs-for */ function indentStr(str, indent) { var result = ''; for (var index = 0; index < indent; index++) { result += ' '; }return result + str; } /** * Converts a Rule to CSS string. */ function toCss(selector, style) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var result = ''; if (!style) return result; var _options$indent = options.indent, indent = _options$indent === undefined ? 0 : _options$indent; var fallbacks = style.fallbacks; indent++; // Apply fallbacks first. if (fallbacks) { // Array syntax {fallbacks: [{prop: value}]} if (Array.isArray(fallbacks)) { for (var index = 0; index < fallbacks.length; index++) { var fallback = fallbacks[index]; for (var prop in fallback) { var value = fallback[prop]; if (value != null) { result += '\n' + indentStr(prop + ': ' + (0, _toCssValue2['default'])(value) + ';', indent); } } } } else { // Object syntax {fallbacks: {prop: value}} for (var _prop in fallbacks) { var _value = fallbacks[_prop]; if (_value != null) { result += '\n' + indentStr(_prop + ': ' + (0, _toCssValue2['default'])(_value) + ';', indent); } } } } for (var _prop2 in style) { var _value2 = style[_prop2]; if (_value2 != null && _prop2 !== 'fallbacks') { result += '\n' + indentStr(_prop2 + ': ' + (0, _toCssValue2['default'])(_value2) + ';', indent); } } // Allow empty style in this case, because properties will be added dynamically. if (!result && !options.allowEmpty) return result; indent--; result = indentStr(selector + ' {' + result + '\n', indent) + indentStr('}', indent); return result; } /***/ }), /* 775 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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['default'] = cloneStyle; var _isObservable = __webpack_require__(776); var _isObservable2 = _interopRequireDefault(_isObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var isArray = Array.isArray; function cloneStyle(style) { // Support empty values in case user ends up with them by accident. if (style == null) return style; // Support string value for SimpleRule. var typeOfStyle = typeof style === 'undefined' ? 'undefined' : _typeof(style); if (typeOfStyle === 'string' || typeOfStyle === 'number' || typeOfStyle === 'function') { return style; } // Support array for FontFaceRule. if (isArray(style)) return style.map(cloneStyle); // Support Observable styles. Observables are immutable, so we don't need to // copy them. if ((0, _isObservable2['default'])(style)) return style; var newStyle = {}; for (var name in style) { var value = style[name]; if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { newStyle[name] = cloneStyle(value); continue; } newStyle[name] = value; } return newStyle; } /***/ }), /* 776 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _symbolObservable = __webpack_require__(777); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = function (value) { return value && value[_symbolObservable2['default']] && value === value[_symbolObservable2['default']](); }; /***/ }), /* 777 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global, module) {/* harmony import */ var _ponyfill_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(779); /* global window */ var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else {} var result = Object(_ponyfill_js__WEBPACK_IMPORTED_MODULE_0__["default"])(root); /* harmony default export */ __webpack_exports__["default"] = (result); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(118), __webpack_require__(778)(module))) /***/ }), /* 778 */ /***/ (function(module, exports) { module.exports = function(originalModule) { if (!originalModule.webpackPolyfill) { var module = Object.create(originalModule); // 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; } }); Object.defineProperty(module, "exports", { enumerable: true }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 779 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return symbolObservablePonyfill; }); function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }), /* 780 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = linkRule; /** * Link rule with CSSStyleRule and nested rules with corresponding nested cssRules if both exists. */ function linkRule(rule, cssRule) { rule.renderable = cssRule; if (rule.rules && cssRule.cssRules) rule.rules.link(cssRule.cssRules); } /***/ }), /* 781 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); var CSS = global.CSS; var env = "none"; var escapeRegex = /([[\].#*$><+~=|^:(),"'`])/g; exports['default'] = function (str) { // We don't need to escape it in production, because we are not using user's // input for selectors, we are generating a valid selector. if (env === 'production') return str; if (!CSS || !CSS.escape) { return str.replace(escapeRegex, '\\$1'); } return CSS.escape(str); }; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(118))) /***/ }), /* 782 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _SheetsRegistry = __webpack_require__(768); var _SheetsRegistry2 = _interopRequireDefault(_SheetsRegistry); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * This is a global sheets registry. Only DomRenderer will add sheets to it. * On the server one should use an own SheetsRegistry instance and add the * sheets to it, because you need to make sure to create a new registry for * each request in order to not leak sheets across requests. */ exports['default'] = new _SheetsRegistry2['default'](); /***/ }), /* 783 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); var _StyleSheet = __webpack_require__(784); var _StyleSheet2 = _interopRequireDefault(_StyleSheet); var _moduleId = __webpack_require__(785); var _moduleId2 = _interopRequireDefault(_moduleId); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var maxRules = 1e10; var env = "none"; /** * Returns a function which generates unique class names based on counters. * When new generator function is created, rule counter is reseted. * We need to reset the rule counter for SSR for each request. */ exports['default'] = function () { var ruleCounter = 0; var defaultPrefix = env === 'production' ? 'c' : ''; return function (rule, sheet) { ruleCounter += 1; if (ruleCounter > maxRules) { (0, _warning2['default'])(false, '[JSS] You might have a memory leak. Rule counter is at %s.', ruleCounter); } var prefix = defaultPrefix; var jssId = ''; if (sheet) { prefix = sheet.options.classNamePrefix || defaultPrefix; if (sheet.options.jss.id != null) jssId += sheet.options.jss.id; } if (env === 'production') { return '' + prefix + _moduleId2['default'] + jssId + ruleCounter; } return prefix + rule.key + '-' + _moduleId2['default'] + (jssId && '-' + jssId) + '-' + ruleCounter; }; }; /***/ }), /* 784 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _linkRule = __webpack_require__(780); var _linkRule2 = _interopRequireDefault(_linkRule); var _RuleList = __webpack_require__(771); var _RuleList2 = _interopRequireDefault(_RuleList); 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"); } } /* eslint-disable-next-line no-use-before-define */ var StyleSheet = function () { function StyleSheet(styles, options) { var _this = this; _classCallCheck(this, StyleSheet); this.update = function (name, data) { if (typeof name === 'string') { _this.rules.update(name, data); } else { _this.rules.update(name); } return _this; }; this.attached = false; this.deployed = false; this.linked = false; this.classes = {}; this.options = _extends({}, options, { sheet: this, parent: this, classes: this.classes }); this.renderer = new options.Renderer(this); this.rules = new _RuleList2['default'](this.options); for (var _name in styles) { this.rules.add(_name, styles[_name]); } this.rules.process(); } /** * Attach renderable to the render tree. */ _createClass(StyleSheet, [{ key: 'attach', value: function attach() { if (this.attached) return this; if (!this.deployed) this.deploy(); this.renderer.attach(); if (!this.linked && this.options.link) this.link(); this.attached = true; return this; } /** * Remove renderable from render tree. */ }, { key: 'detach', value: function detach() { if (!this.attached) return this; this.renderer.detach(); this.attached = false; return this; } /** * Add a rule to the current stylesheet. * Will insert a rule also after the stylesheet has been rendered first time. */ }, { key: 'addRule', value: function addRule(name, decl, options) { var queue = this.queue; // Plugins can create rules. // In order to preserve the right order, we need to queue all `.addRule` calls, // which happen after the first `rules.add()` call. if (this.attached && !queue) this.queue = []; var rule = this.rules.add(name, decl, options); this.options.jss.plugins.onProcessRule(rule); if (this.attached) { if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet. // It will be inserted all together when .attach is called. if (queue) queue.push(rule);else { this.insertRule(rule); if (this.queue) { this.queue.forEach(this.insertRule, this); this.queue = undefined; } } return rule; } // We can't add rules to a detached style node. // We will redeploy the sheet once user will attach it. this.deployed = false; return rule; } /** * Insert rule into the StyleSheet */ }, { key: 'insertRule', value: function insertRule(rule) { var renderable = this.renderer.insertRule(rule); if (renderable && this.options.link) (0, _linkRule2['default'])(rule, renderable); } /** * Create and add rules. * Will render also after Style Sheet was rendered the first time. */ }, { key: 'addRules', value: function addRules(styles, options) { var added = []; for (var _name2 in styles) { added.push(this.addRule(_name2, styles[_name2], options)); } return added; } /** * Get a rule by name. */ }, { key: 'getRule', value: function getRule(name) { return this.rules.get(name); } /** * Delete a rule by name. * Returns `true`: if rule has been deleted from the DOM. */ }, { key: 'deleteRule', value: function deleteRule(name) { var rule = this.rules.get(name); if (!rule) return false; this.rules.remove(rule); if (this.attached && rule.renderable) { return this.renderer.deleteRule(rule.renderable); } return true; } /** * Get index of a rule. */ }, { key: 'indexOf', value: function indexOf(rule) { return this.rules.indexOf(rule); } /** * Deploy pure CSS string to a renderable. */ }, { key: 'deploy', value: function deploy() { this.renderer.deploy(); this.deployed = true; return this; } /** * Link renderable CSS rules from sheet with their corresponding models. */ }, { key: 'link', value: function link() { var cssRules = this.renderer.getRules(); // Is undefined when VirtualRenderer is used. if (cssRules) this.rules.link(cssRules); this.linked = true; return this; } /** * Update the function values with a new data. */ }, { key: 'toString', /** * Convert rules to a CSS string. */ value: function toString(options) { return this.rules.toString(options); } }]); return StyleSheet; }(); exports['default'] = StyleSheet; /***/ }), /* 785 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); var ns = '2f1acc6c3a606b082e5eef5e54414ffb'; if (global[ns] == null) global[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify // the current version with just one short number and use it for classes generation // we use a counter. Also it is more accurate, because user can manually reevaluate // the module. exports['default'] = global[ns]++; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(118))) /***/ }), /* 786 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _isInBrowser = __webpack_require__(787); var _isInBrowser2 = _interopRequireDefault(_isInBrowser); var _StyleSheet = __webpack_require__(784); var _StyleSheet2 = _interopRequireDefault(_StyleSheet); var _PluginsRegistry = __webpack_require__(788); var _PluginsRegistry2 = _interopRequireDefault(_PluginsRegistry); var _rules = __webpack_require__(789); var _rules2 = _interopRequireDefault(_rules); var _observables = __webpack_require__(795); var _observables2 = _interopRequireDefault(_observables); var _functions = __webpack_require__(796); var _functions2 = _interopRequireDefault(_functions); var _sheets = __webpack_require__(782); var _sheets2 = _interopRequireDefault(_sheets); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _createGenerateClassName = __webpack_require__(783); var _createGenerateClassName2 = _interopRequireDefault(_createGenerateClassName); var _createRule2 = __webpack_require__(772); var _createRule3 = _interopRequireDefault(_createRule2); var _DomRenderer = __webpack_require__(797); var _DomRenderer2 = _interopRequireDefault(_DomRenderer); var _VirtualRenderer = __webpack_require__(798); var _VirtualRenderer2 = _interopRequireDefault(_VirtualRenderer); 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 defaultPlugins = _rules2['default'].concat([_observables2['default'], _functions2['default']]); var instanceCounter = 0; var Jss = function () { function Jss(options) { _classCallCheck(this, Jss); this.id = instanceCounter++; this.version = "9.8.7"; this.plugins = new _PluginsRegistry2['default'](); this.options = { createGenerateClassName: _createGenerateClassName2['default'], Renderer: _isInBrowser2['default'] ? _DomRenderer2['default'] : _VirtualRenderer2['default'], plugins: [] }; this.generateClassName = (0, _createGenerateClassName2['default'])(); // eslint-disable-next-line prefer-spread this.use.apply(this, defaultPlugins); this.setup(options); } _createClass(Jss, [{ key: 'setup', value: function setup() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (options.createGenerateClassName) { this.options.createGenerateClassName = options.createGenerateClassName; // $FlowFixMe this.generateClassName = options.createGenerateClassName(); } if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint; if (options.virtual || options.Renderer) { this.options.Renderer = options.Renderer || (options.virtual ? _VirtualRenderer2['default'] : _DomRenderer2['default']); } // eslint-disable-next-line prefer-spread if (options.plugins) this.use.apply(this, options.plugins); return this; } /** * Create a Style Sheet. */ }, { key: 'createStyleSheet', value: function createStyleSheet(styles) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var index = options.index; if (typeof index !== 'number') { index = _sheets2['default'].index === 0 ? 0 : _sheets2['default'].index + 1; } var sheet = new _StyleSheet2['default'](styles, _extends({}, options, { jss: this, generateClassName: options.generateClassName || this.generateClassName, insertionPoint: this.options.insertionPoint, Renderer: this.options.Renderer, index: index })); this.plugins.onProcessSheet(sheet); return sheet; } /** * Detach the Style Sheet and remove it from the registry. */ }, { key: 'removeStyleSheet', value: function removeStyleSheet(sheet) { sheet.detach(); _sheets2['default'].remove(sheet); return this; } /** * Create a rule without a Style Sheet. */ }, { key: 'createRule', value: function createRule(name) { var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; // Enable rule without name for inline styles. if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { options = style; style = name; name = undefined; } // Cast from RuleFactoryOptions to RuleOptions // https://stackoverflow.com/questions/41328728/force-casting-in-flow var ruleOptions = options; ruleOptions.jss = this; ruleOptions.Renderer = this.options.Renderer; if (!ruleOptions.generateClassName) ruleOptions.generateClassName = this.generateClassName; if (!ruleOptions.classes) ruleOptions.classes = {}; var rule = (0, _createRule3['default'])(name, style, ruleOptions); if (!ruleOptions.selector && rule instanceof _StyleRule2['default']) { rule.selector = '.' + ruleOptions.generateClassName(rule); } this.plugins.onProcessRule(rule); return rule; } /** * Register plugin. Passed function will be invoked with a rule instance. */ }, { key: 'use', value: function use() { var _this = this; for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) { plugins[_key] = arguments[_key]; } plugins.forEach(function (plugin) { // Avoids applying same plugin twice, at least based on ref. if (_this.options.plugins.indexOf(plugin) === -1) { _this.options.plugins.push(plugin); _this.plugins.use(plugin); } }); return this; } }]); return Jss; }(); exports['default'] = Jss; /***/ }), /* 787 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBrowser", function() { return isBrowser; }); 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 isBrowser = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object" && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && document.nodeType === 9; /* harmony default export */ __webpack_exports__["default"] = (isBrowser); /***/ }), /* 788 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); 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 PluginsRegistry = function () { function PluginsRegistry() { _classCallCheck(this, PluginsRegistry); this.hooks = { onCreateRule: [], onProcessRule: [], onProcessStyle: [], onProcessSheet: [], onChangeValue: [], onUpdate: [] /** * Call `onCreateRule` hooks and return an object if returned by a hook. */ }; } _createClass(PluginsRegistry, [{ key: 'onCreateRule', value: function onCreateRule(name, decl, options) { for (var i = 0; i < this.hooks.onCreateRule.length; i++) { var rule = this.hooks.onCreateRule[i](name, decl, options); if (rule) return rule; } return null; } /** * Call `onProcessRule` hooks. */ }, { key: 'onProcessRule', value: function onProcessRule(rule) { if (rule.isProcessed) return; var sheet = rule.options.sheet; for (var i = 0; i < this.hooks.onProcessRule.length; i++) { this.hooks.onProcessRule[i](rule, sheet); } // $FlowFixMe if (rule.style) this.onProcessStyle(rule.style, rule, sheet); rule.isProcessed = true; } /** * Call `onProcessStyle` hooks. */ }, { key: 'onProcessStyle', value: function onProcessStyle(style, rule, sheet) { var nextStyle = style; for (var i = 0; i < this.hooks.onProcessStyle.length; i++) { nextStyle = this.hooks.onProcessStyle[i](nextStyle, rule, sheet); // $FlowFixMe rule.style = nextStyle; } } /** * Call `onProcessSheet` hooks. */ }, { key: 'onProcessSheet', value: function onProcessSheet(sheet) { for (var i = 0; i < this.hooks.onProcessSheet.length; i++) { this.hooks.onProcessSheet[i](sheet); } } /** * Call `onUpdate` hooks. */ }, { key: 'onUpdate', value: function onUpdate(data, rule, sheet) { for (var i = 0; i < this.hooks.onUpdate.length; i++) { this.hooks.onUpdate[i](data, rule, sheet); } } /** * Call `onChangeValue` hooks. */ }, { key: 'onChangeValue', value: function onChangeValue(value, prop, rule) { var processedValue = value; for (var i = 0; i < this.hooks.onChangeValue.length; i++) { processedValue = this.hooks.onChangeValue[i](processedValue, prop, rule); } return processedValue; } /** * Register a plugin. * If function is passed, it is a shortcut for `{onProcessRule}`. */ }, { key: 'use', value: function use(plugin) { for (var name in plugin) { if (this.hooks[name]) this.hooks[name].push(plugin[name]);else (0, _warning2['default'])(false, '[JSS] Unknown hook "%s".', name); } } }]); return PluginsRegistry; }(); exports['default'] = PluginsRegistry; /***/ }), /* 789 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _SimpleRule = __webpack_require__(790); var _SimpleRule2 = _interopRequireDefault(_SimpleRule); var _KeyframesRule = __webpack_require__(791); var _KeyframesRule2 = _interopRequireDefault(_KeyframesRule); var _ConditionalRule = __webpack_require__(792); var _ConditionalRule2 = _interopRequireDefault(_ConditionalRule); var _FontFaceRule = __webpack_require__(793); var _FontFaceRule2 = _interopRequireDefault(_FontFaceRule); var _ViewportRule = __webpack_require__(794); var _ViewportRule2 = _interopRequireDefault(_ViewportRule); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var classes = { '@charset': _SimpleRule2['default'], '@import': _SimpleRule2['default'], '@namespace': _SimpleRule2['default'], '@keyframes': _KeyframesRule2['default'], '@media': _ConditionalRule2['default'], '@supports': _ConditionalRule2['default'], '@font-face': _FontFaceRule2['default'], '@viewport': _ViewportRule2['default'], '@-ms-viewport': _ViewportRule2['default'] /** * Generate plugins which will register all rules. */ }; var plugins = Object.keys(classes).map(function (key) { // https://jsperf.com/indexof-vs-substr-vs-regex-at-the-beginning-3 var re = new RegExp('^' + key); var RuleClass = classes[key]; var onCreateRule = function onCreateRule(name, decl, options) { return re.test(name) ? new RuleClass(name, decl, options) : null; }; return { onCreateRule: onCreateRule }; }); exports['default'] = plugins; /***/ }), /* 790 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 SimpleRule = function () { function SimpleRule(key, value, options) { _classCallCheck(this, SimpleRule); this.type = 'simple'; this.isProcessed = false; this.key = key; this.value = value; this.options = options; } /** * Generates a CSS string. */ // eslint-disable-next-line no-unused-vars _createClass(SimpleRule, [{ key: 'toString', value: function toString(options) { if (Array.isArray(this.value)) { var str = ''; for (var index = 0; index < this.value.length; index++) { str += this.key + ' ' + this.value[index] + ';'; if (this.value[index + 1]) str += '\n'; } return str; } return this.key + ' ' + this.value + ';'; } }]); return SimpleRule; }(); exports['default'] = SimpleRule; /***/ }), /* 791 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _RuleList = __webpack_require__(771); var _RuleList2 = _interopRequireDefault(_RuleList); 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"); } } /** * Rule for @keyframes */ var KeyframesRule = function () { function KeyframesRule(key, frames, options) { _classCallCheck(this, KeyframesRule); this.type = 'keyframes'; this.isProcessed = false; this.key = key; this.options = options; this.rules = new _RuleList2['default'](_extends({}, options, { parent: this })); for (var name in frames) { this.rules.add(name, frames[name], _extends({}, this.options, { parent: this, selector: name })); } this.rules.process(); } /** * Generates a CSS string. */ _createClass(KeyframesRule, [{ key: 'toString', value: function toString() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { indent: 1 }; var inner = this.rules.toString(options); if (inner) inner += '\n'; return this.key + ' {\n' + inner + '}'; } }]); return KeyframesRule; }(); exports['default'] = KeyframesRule; /***/ }), /* 792 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _RuleList = __webpack_require__(771); var _RuleList2 = _interopRequireDefault(_RuleList); 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"); } } /** * Conditional rule for @media, @supports */ var ConditionalRule = function () { function ConditionalRule(key, styles, options) { _classCallCheck(this, ConditionalRule); this.type = 'conditional'; this.isProcessed = false; this.key = key; this.options = options; this.rules = new _RuleList2['default'](_extends({}, options, { parent: this })); for (var name in styles) { this.rules.add(name, styles[name]); } this.rules.process(); } /** * Get a rule. */ _createClass(ConditionalRule, [{ key: 'getRule', value: function getRule(name) { return this.rules.get(name); } /** * Get index of a rule. */ }, { key: 'indexOf', value: function indexOf(rule) { return this.rules.indexOf(rule); } /** * Create and register rule, run plugins. */ }, { key: 'addRule', value: function addRule(name, style, options) { var rule = this.rules.add(name, style, options); this.options.jss.plugins.onProcessRule(rule); return rule; } /** * Generates a CSS string. */ }, { key: 'toString', value: function toString() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { indent: 1 }; var inner = this.rules.toString(options); return inner ? this.key + ' {\n' + inner + '\n}' : ''; } }]); return ConditionalRule; }(); exports['default'] = ConditionalRule; /***/ }), /* 793 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _toCss = __webpack_require__(774); var _toCss2 = _interopRequireDefault(_toCss); 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 FontFaceRule = function () { function FontFaceRule(key, style, options) { _classCallCheck(this, FontFaceRule); this.type = 'font-face'; this.isProcessed = false; this.key = key; this.style = style; this.options = options; } /** * Generates a CSS string. */ _createClass(FontFaceRule, [{ key: 'toString', value: function toString(options) { if (Array.isArray(this.style)) { var str = ''; for (var index = 0; index < this.style.length; index++) { str += (0, _toCss2['default'])(this.key, this.style[index]); if (this.style[index + 1]) str += '\n'; } return str; } return (0, _toCss2['default'])(this.key, this.style, options); } }]); return FontFaceRule; }(); exports['default'] = FontFaceRule; /***/ }), /* 794 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _toCss = __webpack_require__(774); var _toCss2 = _interopRequireDefault(_toCss); 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 ViewportRule = function () { function ViewportRule(key, style, options) { _classCallCheck(this, ViewportRule); this.type = 'viewport'; this.isProcessed = false; this.key = key; this.style = style; this.options = options; } /** * Generates a CSS string. */ _createClass(ViewportRule, [{ key: 'toString', value: function toString(options) { return (0, _toCss2['default'])(this.key, this.style, options); } }]); return ViewportRule; }(); exports['default'] = ViewportRule; /***/ }), /* 795 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _createRule = __webpack_require__(772); var _createRule2 = _interopRequireDefault(_createRule); var _isObservable = __webpack_require__(776); var _isObservable2 = _interopRequireDefault(_isObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { onCreateRule: function onCreateRule(name, decl, options) { if (!(0, _isObservable2['default'])(decl)) return null; // Cast `decl` to `Observable`, since it passed the type guard. var style$ = decl; var rule = (0, _createRule2['default'])(name, {}, options); // TODO // Call `stream.subscribe()` returns a subscription, which should be explicitly // unsubscribed from when we know this sheet is no longer needed. style$.subscribe(function (style) { for (var prop in style) { rule.prop(prop, style[prop]); } }); return rule; }, onProcessRule: function onProcessRule(rule) { if (!(rule instanceof _StyleRule2['default'])) return; var styleRule = rule; var style = styleRule.style; var _loop = function _loop(prop) { var value = style[prop]; if (!(0, _isObservable2['default'])(value)) return 'continue'; delete style[prop]; value.subscribe({ next: function next(nextValue) { styleRule.prop(prop, nextValue); } }); }; for (var prop in style) { var _ret = _loop(prop); if (_ret === 'continue') continue; } } }; /***/ }), /* 796 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _RuleList = __webpack_require__(771); var _RuleList2 = _interopRequireDefault(_RuleList); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _createRule = __webpack_require__(772); var _createRule2 = _interopRequireDefault(_createRule); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // A symbol replacement. var now = Date.now(); var fnValuesNs = 'fnValues' + now; var fnStyleNs = 'fnStyle' + ++now; exports['default'] = { onCreateRule: function onCreateRule(name, decl, options) { if (typeof decl !== 'function') return null; var rule = (0, _createRule2['default'])(name, {}, options); rule[fnStyleNs] = decl; return rule; }, onProcessStyle: function onProcessStyle(style, rule) { var fn = {}; for (var prop in style) { var value = style[prop]; if (typeof value !== 'function') continue; delete style[prop]; fn[prop] = value; } rule = rule; rule[fnValuesNs] = fn; return style; }, onUpdate: function onUpdate(data, rule) { // It is a rules container like for e.g. ConditionalRule. if (rule.rules instanceof _RuleList2['default']) { rule.rules.update(data); return; } if (!(rule instanceof _StyleRule2['default'])) return; rule = rule; // If we have a fn values map, it is a rule with function values. if (rule[fnValuesNs]) { for (var prop in rule[fnValuesNs]) { rule.prop(prop, rule[fnValuesNs][prop](data)); } } rule = rule; var fnStyle = rule[fnStyleNs]; // If we have a style function, the entire rule is dynamic and style object // will be returned from that function. if (fnStyle) { var style = fnStyle(data); for (var _prop in style) { rule.prop(_prop, style[_prop]); } } } }; /***/ }), /* 797 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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 _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); var _sheets = __webpack_require__(782); var _sheets2 = _interopRequireDefault(_sheets); var _StyleRule = __webpack_require__(773); var _StyleRule2 = _interopRequireDefault(_StyleRule); var _toCssValue = __webpack_require__(767); var _toCssValue2 = _interopRequireDefault(_toCssValue); 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"); } } /** * Cache the value from the first time a function is called. */ var memoize = function memoize(fn) { var value = void 0; return function () { if (!value) value = fn(); return value; }; }; /** * Get a style property value. */ function getPropertyValue(cssRule, prop) { try { return cssRule.style.getPropertyValue(prop); } catch (err) { // IE may throw if property is unknown. return ''; } } /** * Set a style property. */ function setProperty(cssRule, prop, value) { try { var cssValue = value; if (Array.isArray(value)) { cssValue = (0, _toCssValue2['default'])(value, true); if (value[value.length - 1] === '!important') { cssRule.style.setProperty(prop, cssValue, 'important'); return true; } } cssRule.style.setProperty(prop, cssValue); } catch (err) { // IE may throw if property is unknown. return false; } return true; } /** * Remove a style property. */ function removeProperty(cssRule, prop) { try { cssRule.style.removeProperty(prop); } catch (err) { (0, _warning2['default'])(false, '[JSS] DOMException "%s" was thrown. Tried to remove property "%s".', err.message, prop); } } var CSSRuleTypes = { STYLE_RULE: 1, KEYFRAMES_RULE: 7 /** * Get the CSS Rule key. */ };var getKey = function () { var extractKey = function extractKey(cssText) { var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return cssText.substr(from, cssText.indexOf('{') - 1); }; return function (cssRule) { if (cssRule.type === CSSRuleTypes.STYLE_RULE) return cssRule.selectorText; if (cssRule.type === CSSRuleTypes.KEYFRAMES_RULE) { var name = cssRule.name; if (name) return '@keyframes ' + name; // There is no rule.name in the following browsers: // - IE 9 // - Safari 7.1.8 // - Mobile Safari 9.0.0 var cssText = cssRule.cssText; return '@' + extractKey(cssText, cssText.indexOf('keyframes')); } // Conditionals. return extractKey(cssRule.cssText); }; }(); /** * Set the selector. */ function setSelector(cssRule, selectorText) { cssRule.selectorText = selectorText; // Return false if setter was not successful. // Currently works in chrome only. return cssRule.selectorText === selectorText; } /** * Gets the `head` element upon the first call and caches it. */ var getHead = memoize(function () { return document.head || document.getElementsByTagName('head')[0]; }); /** * Gets a map of rule keys, where the property is an unescaped key and value * is a potentially escaped one. * It is used to identify CSS rules and the corresponding JSS rules. As an identifier * for CSSStyleRule we normally use `selectorText`. Though if original selector text * contains escaped code points e.g. `:not(#\\20)`, CSSOM will compile it to `:not(# )` * and so CSS rule's `selectorText` won't match JSS rule selector. * * https://www.w3.org/International/questions/qa-escapes#cssescapes */ var getUnescapedKeysMap = function () { var style = void 0; var isAttached = false; return function (rules) { var map = {}; // https://github.com/facebook/flow/issues/2696 if (!style) style = document.createElement('style'); for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (!(rule instanceof _StyleRule2['default'])) continue; var selector = rule.selector; // Only unescape selector over CSSOM if it contains a back slash. if (selector && selector.indexOf('\\') !== -1) { // Lazilly attach when needed. if (!isAttached) { getHead().appendChild(style); isAttached = true; } style.textContent = selector + ' {}'; var _style = style, sheet = _style.sheet; if (sheet) { var cssRules = sheet.cssRules; if (cssRules) map[cssRules[0].selectorText] = rule.key; } } } if (isAttached) { getHead().removeChild(style); isAttached = false; } return map; }; }(); /** * Find attached sheet with an index higher than the passed one. */ function findHigherSheet(registry, options) { for (var i = 0; i < registry.length; i++) { var sheet = registry[i]; if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) { return sheet; } } return null; } /** * Find attached sheet with the highest index. */ function findHighestSheet(registry, options) { for (var i = registry.length - 1; i >= 0; i--) { var sheet = registry[i]; if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) { return sheet; } } return null; } /** * Find a comment with "jss" inside. */ function findCommentNode(text) { var head = getHead(); for (var i = 0; i < head.childNodes.length; i++) { var node = head.childNodes[i]; if (node.nodeType === 8 && node.nodeValue.trim() === text) { return node; } } return null; } /** * Find a node before which we can insert the sheet. */ function findPrevNode(options) { var registry = _sheets2['default'].registry; if (registry.length > 0) { // Try to insert before the next higher sheet. var sheet = findHigherSheet(registry, options); if (sheet) return sheet.renderer.element; // Otherwise insert after the last attached. sheet = findHighestSheet(registry, options); if (sheet) return sheet.renderer.element.nextElementSibling; } // Try to find a comment placeholder if registry is empty. var insertionPoint = options.insertionPoint; if (insertionPoint && typeof insertionPoint === 'string') { var comment = findCommentNode(insertionPoint); if (comment) return comment.nextSibling; // If user specifies an insertion point and it can't be found in the document - // bad specificity issues may appear. (0, _warning2['default'])(insertionPoint === 'jss', '[JSS] Insertion point "%s" not found.', insertionPoint); } return null; } /** * Insert style element into the DOM. */ function insertStyle(style, options) { var insertionPoint = options.insertionPoint; var prevNode = findPrevNode(options); if (prevNode) { var parentNode = prevNode.parentNode; if (parentNode) parentNode.insertBefore(style, prevNode); return; } // Works with iframes and any node types. if (insertionPoint && typeof insertionPoint.nodeType === 'number') { // https://stackoverflow.com/questions/41328728/force-casting-in-flow var insertionPointElement = insertionPoint; var _parentNode = insertionPointElement.parentNode; if (_parentNode) _parentNode.insertBefore(style, insertionPointElement.nextSibling);else (0, _warning2['default'])(false, '[JSS] Insertion point is not in the DOM.'); return; } getHead().insertBefore(style, prevNode); } /** * Read jss nonce setting from the page if the user has set it. */ var getNonce = memoize(function () { var node = document.querySelector('meta[property="csp-nonce"]'); return node ? node.getAttribute('content') : null; }); var DomRenderer = function () { function DomRenderer(sheet) { _classCallCheck(this, DomRenderer); this.getPropertyValue = getPropertyValue; this.setProperty = setProperty; this.removeProperty = removeProperty; this.setSelector = setSelector; this.getKey = getKey; this.getUnescapedKeysMap = getUnescapedKeysMap; this.hasInsertedRules = false; // There is no sheet when the renderer is used from a standalone StyleRule. if (sheet) _sheets2['default'].add(sheet); this.sheet = sheet; var _ref = this.sheet ? this.sheet.options : {}, media = _ref.media, meta = _ref.meta, element = _ref.element; this.element = element || document.createElement('style'); this.element.setAttribute('data-jss', ''); if (media) this.element.setAttribute('media', media); if (meta) this.element.setAttribute('data-meta', meta); var nonce = getNonce(); if (nonce) this.element.setAttribute('nonce', nonce); } /** * Insert style element into render tree. */ // HTMLStyleElement needs fixing https://github.com/facebook/flow/issues/2696 _createClass(DomRenderer, [{ key: 'attach', value: function attach() { // In the case the element node is external and it is already in the DOM. if (this.element.parentNode || !this.sheet) return; // When rules are inserted using `insertRule` API, after `sheet.detach().attach()` // browsers remove those rules. // TODO figure out if its a bug and if it is known. // Workaround is to redeploy the sheet before attaching as a string. if (this.hasInsertedRules) { this.deploy(); this.hasInsertedRules = false; } insertStyle(this.element, this.sheet.options); } /** * Remove style element from render tree. */ }, { key: 'detach', value: function detach() { this.element.parentNode.removeChild(this.element); } /** * Inject CSS string into element. */ }, { key: 'deploy', value: function deploy() { if (!this.sheet) return; this.element.textContent = '\n' + this.sheet.toString() + '\n'; } /** * Insert a rule into element. */ }, { key: 'insertRule', value: function insertRule(rule, index) { var sheet = this.element.sheet; var cssRules = sheet.cssRules; var str = rule.toString(); if (!index) index = cssRules.length; if (!str) return false; try { sheet.insertRule(str, index); } catch (err) { (0, _warning2['default'])(false, '[JSS] Can not insert an unsupported rule \n\r%s', rule); return false; } this.hasInsertedRules = true; return cssRules[index]; } /** * Delete a rule. */ }, { key: 'deleteRule', value: function deleteRule(cssRule) { var sheet = this.element.sheet; var index = this.indexOf(cssRule); if (index === -1) return false; sheet.deleteRule(index); return true; } /** * Get index of a CSS Rule. */ }, { key: 'indexOf', value: function indexOf(cssRule) { var cssRules = this.element.sheet.cssRules; for (var _index = 0; _index < cssRules.length; _index++) { if (cssRule === cssRules[_index]) return _index; } return -1; } /** * Generate a new CSS rule and replace the existing one. */ }, { key: 'replaceRule', value: function replaceRule(cssRule, rule) { var index = this.indexOf(cssRule); var newCssRule = this.insertRule(rule, index); this.element.sheet.deleteRule(index); return newCssRule; } /** * Get all rules elements. */ }, { key: 'getRules', value: function getRules() { return this.element.sheet.cssRules; } }]); return DomRenderer; }(); exports['default'] = DomRenderer; /***/ }), /* 798 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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"); } } /* eslint-disable class-methods-use-this */ /** * Rendering backend to do nothing in nodejs. */ var VirtualRenderer = function () { function VirtualRenderer() { _classCallCheck(this, VirtualRenderer); } _createClass(VirtualRenderer, [{ key: 'setProperty', value: function setProperty() { return true; } }, { key: 'getPropertyValue', value: function getPropertyValue() { return ''; } }, { key: 'removeProperty', value: function removeProperty() {} }, { key: 'setSelector', value: function setSelector() { return true; } }, { key: 'getKey', value: function getKey() { return ''; } }, { key: 'attach', value: function attach() {} }, { key: 'detach', value: function detach() {} }, { key: 'deploy', value: function deploy() {} }, { key: 'insertRule', value: function insertRule() { return false; } }, { key: 'deleteRule', value: function deleteRule() { return true; } }, { key: 'replaceRule', value: function replaceRule() { return false; } }, { key: 'getRules', value: function getRules() {} }, { key: 'indexOf', value: function indexOf() { return -1; } }]); return VirtualRenderer; }(); exports['default'] = VirtualRenderer; /***/ }), /* 799 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _jssTemplate = __webpack_require__(800); var _jssTemplate2 = _interopRequireDefault(_jssTemplate); var _jssGlobal = __webpack_require__(802); var _jssGlobal2 = _interopRequireDefault(_jssGlobal); var _jssExtend = __webpack_require__(803); var _jssExtend2 = _interopRequireDefault(_jssExtend); var _jssNested = __webpack_require__(804); var _jssNested2 = _interopRequireDefault(_jssNested); var _jssCompose = __webpack_require__(805); var _jssCompose2 = _interopRequireDefault(_jssCompose); var _jssCamelCase = __webpack_require__(806); var _jssCamelCase2 = _interopRequireDefault(_jssCamelCase); var _jssDefaultUnit = __webpack_require__(808); var _jssDefaultUnit2 = _interopRequireDefault(_jssDefaultUnit); var _jssExpand = __webpack_require__(810); var _jssExpand2 = _interopRequireDefault(_jssExpand); var _jssVendorPrefixer = __webpack_require__(812); var _jssVendorPrefixer2 = _interopRequireDefault(_jssVendorPrefixer); var _jssPropsSort = __webpack_require__(818); var _jssPropsSort2 = _interopRequireDefault(_jssPropsSort); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return { plugins: [(0, _jssTemplate2.default)(options.template), (0, _jssGlobal2.default)(options.global), (0, _jssExtend2.default)(options.extend), (0, _jssNested2.default)(options.nested), (0, _jssCompose2.default)(options.compose), (0, _jssCamelCase2.default)(options.camelCase), (0, _jssDefaultUnit2.default)(options.defaultUnit), (0, _jssExpand2.default)(options.expand), (0, _jssVendorPrefixer2.default)(options.vendorPrefixer), (0, _jssPropsSort2.default)(options.propsSort)] }; }; /***/ }), /* 800 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _parse = __webpack_require__(801); var _parse2 = _interopRequireDefault(_parse); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var onProcessRule = function onProcessRule(rule) { if (typeof rule.style === 'string') { rule.style = (0, _parse2['default'])(rule.style); } }; exports['default'] = function () { return { onProcessRule: onProcessRule }; }; /***/ }), /* 801 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var semiWithNl = /;\n/; /** * Naive CSS parser. * - Supports only rule body (no selectors) * - Requires semicolon and new line after the value (except of last line) * - No nested rules support */ exports['default'] = function (cssText) { var style = {}; var split = cssText.split(semiWithNl); for (var i = 0; i < split.length; i++) { var decl = (split[i] || '').trim(); if (!decl) continue; var colonIndex = decl.indexOf(':'); if (colonIndex === -1) { (0, _warning2['default'])(false, 'Malformed CSS string "%s"', decl); continue; } var prop = decl.substr(0, colonIndex).trim(); var value = decl.substr(colonIndex + 1).trim(); style[prop] = value; } return style; }; /***/ }), /* 802 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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['default'] = jssGlobal; var _jss = __webpack_require__(765); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var propKey = '@global'; var prefixKey = '@global '; var GlobalContainerRule = function () { function GlobalContainerRule(key, styles, options) { _classCallCheck(this, GlobalContainerRule); this.type = 'global'; this.key = key; this.options = options; this.rules = new _jss.RuleList(_extends({}, options, { parent: this })); for (var selector in styles) { this.rules.add(selector, styles[selector], { selector: selector }); } this.rules.process(); } /** * Get a rule. */ _createClass(GlobalContainerRule, [{ key: 'getRule', value: function getRule(name) { return this.rules.get(name); } /** * Create and register rule, run plugins. */ }, { key: 'addRule', value: function addRule(name, style, options) { var rule = this.rules.add(name, style, options); this.options.jss.plugins.onProcessRule(rule); return rule; } /** * Get index of a rule. */ }, { key: 'indexOf', value: function indexOf(rule) { return this.rules.indexOf(rule); } /** * Generates a CSS string. */ }, { key: 'toString', value: function toString() { return this.rules.toString(); } }]); return GlobalContainerRule; }(); var GlobalPrefixedRule = function () { function GlobalPrefixedRule(name, style, options) { _classCallCheck(this, GlobalPrefixedRule); this.name = name; this.options = options; var selector = name.substr(prefixKey.length); this.rule = options.jss.createRule(selector, style, _extends({}, options, { parent: this, selector: selector })); } _createClass(GlobalPrefixedRule, [{ key: 'toString', value: function toString(options) { return this.rule.toString(options); } }]); return GlobalPrefixedRule; }(); var separatorRegExp = /\s*,\s*/g; function addScope(selector, scope) { var parts = selector.split(separatorRegExp); var scoped = ''; for (var i = 0; i < parts.length; i++) { scoped += scope + ' ' + parts[i].trim(); if (parts[i + 1]) scoped += ', '; } return scoped; } function handleNestedGlobalContainerRule(rule) { var options = rule.options, style = rule.style; var rules = style[propKey]; if (!rules) return; for (var name in rules) { options.sheet.addRule(name, rules[name], _extends({}, options, { selector: addScope(name, rule.selector) })); } delete style[propKey]; } function handlePrefixedGlobalRule(rule) { var options = rule.options, style = rule.style; for (var prop in style) { if (prop.substr(0, propKey.length) !== propKey) continue; var selector = addScope(prop.substr(propKey.length), rule.selector); options.sheet.addRule(selector, style[prop], _extends({}, options, { selector: selector })); delete style[prop]; } } /** * Convert nested rules to separate, remove them from original styles. * * @param {Rule} rule * @api public */ function jssGlobal() { function onCreateRule(name, styles, options) { if (name === propKey) { return new GlobalContainerRule(name, styles, options); } if (name[0] === '@' && name.substr(0, prefixKey.length) === prefixKey) { return new GlobalPrefixedRule(name, styles, options); } var parent = options.parent; if (parent) { if (parent.type === 'global' || parent.options.parent.type === 'global') { options.global = true; } } if (options.global) options.selector = name; return null; } function onProcessRule(rule) { if (rule.type !== 'style') return; handleNestedGlobalContainerRule(rule); handlePrefixedGlobalRule(rule); } return { onCreateRule: onCreateRule, onProcessRule: onProcessRule }; } /***/ }), /* 803 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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['default'] = jssExtend; var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var isObject = function isObject(obj) { return obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && !Array.isArray(obj); }; var valueNs = 'extendCurrValue' + Date.now(); function mergeExtend(style, rule, sheet, newStyle) { var extendType = _typeof(style.extend); // Extend using a rule name. if (extendType === 'string') { if (!sheet) return; var refRule = sheet.getRule(style.extend); if (!refRule) return; if (refRule === rule) { (0, _warning2['default'])(false, '[JSS] A rule tries to extend itself \r\n%s', rule); return; } var parent = refRule.options.parent; if (parent) { var originalStyle = parent.rules.raw[style.extend]; extend(originalStyle, rule, sheet, newStyle); } return; } // Extend using an array of objects. if (Array.isArray(style.extend)) { for (var index = 0; index < style.extend.length; index++) { extend(style.extend[index], rule, sheet, newStyle); } return; } // Extend is a style object. for (var prop in style.extend) { if (prop === 'extend') { extend(style.extend.extend, rule, sheet, newStyle); continue; } if (isObject(style.extend[prop])) { if (!(prop in newStyle)) newStyle[prop] = {}; extend(style.extend[prop], rule, sheet, newStyle[prop]); continue; } newStyle[prop] = style.extend[prop]; } } function mergeRest(style, rule, sheet, newStyle) { // Copy base style. for (var prop in style) { if (prop === 'extend') continue; if (isObject(newStyle[prop]) && isObject(style[prop])) { extend(style[prop], rule, sheet, newStyle[prop]); continue; } if (isObject(style[prop])) { newStyle[prop] = extend(style[prop], rule, sheet); continue; } newStyle[prop] = style[prop]; } } /** * Recursively extend styles. */ function extend(style, rule, sheet) { var newStyle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; mergeExtend(style, rule, sheet, newStyle); mergeRest(style, rule, sheet, newStyle); return newStyle; } /** * Handle `extend` property. * * @param {Rule} rule * @api public */ function jssExtend() { function onProcessStyle(style, rule, sheet) { if ('extend' in style) return extend(style, rule, sheet); return style; } function onChangeValue(value, prop, rule) { if (prop !== 'extend') return value; // Value is empty, remove properties set previously. if (value == null || value === false) { for (var key in rule[valueNs]) { rule.prop(key, null); } rule[valueNs] = null; return null; } for (var _key in value) { rule.prop(_key, value[_key]); } rule[valueNs] = value; // Make sure we don't set the value in the core. return null; } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; } /***/ }), /* 804 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = jssNested; var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var separatorRegExp = /\s*,\s*/g; var parentRegExp = /&/g; var refRegExp = /\$([\w-]+)/g; /** * Convert nested rules to separate, remove them from original styles. * * @param {Rule} rule * @api public */ function jssNested() { // Get a function to be used for $ref replacement. function getReplaceRef(container) { return function (match, key) { var rule = container.getRule(key); if (rule) return rule.selector; (0, _warning2.default)(false, '[JSS] Could not find the referenced rule %s in %s.', key, container.options.meta || container); return key; }; } var hasAnd = function hasAnd(str) { return str.indexOf('&') !== -1; }; function replaceParentRefs(nestedProp, parentProp) { var parentSelectors = parentProp.split(separatorRegExp); var nestedSelectors = nestedProp.split(separatorRegExp); var result = ''; for (var i = 0; i < parentSelectors.length; i++) { var parent = parentSelectors[i]; for (var j = 0; j < nestedSelectors.length; j++) { var nested = nestedSelectors[j]; if (result) result += ', '; // Replace all & by the parent or prefix & with the parent. result += hasAnd(nested) ? nested.replace(parentRegExp, parent) : parent + ' ' + nested; } } return result; } function getOptions(rule, container, options) { // Options has been already created, now we only increase index. if (options) return _extends({}, options, { index: options.index + 1 }); var nestingLevel = rule.options.nestingLevel; nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1; return _extends({}, rule.options, { nestingLevel: nestingLevel, index: container.indexOf(rule) + 1 }); } function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; var container = rule.options.parent; var options = void 0; var replaceRef = void 0; for (var prop in style) { var isNested = hasAnd(prop); var isNestedConditional = prop[0] === '@'; if (!isNested && !isNestedConditional) continue; options = getOptions(rule, container, options); if (isNested) { var selector = replaceParentRefs(prop, rule.selector // Lazily create the ref replacer function just once for // all nested rules within the sheet. );if (!replaceRef) replaceRef = getReplaceRef(container // Replace all $refs. );selector = selector.replace(refRegExp, replaceRef); container.addRule(selector, style[prop], _extends({}, options, { selector: selector })); } else if (isNestedConditional) { container // Place conditional right after the parent rule to ensure right ordering. .addRule(prop, null, options).addRule(rule.key, style[prop], { selector: rule.selector }); } delete style[prop]; } return style; } return { onProcessStyle: onProcessStyle }; } /***/ }), /* 805 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = jssCompose; var _warning = __webpack_require__(770); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Set selector. * * @param {Object} original rule * @param {String} className class string * @return {Boolean} flag, indicating function was successfull or not */ function registerClass(rule, className) { // Skip falsy values if (!className) return true; // Support array of class names `{composes: ['foo', 'bar']}` if (Array.isArray(className)) { for (var index = 0; index < className.length; index++) { var isSetted = registerClass(rule, className[index]); if (!isSetted) return false; } return true; } // Support space separated class names `{composes: 'foo bar'}` if (className.indexOf(' ') > -1) { return registerClass(rule, className.split(' ')); } var parent = rule.options.parent; // It is a ref to a local rule. if (className[0] === '$') { var refRule = parent.getRule(className.substr(1)); if (!refRule) { (0, _warning2.default)(false, '[JSS] Referenced rule is not defined. \r\n%s', rule); return false; } if (refRule === rule) { (0, _warning2.default)(false, '[JSS] Cyclic composition detected. \r\n%s', rule); return false; } parent.classes[rule.key] += ' ' + parent.classes[refRule.key]; return true; } rule.options.parent.classes[rule.key] += ' ' + className; return true; } /** * Convert compose property to additional class, remove property from original styles. * * @param {Rule} rule * @api public */ function jssCompose() { function onProcessStyle(style, rule) { if (!style.composes) return style; registerClass(rule, style.composes); // Remove composes property to prevent infinite loop. delete style.composes; return style; } return { onProcessStyle: onProcessStyle }; } /***/ }), /* 806 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = camelCase; var _hyphenateStyleName = __webpack_require__(807); var _hyphenateStyleName2 = _interopRequireDefault(_hyphenateStyleName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Convert camel cased property names to dash separated. * * @param {Object} style * @return {Object} */ function convertCase(style) { var converted = {}; for (var prop in style) { converted[(0, _hyphenateStyleName2['default'])(prop)] = style[prop]; } if (style.fallbacks) { if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase);else converted.fallbacks = convertCase(style.fallbacks); } return converted; } /** * Allow camel cased property names by converting them back to dasherized. * * @param {Rule} rule */ function camelCase() { function onProcessStyle(style) { if (Array.isArray(style)) { // Handle rules like @font-face, which can have multiple styles in an array for (var index = 0; index < style.length; index++) { style[index] = convertCase(style[index]); } return style; } return convertCase(style); } function onChangeValue(value, prop, rule) { var hyphenatedProp = (0, _hyphenateStyleName2['default'])(prop); // There was no camel case in place if (prop === hyphenatedProp) return value; rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above. return null; } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; } /***/ }), /* 807 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uppercasePattern = /[A-Z]/g; var msPattern = /^ms-/; var cache = {}; function hyphenateStyleName(string) { return string in cache ? cache[string] : cache[string] = string .replace(uppercasePattern, '-$&') .toLowerCase() .replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }), /* 808 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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['default'] = defaultUnit; var _defaultUnits = __webpack_require__(809); var _defaultUnits2 = _interopRequireDefault(_defaultUnits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Clones the object and adds a camel cased property version. */ function addCamelCasedVersion(obj) { var regExp = /(-[a-z])/g; var replace = function replace(str) { return str[1].toUpperCase(); }; var newObj = {}; for (var key in obj) { newObj[key] = obj[key]; newObj[key.replace(regExp, replace)] = obj[key]; } return newObj; } var units = addCamelCasedVersion(_defaultUnits2['default']); /** * Recursive deep style passing function * * @param {String} current property * @param {(Object|Array|Number|String)} property value * @param {Object} options * @return {(Object|Array|Number|String)} resulting value */ function iterate(prop, value, options) { if (!value) return value; var convertedValue = value; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (type === 'object' && Array.isArray(value)) type = 'array'; switch (type) { case 'object': if (prop === 'fallbacks') { for (var innerProp in value) { value[innerProp] = iterate(innerProp, value[innerProp], options); } break; } for (var _innerProp in value) { value[_innerProp] = iterate(prop + '-' + _innerProp, value[_innerProp], options); } break; case 'array': for (var i = 0; i < value.length; i++) { value[i] = iterate(prop, value[i], options); } break; case 'number': if (value !== 0) { convertedValue = value + (options[prop] || units[prop] || ''); } break; default: break; } return convertedValue; } /** * Add unit to numeric values. */ function defaultUnit() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var camelCasedOptions = addCamelCasedVersion(options); function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; for (var prop in style) { style[prop] = iterate(prop, style[prop], camelCasedOptions); } return style; } function onChangeValue(value, prop) { return iterate(prop, value, camelCasedOptions); } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; } /***/ }), /* 809 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Generated jss-default-unit CSS property units * * @type object */ exports['default'] = { 'animation-delay': 'ms', 'animation-duration': 'ms', 'background-position': 'px', 'background-position-x': 'px', 'background-position-y': 'px', 'background-size': 'px', border: 'px', 'border-bottom': 'px', 'border-bottom-left-radius': 'px', 'border-bottom-right-radius': 'px', 'border-bottom-width': 'px', 'border-left': 'px', 'border-left-width': 'px', 'border-radius': 'px', 'border-right': 'px', 'border-right-width': 'px', 'border-spacing': 'px', 'border-top': 'px', 'border-top-left-radius': 'px', 'border-top-right-radius': 'px', 'border-top-width': 'px', 'border-width': 'px', 'border-after-width': 'px', 'border-before-width': 'px', 'border-end-width': 'px', 'border-horizontal-spacing': 'px', 'border-start-width': 'px', 'border-vertical-spacing': 'px', bottom: 'px', 'box-shadow': 'px', 'column-gap': 'px', 'column-rule': 'px', 'column-rule-width': 'px', 'column-width': 'px', 'flex-basis': 'px', 'font-size': 'px', 'font-size-delta': 'px', height: 'px', left: 'px', 'letter-spacing': 'px', 'logical-height': 'px', 'logical-width': 'px', margin: 'px', 'margin-after': 'px', 'margin-before': 'px', 'margin-bottom': 'px', 'margin-left': 'px', 'margin-right': 'px', 'margin-top': 'px', 'max-height': 'px', 'max-width': 'px', 'margin-end': 'px', 'margin-start': 'px', 'mask-position-x': 'px', 'mask-position-y': 'px', 'mask-size': 'px', 'max-logical-height': 'px', 'max-logical-width': 'px', 'min-height': 'px', 'min-width': 'px', 'min-logical-height': 'px', 'min-logical-width': 'px', motion: 'px', 'motion-offset': 'px', outline: 'px', 'outline-offset': 'px', 'outline-width': 'px', padding: 'px', 'padding-bottom': 'px', 'padding-left': 'px', 'padding-right': 'px', 'padding-top': 'px', 'padding-after': 'px', 'padding-before': 'px', 'padding-end': 'px', 'padding-start': 'px', 'perspective-origin-x': '%', 'perspective-origin-y': '%', perspective: 'px', right: 'px', 'shape-margin': 'px', size: 'px', 'text-indent': 'px', 'text-stroke': 'px', 'text-stroke-width': 'px', top: 'px', 'transform-origin': '%', 'transform-origin-x': '%', 'transform-origin-y': '%', 'transform-origin-z': '%', 'transition-delay': 'ms', 'transition-duration': 'ms', 'vertical-align': 'px', width: 'px', 'word-spacing': 'px', // Not existing properties. // Used to avoid issues with jss-expand intergration. 'box-shadow-x': 'px', 'box-shadow-y': 'px', 'box-shadow-blur': 'px', 'box-shadow-spread': 'px', 'font-line-height': 'px', 'text-shadow-x': 'px', 'text-shadow-y': 'px', 'text-shadow-blur': 'px' }; /***/ }), /* 810 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: 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.default = jssExpand; var _props = __webpack_require__(811); 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; } /** * Map values by given prop. * * @param {Array} array of values * @param {String} original property * @param {String} original rule * @return {String} mapped values */ function mapValuesByProp(value, prop, rule) { return value.map(function (item) { return objectToArray(item, prop, rule, false, true); }); } /** * Convert array to nested array, if needed * * @param {Array} array of values * @param {String} original property * @param {Object} sheme, for converting arrays in strings * @param {Object} original rule * @return {String} converted string */ function processArray(value, prop, scheme, rule) { if (scheme[prop] == null) return value; if (value.length === 0) return []; if (Array.isArray(value[0])) return processArray(value[0], prop, scheme); if (_typeof(value[0]) === 'object') { return mapValuesByProp(value, prop, rule); } return [value]; } /** * Convert object to array. * * @param {Object} object of values * @param {String} original property * @param {Object} original rule * @param {Boolean} is fallback prop * @param {Boolean} object is inside array * @return {String} converted string */ function objectToArray(value, prop, rule, isFallback, isInArray) { if (!(_props.propObj[prop] || _props.customPropObj[prop])) return []; var result = []; // Check if exists any non-standart property if (_props.customPropObj[prop]) { value = customPropsToStyle(value, rule, _props.customPropObj[prop], isFallback); } // Pass throught all standart props if (Object.keys(value).length) { for (var baseProp in _props.propObj[prop]) { if (value[baseProp]) { if (Array.isArray(value[baseProp])) { result.push(_props.propArrayInObj[baseProp] === null ? value[baseProp] : value[baseProp].join(' ')); } else result.push(value[baseProp]); continue; } // Add default value from props config. if (_props.propObj[prop][baseProp] != null) { result.push(_props.propObj[prop][baseProp]); } } } if (!result.length || isInArray) return result; return [result]; } /** * Convert custom properties values to styles adding them to rule directly * * @param {Object} object of values * @param {Object} original rule * @param {String} property, that contain partial custom properties * @param {Boolean} is fallback prop * @return {Object} value without custom properties, that was already added to rule */ function customPropsToStyle(value, rule, customProps, isFallback) { for (var prop in customProps) { var propName = customProps[prop]; // If current property doesn't exist already in rule - add new one if (typeof value[prop] !== 'undefined' && (isFallback || !rule.prop(propName))) { var appendedValue = styleDetector(_defineProperty({}, propName, value[prop]), rule)[propName]; // Add style directly in rule if (isFallback) rule.style.fallbacks[propName] = appendedValue;else rule.style[propName] = appendedValue; } // Delete converted property to avoid double converting delete value[prop]; } return value; } /** * Detect if a style needs to be converted. * * @param {Object} style * @param {Object} rule * @param {Boolean} is fallback prop * @return {Object} convertedStyle */ function styleDetector(style, rule, isFallback) { for (var prop in style) { var value = style[prop]; if (Array.isArray(value)) { // Check double arrays to avoid recursion. if (!Array.isArray(value[0])) { if (prop === 'fallbacks') { for (var index = 0; index < style.fallbacks.length; index++) { style.fallbacks[index] = styleDetector(style.fallbacks[index], rule, true); } continue; } style[prop] = processArray(value, prop, _props.propArray); // Avoid creating properties with empty values if (!style[prop].length) delete style[prop]; } } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { if (prop === 'fallbacks') { style.fallbacks = styleDetector(style.fallbacks, rule, true); continue; } style[prop] = objectToArray(value, prop, rule, isFallback); // Avoid creating properties with empty values if (!style[prop].length) delete style[prop]; } // Maybe a computed value resulting in an empty string else if (style[prop] === '') delete style[prop]; } return style; } /** * Adds possibility to write expanded styles. * * @param {Rule} rule * @api public */ function jssExpand() { function onProcessStyle(style, rule) { if (!style || rule.type !== 'style') return style; if (Array.isArray(style)) { // Pass rules one by one and reformat them for (var index = 0; index < style.length; index++) { style[index] = styleDetector(style[index], rule); } return style; } return styleDetector(style, rule); } return { onProcessStyle: onProcessStyle }; } /***/ }), /* 811 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A scheme for converting properties from array to regular style. * All properties listed below will be transformed to a string separated by space. */ var propArray = exports.propArray = { 'background-size': true, 'background-position': true, border: true, 'border-bottom': true, 'border-left': true, 'border-top': true, 'border-right': true, 'border-radius': true, 'border-image': true, 'border-width': true, 'border-style': true, 'border-color': true, 'box-shadow': true, flex: true, margin: true, padding: true, outline: true, 'transform-origin': true, transform: true, transition: true /** * A scheme for converting arrays to regular styles inside of objects. * For e.g.: "{position: [0, 0]}" => "background-position: 0 0;". */ };var propArrayInObj = exports.propArrayInObj = { position: true, // background-position size: true // background-size /** * A scheme for parsing and building correct styles from passed objects. */ };var propObj = exports.propObj = { padding: { top: 0, right: 0, bottom: 0, left: 0 }, margin: { top: 0, right: 0, bottom: 0, left: 0 }, background: { attachment: null, color: null, image: null, position: null, repeat: null }, border: { width: null, style: null, color: null }, 'border-top': { width: null, style: null, color: null }, 'border-right': { width: null, style: null, color: null }, 'border-bottom': { width: null, style: null, color: null }, 'border-left': { width: null, style: null, color: null }, outline: { width: null, style: null, color: null }, 'list-style': { type: null, position: null, image: null }, transition: { property: null, duration: null, 'timing-function': null, timingFunction: null, // Needed for avoiding comilation issues with jss-camel-case delay: null }, animation: { name: null, duration: null, 'timing-function': null, timingFunction: null, // Needed to avoid compilation issues with jss-camel-case delay: null, 'iteration-count': null, iterationCount: null, // Needed to avoid compilation issues with jss-camel-case direction: null, 'fill-mode': null, fillMode: null, // Needed to avoid compilation issues with jss-camel-case 'play-state': null, playState: null // Needed to avoid compilation issues with jss-camel-case }, 'box-shadow': { x: 0, y: 0, blur: 0, spread: 0, color: null, inset: null }, 'text-shadow': { x: 0, y: 0, blur: null, color: null } /** * A scheme for converting non-standart properties inside object. * For e.g.: include 'border-radius' property inside 'border' object. */ };var customPropObj = exports.customPropObj = { border: { radius: 'border-radius', image: 'border-image', width: 'border-width', style: 'border-style', color: 'border-color' }, background: { size: 'background-size', image: 'background-image' }, font: { style: 'font-style', variant: 'font-variant', weight: 'font-weight', stretch: 'font-stretch', size: 'font-size', family: 'font-family', lineHeight: 'line-height', // Needed to avoid compilation issues with jss-camel-case 'line-height': 'line-height' }, flex: { grow: 'flex-grow', basis: 'flex-basis', direction: 'flex-direction', wrap: 'flex-wrap', flow: 'flex-flow', shrink: 'flex-shrink' }, align: { self: 'align-self', items: 'align-items', content: 'align-content' }, grid: { 'template-columns': 'grid-template-columns', templateColumns: 'grid-template-columns', 'template-rows': 'grid-template-rows', templateRows: 'grid-template-rows', 'template-areas': 'grid-template-areas', templateAreas: 'grid-template-areas', template: 'grid-template', 'auto-columns': 'grid-auto-columns', autoColumns: 'grid-auto-columns', 'auto-rows': 'grid-auto-rows', autoRows: 'grid-auto-rows', 'auto-flow': 'grid-auto-flow', autoFlow: 'grid-auto-flow', row: 'grid-row', column: 'grid-column', 'row-start': 'grid-row-start', rowStart: 'grid-row-start', 'row-end': 'grid-row-end', rowEnd: 'grid-row-end', 'column-start': 'grid-column-start', columnStart: 'grid-column-start', 'column-end': 'grid-column-end', columnEnd: 'grid-column-end', area: 'grid-area', gap: 'grid-gap', 'row-gap': 'grid-row-gap', rowGap: 'grid-row-gap', 'column-gap': 'grid-column-gap', columnGap: 'grid-column-gap' } }; /***/ }), /* 812 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = jssVendorPrefixer; var _cssVendor = __webpack_require__(813); var vendor = _interopRequireWildcard(_cssVendor); 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; } } /** * Add vendor prefix to a property name when needed. * * @param {Rule} rule * @api public */ function jssVendorPrefixer() { function onProcessRule(rule) { if (rule.type === 'keyframes') { rule.key = '@' + vendor.prefix.css + rule.key.substr(1); } } function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; for (var prop in style) { var value = style[prop]; var changeProp = false; var supportedProp = vendor.supportedProperty(prop); if (supportedProp && supportedProp !== prop) changeProp = true; var changeValue = false; var supportedValue = vendor.supportedValue(supportedProp, value); if (supportedValue && supportedValue !== value) changeValue = true; if (changeProp || changeValue) { if (changeProp) delete style[prop]; style[supportedProp || prop] = supportedValue || value; } } return style; } function onChangeValue(value, prop) { return vendor.supportedValue(prop, value); } return { onProcessRule: onProcessRule, onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; } /***/ }), /* 813 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.supportedValue = exports.supportedProperty = exports.prefix = undefined; var _prefix = __webpack_require__(814); var _prefix2 = _interopRequireDefault(_prefix); var _supportedProperty = __webpack_require__(815); var _supportedProperty2 = _interopRequireDefault(_supportedProperty); var _supportedValue = __webpack_require__(817); var _supportedValue2 = _interopRequireDefault(_supportedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { prefix: _prefix2['default'], supportedProperty: _supportedProperty2['default'], supportedValue: _supportedValue2['default'] }; /** * CSS Vendor prefix detection and property feature testing. * * @copyright Oleg Slobodskoi 2015 * @website https://github.com/jsstyles/css-vendor * @license MIT */ exports.prefix = _prefix2['default']; exports.supportedProperty = _supportedProperty2['default']; exports.supportedValue = _supportedValue2['default']; /***/ }), /* 814 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _isInBrowser = __webpack_require__(787); var _isInBrowser2 = _interopRequireDefault(_isInBrowser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var js = ''; /** * Export javascript style and css style vendor prefixes. * Based on "transform" support test. */ var css = ''; // We should not do anything if required serverside. if (_isInBrowser2['default']) { // Order matters. We need to check Webkit the last one because // other vendors use to add Webkit prefixes to some properties var jsCssMap = { Moz: '-moz-', // IE did it wrong again ... ms: '-ms-', O: '-o-', Webkit: '-webkit-' }; var style = document.createElement('p').style; var testProp = 'Transform'; for (var key in jsCssMap) { if (key + testProp in style) { js = key; css = jsCssMap[key]; break; } } } /** * Vendor prefix string for the current browser. * * @type {{js: String, css: String}} * @api public */ exports['default'] = { js: js, css: css }; /***/ }), /* 815 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = supportedProperty; var _isInBrowser = __webpack_require__(787); var _isInBrowser2 = _interopRequireDefault(_isInBrowser); var _prefix = __webpack_require__(814); var _prefix2 = _interopRequireDefault(_prefix); var _camelize = __webpack_require__(816); var _camelize2 = _interopRequireDefault(_camelize); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var el = void 0; var cache = {}; if (_isInBrowser2['default']) { el = document.createElement('p'); /** * We test every property on vendor prefix requirement. * Once tested, result is cached. It gives us up to 70% perf boost. * http://jsperf.com/element-style-object-access-vs-plain-object * * Prefill cache with known css properties to reduce amount of * properties we need to feature test at runtime. * http://davidwalsh.name/vendor-prefix */ var computed = window.getComputedStyle(document.documentElement, ''); for (var key in computed) { if (!isNaN(key)) cache[computed[key]] = computed[key]; } } /** * Test if a property is supported, returns supported property with vendor * prefix if required. Returns `false` if not supported. * * @param {String} prop dash separated * @return {String|Boolean} * @api public */ function supportedProperty(prop) { // For server-side rendering. if (!el) return prop; // We have not tested this prop yet, lets do the test. if (cache[prop] != null) return cache[prop]; // Camelization is required because we can't test using // css syntax for e.g. in FF. // Test if property is supported as it is. if ((0, _camelize2['default'])(prop) in el.style) { cache[prop] = prop; } // Test if property is supported with vendor prefix. else if (_prefix2['default'].js + (0, _camelize2['default'])('-' + prop) in el.style) { cache[prop] = _prefix2['default'].css + prop; } else { cache[prop] = false; } return cache[prop]; } /***/ }), /* 816 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = camelize; var regExp = /[-\s]+(.)?/g; /** * Convert dash separated strings to camel cased. * * @param {String} str * @return {String} */ function camelize(str) { return str.replace(regExp, toUpper); } function toUpper(match, c) { return c ? c.toUpperCase() : ''; } /***/ }), /* 817 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = supportedValue; var _isInBrowser = __webpack_require__(787); var _isInBrowser2 = _interopRequireDefault(_isInBrowser); var _prefix = __webpack_require__(814); var _prefix2 = _interopRequireDefault(_prefix); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var cache = {}; var el = void 0; if (_isInBrowser2['default']) el = document.createElement('p'); /** * Returns prefixed value if needed. Returns `false` if value is not supported. * * @param {String} property * @param {String} value * @return {String|Boolean} * @api public */ function supportedValue(property, value) { // For server-side rendering. if (!el) return value; // It is a string or a number as a string like '1'. // We want only prefixable values here. if (typeof value !== 'string' || !isNaN(parseInt(value, 10))) return value; var cacheKey = property + value; if (cache[cacheKey] != null) return cache[cacheKey]; // IE can even throw an error in some cases, for e.g. style.content = 'bar' try { // Test value as it is. el.style[property] = value; } catch (err) { cache[cacheKey] = false; return false; } // Value is supported as it is. if (el.style[property] !== '') { cache[cacheKey] = value; } else { // Test value with vendor prefix. value = _prefix2['default'].css + value; // Hardcode test to convert "flex" to "-ms-flexbox" for IE10. if (value === '-ms-flex') value = '-ms-flexbox'; el.style[property] = value; // Value is supported with vendor prefix. if (el.style[property] !== '') cache[cacheKey] = value; } if (!cache[cacheKey]) cache[cacheKey] = false; // Reset style value. el.style[property] = ''; return cache[cacheKey]; } /***/ }), /* 818 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = jssPropsSort; /** * Sort props by length. */ function jssPropsSort() { function sort(prop0, prop1) { return prop0.length - prop1.length; } function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; var newStyle = {}; var props = Object.keys(style).sort(sort); for (var prop in props) { newStyle[props[prop]] = style[props[prop]]; } return newStyle; } return { onProcessStyle: onProcessStyle }; } /***/ }), /* 819 */, /* 820 */, /* 821 */, /* 822 */, /* 823 */, /* 824 */, /* 825 */, /* 826 */, /* 827 */, /* 828 */, /* 829 */, /* 830 */, /* 831 */, /* 832 */, /* 833 */, /* 834 */, /* 835 */, /* 836 */, /* 837 */, /* 838 */, /* 839 */, /* 840 */, /* 841 */, /* 842 */, /* 843 */, /* 844 */, /* 845 */, /* 846 */, /* 847 */, /* 848 */, /* 849 */, /* 850 */, /* 851 */, /* 852 */, /* 853 */, /* 854 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; /** * This function feeds real-time data to real-time gauges. In single value gauges (LEDs, Bulb, Cylinder, * Thermometer) the function takes a numeric value as the parameter. For Angular gauge and Horizontal Linear * gauge, this function accepts two parameters - the dial number and the value to update. * * @group chart-realtime * @see FusionCharts#feedData * @see FusionCharts#getData * @param {string} value * @param {string} label */ function _getData() { var iapi = this, components = iapi.getChildren(), dataset = iapi.getDatasets(), xAxis = components.xAxis && components.xAxis[0] || components.scale, length, i, j, store = [], maxLength = 0, data, innerStore; if (dataset) { length = dataset.length; // Finding the dataset with maximum length for (i = 0; i < length; i++) { maxLength = Math.max(maxLength, dataset[i].components.data.length); } for (i = 0; i < maxLength; i++) { innerStore = store[i] = []; innerStore[0] = xAxis.getLabel(i).label; for (j = 1; j <= length; j++) { data = dataset[j - 1].components.data[i]; innerStore[j] = data && data.config.setValue; } } return store; } } exports["default"] = _getData; /***/ }), /* 855 */, /* 856 */, /* 857 */, /* 858 */, /* 859 */, /* 860 */, /* 861 */, /* 862 */, /* 863 */, /* 864 */, /* 865 */, /* 866 */, /* 867 */, /* 868 */, /* 869 */, /* 870 */, /* 871 */, /* 872 */, /* 873 */, /* 874 */, /* 875 */, /* 876 */, /* 877 */, /* 878 */, /* 879 */, /* 880 */, /* 881 */, /* 882 */, /* 883 */, /* 884 */, /* 885 */, /* 886 */, /* 887 */, /* 888 */, /* 889 */, /* 890 */, /* 891 */, /* 892 */, /* 893 */, /* 894 */, /* 895 */, /* 896 */, /* 897 */, /* 898 */, /* 899 */, /* 900 */, /* 901 */, /* 902 */, /* 903 */, /* 904 */, /* 905 */, /* 906 */, /* 907 */, /* 908 */, /* 909 */, /* 910 */, /* 911 */, /* 912 */, /* 913 */, /* 914 */, /* 915 */, /* 916 */, /* 917 */, /* 918 */, /* 919 */, /* 920 */, /* 921 */, /* 922 */, /* 923 */, /* 924 */, /* 925 */, /* 926 */, /* 927 */, /* 928 */, /* 929 */, /* 930 */, /* 931 */, /* 932 */, /* 933 */, /* 934 */, /* 935 */, /* 936 */, /* 937 */, /* 938 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { _createColorRangeManager(chart); }; var _colorrange = __webpack_require__(939); var _colorrange2 = _interopRequireDefault(_colorrange); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Function to create and configure color-manager and attach * color-manager as a child of chart. * @param {Object} chart chart instance */ function _createColorRangeManager(chart) { var manager = chart.getChildren('colorManager'); if (!chart.getFromEnv('dataSource').colorrange) { manager && (manager[0].config.legendItemIds = []); chart.deleteFromEnv('colorManager'); return; } if (manager) { chart.addToEnv('colorManager', manager[0]); manager[0].configure(); return; } manager = new _colorrange2['default'](); chart.attachChild(manager, 'colorManager'); chart.addToEnv('colorManager', manager); manager.configure(); } /***/ }), /* 939 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _colorBucket = __webpack_require__(940); var _colorBucket2 = _interopRequireDefault(_colorBucket); var _gradientColorRange = __webpack_require__(941); var _gradientColorRange2 = _interopRequireDefault(_gradientColorRange); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* * Returns the opposite LIGHT color of a color. If the color is alraedy light, wont get much difference. * * @param code {String} - color code in string * @return {String} - Lightest (approx) color code of the color sent */ function getOppositeColor(code) { return (0, _lib.getLightColor)(code, 1); } /* * Takes care of sanity checking of the color to some extent. * If no color is passed, ie called as getValidHexColor() it returns the default color. If incorrect color is passed * it returns false. * * @param code {String} - color code in string * @return {String | Boolean} - false if invalid color is passed, otherwise the same color or default color if no * no color is passed */ function getValidHexColor(code) { var color = code || DEF_COLOR; return (0, _lib.getValidColor)(color) || DEF_COLOR; } var TRACKER_FILL = 'rgba(192,192,192,' + (_lib.isIE ? 0.002 : 0.000001) + ')', UNDEF = void 0, PERCENT_STR = '%', DEF_COLOR = '#000000', legendManager = function () { var chart, defaultConf = {}; defaultConf.legendCarpetConf = { spreadFactor: 0.85, allowDrag: false, captionAlignment: 'center', padding: { v: 3, h: 3 }, style: { 'fill': '#e4d9c1', 'stroke': '#c4b89d' } }; defaultConf.legendCaptionConf = { spreadFactor: 0.2, padding: { v: 2, h: 2 }, style: { fill: '#786B50', fontFamily: 'sans-serif', fontSize: '12px', fontWeight: 'bold', fontStyle: 'normal' }, bound: { style: { stroke: 'none' } } }; defaultConf.legendBodyConf = { spreadFactor: 0.8, padding: { v: 2, h: 2 }, bound: { style: { stroke: 'none' } } }; defaultConf.legendAxisConf = { legendAxisHeight: 11, spreadFactor: 0.4, padding: { v: 1, h: 1 }, style: { stroke: 'none', 'stroke-opacity': 0, 'stroke-width': 1 }, line: { grooveLength: 3, offset: 8, style: { stroke: 'rgba(255, 255, 255, 0.65)', 'stroke-width': 1.5 } }, shadow: { style: { stroke: 'none', fill: (0, _lib.toRaphaelColor)({ FCcolor: { alpha: '25,0,0', angle: 360, color: '000000,FFFFFF,FFFFFF', ratio: '0,30,40' } }) } }, bound: { style: { stroke: 'none' } } }; defaultConf.sliderGroupConf = { showTooltip: 1, outerCircle: { rFactor: 1.4, style: { fill: TRACKER_FILL, stroke: '#757575', 'stroke-width': 3 } }, innerCircle: { rFactor: 0.65, style: { fill: TRACKER_FILL, stroke: '#FFFFFF' } } }; defaultConf.axisTextItemConf = { spreadFactor: 0.3, padding: { v: 1, h: 1 }, style: { fill: '#786B50', fontFamily: 'sans-serif', fontSize: '12px', fontWeight: 'normal', fontStyle: 'normal' } }; function normalizePreprocessedData(confArr) { var numberFormatter = chart.getFromEnv('number-formatter'), index, length, rawVal; for (index = 0, length = confArr.length; index < length; index++) { rawVal = confArr[index].maxvalue; if (!rawVal) { continue; } confArr[index].maxvalue = numberFormatter.getCleanValue(rawVal); } } return { init: function init(options) { chart = options.chart; // layers = chart.graphics; // components = chart.components; }, // setConf: function (conf) { // config = conf; // }, legacyDataParser: function legacyDataParser(data, extremes) { var colormanagerConf = {}, numberFormatter = chart.getFromEnv('number-formatter'), dataSource = chart.getFromEnv('dataSource'), datasets = dataSource.dataset, mapData = dataSource.data, colorConfArr, colorConf, startColor, endColor, index, validColor, length, colorRange, value, dispValue, mapByPercent, isMaxValPresent; extremes = extremes || {}; if (!data) { return false; } /* * dsmin: minimum value among all dataset/data * dsmax: maximum value among all dataset/data * crmin: colorrange minvalue * crmax: colorrange maxvalue * cmin: minimum minvalue among all objects in color(array) property of colorrange * cmax: maximum maxvalue among all objects in color(array) property of colorrange * P: Present * X: Not Present * * ______________________________________________________________________________________________ * Cases | dsmin | dsmax | crmin | crmax | cmin | cmax | Range * _______|_________|_______|_______|_______|_______|_______|____________________________________ * 1 | P | P | P | P | P | P | [crmin, cmax] * 2 | P | P | P | P | P | X | [crmin, crmax] * 3 | P | P | P | P | X | P | [crmin, cmax] * 4 | P | P | P | P | X | X | [crmin, crmax] * 5 | P | P | P | X | P/X | P | [crmin, cmax] * 6 | P | P | P | X | P/X | X | [crmin, dsmax] * 7 | P | P | X | P | P/X | P | [dsmin, cmax] * 8 | P | P | X | P | P/X | X | [dsmin, crmax] * 9 | P | P | X | X | P/X | X | [dsmin, dsmax] * 10 | X | X | X | X | X | X | [0, 100] (no data specified) * 11 | P | X | X | X | X | X | [0, 100] (only 1 data is specified) * ============================================================================================== * * Scope of improvements:- * 1) cmin must be taken into account when cmax is not specified to calculate gradient stops * 2) cmin must be taken into account when cmax, crmin,crmax is not specified to calculate gradient stops * 3) gradient min must be min(crmin, cmin) * 4) gradient max must be max(crmax, cmax) * 5) Seperate parsing for charts(heatmap, maps) should not be done for calculating extremes */ if (chart.defaultDatasetType === 'maps' && (extremes.min === UNDEF || extremes.max === UNDEF)) { extremes = { min: Infinity, max: -Infinity }; mapData && mapData.forEach(function (dataObj) { extremes.min = Math.min(extremes.min, (0, _lib.pluckNumber)(dataObj.value, extremes.min)); extremes.max = Math.max(extremes.max, (0, _lib.pluckNumber)(dataObj.value, extremes.min)); }); } else if (chart.getName() === 'HeatMap' && (extremes.min === UNDEF || extremes.max === UNDEF)) { extremes = { min: Infinity, max: -Infinity }; datasets.forEach(function (dataset) { dataset.data && dataset.data.forEach(function (dataObj) { extremes.min = Math.min(extremes.min, (0, _lib.pluckNumber)(dataObj.value, extremes.min)); extremes.max = Math.max(extremes.max, (0, _lib.pluckNumber)(dataObj.value, extremes.max)); }); }); } colormanagerConf.mapByPercent = mapByPercent = !!(0, _lib.pluckNumber)(data.mapbypercent, 0); colorConfArr = data.color || []; if (data.minvalue === UNDEF) { data.minvalue = extremes.min !== UNDEF ? mapByPercent ? 0 : extremes.min : 0; } if (data.maxvalue === UNDEF) { data.maxvalue = extremes.max !== UNDEF ? mapByPercent ? 100 : extremes.max : 100; } if (data.maxvalue === data.minvalue || extremes.min === Infinity || extremes.max === -Infinity) { data.minvalue = 0; data.maxvalue = 100; } isMaxValPresent = false; for (index = 0, length = colorConfArr.length; index < length; index++) { if (colorConfArr[index].maxvalue) { isMaxValPresent = true; break; } } if (!isMaxValPresent) { colorConfArr = []; } startColor = data.code; colorRange = colormanagerConf.colorRange = []; colormanagerConf.gradient = !!(0, _lib.pluckNumber)(data.gradient, 1); // If no additional color array is provided as part of generating the gradient, creates the start and // end value to create the gradient if (!colorConfArr.length) { if (startColor) { // If start color is mentioned, create a gradient starting from default color to the mentioned // color endColor = getValidHexColor(startColor); startColor = getValidHexColor(); } else { // If no color is mentioned, create a gradient of two opposite color startColor = getValidHexColor(); endColor = getOppositeColor(startColor); } colorConfArr.push({ code: endColor, maxvalue: data.maxvalue, label: UNDEF }); } else { startColor = getValidHexColor(startColor); } normalizePreprocessedData(colorConfArr); colorConfArr = colorConfArr.sort(function (m, n) { return m.maxvalue - n.maxvalue; }); value = dispValue = data.minvalue && numberFormatter.getCleanValue(data.minvalue); dispValue = (value !== UNDEF || value !== null) && (mapByPercent ? value + PERCENT_STR : numberFormatter.legendValue(value)); colorRange.push({ code: (0, _lib.dehashify)(startColor), value: value, displayValue: dispValue, label: data.startlabel }); for (index = 0, length = colorConfArr.length; index < length; index++) { colorConf = colorConfArr[index]; validColor = getValidHexColor(colorConf.code || colorConf.color); value = dispValue = colorConf.maxvalue; if (isNaN(parseInt(value, 10))) { continue; } dispValue = (value !== UNDEF || value !== null) && (mapByPercent ? value + PERCENT_STR : numberFormatter.legendValue(value)); colorRange.push({ code: (0, _lib.dehashify)(validColor), value: value, displayValue: dispValue, label: colorConf.label || colorConf.displayvalue }); } colorRange[colorRange.length - 1].label = data.endlabel || colorConf.label; return colormanagerConf; }, getDefaultConf: function getDefaultConf(key) { return defaultConf[key]; } }; }(); var ColorRange = function (_ComponentInterface) { _inherits(ColorRange, _ComponentInterface); /** * constructor of ColorRange */ function ColorRange() { _classCallCheck(this, ColorRange); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this.datasource = {}; _this.config.legendItemIds = []; return _this; } /** * This function configures the legend and colorRange * according to the chart configuration. */ ColorRange.prototype.configure = function configure() { var colorManager = this, chart = this.getFromEnv('chart'), colorrange = void 0, isMap = chart.defaultDatasetType === 'maps', isTreeMap = chart.getName() === 'TreeMap', legendType = void 0, mapByCategory = this.getFromEnv('dataSource').chart.mapbycategory, numberFormatter = chart.getFromEnv('number-formatter'), nData = void 0, showLegend = chart.config.showLegend, colorRangeInstance = chart.getChildren('colorRange') && chart.getChildren('colorRange')[0]; chart.addToEnv('colorManager', colorManager); colorManager.datasource = chart.getFromEnv('dataSource'); colorrange = colorManager.datasource.colorrange; // remove colorrange instance if any colorRangeInstance && colorRangeInstance.remove({ instant: true }); if (!showLegend) { colorManager.config.legendItemIds = []; } if (isMap) { if (colorrange.gradient && Number(colorrange.gradient)) { legendType = 'gradient'; } else if (colorrange.color) { legendType = 'icon'; } else { legendType = 'none'; } } else if (isTreeMap) { legendType = 'gradient'; } else { if (colorrange.gradient && colorrange.gradient != '0' && !Number(mapByCategory)) { legendType = 'gradient'; } else { legendType = 'icon'; } } switch (legendType) { case 'gradient': legendManager.init({ chart: chart }); nData = legendManager.legacyDataParser(colorrange); (0, _lib.componentFactory)(chart, _gradientColorRange2['default'], 'colorRange', 1, [nData]); colorRangeInstance = chart.getChildren('colorRange')[0]; chart.addToEnv('colorRange', colorRangeInstance); if (!nData) { // If no valid data is present, sets a flag not to draw the legend. // This will be read by subsequent calls. colorRangeInstance._dontPlot = true; } colorManager.config.legendItemIds = []; // configure gradient legend colorManager._configureGradientLegend(colorRangeInstance); break; case 'icon': (0, _lib.componentFactory)(chart, _colorBucket2['default'], 'colorRange', 1, [{ colorRange: colorrange, sortLegend: 0, mapByCategory: (0, _lib.pluckNumber)(mapByCategory, 0), defaultColor: 'cccccc', numberFormatter: numberFormatter }]); chart.addToEnv('colorRange', chart.getChildren('colorRange')[0]); // create legend-items and configure them showLegend && colorManager._addLegendItems(); break; case 'none': chart.deleteFromEnv('colorManager'); colorManager.config.legendItemIds = []; } }; /** * Sets color range of gradient legend and fires legendupdate event * when gradient legend limits are changed. * @param {Object} colorRangeInstance - the colorrange instace i.e. gradient-colorrange */ ColorRange.prototype._configureGradientLegend = function _configureGradientLegend(colorRangeInstance) { var colorManager = this, chart = colorManager.getFromEnv('chart'), gradientLegend = chart.getFromEnv('gLegend'); if (!gradientLegend) { return; } gradientLegend.setColorRange(colorRangeInstance); // listen to event rangeUpdated fired by gradient legend and notify dataset by firing legendUpdate event colorManager.addExtEventListener('rangeUpdated', function (e, d) { colorManager.fireEvent('legendUpdate', { 'original-event': e, 'maxMinArray': d, 'component': 'gradientlegend' }); }, gradientLegend); }; /** * Add legend-items and add legend interactivity to the items on click. * @param {Object} legend - legend component */ ColorRange.prototype._addLegendItems = function _addLegendItems() { var colorManager = this, config = colorManager.config, chart = colorManager.getFromEnv('chart'), legend = chart.getChildren('legend')[0], colorrange = chart.getFromEnv('colorRange'), colorMap = colorrange.colorArr, fillColor = void 0, lightColor = void 0, len = colorMap.length, legendItem = void 0, i = void 0, lconfig = void 0; // create legend-items according to the colors of colorrange in datasource for (i = 0; i < len; i++) { lconfig = { label: (0, _lib.pluck)(colorMap[i].label, colorMap[i].displayvalue), datasetObj: colorMap[i], index: i }; lightColor = (0, _lib.getLightColor)(colorMap[i].code, 40); fillColor = { FCcolor: { color: colorMap[i].code + ',' + colorMap[i].code + ',' + lightColor, ratio: '0,70,30', angle: 270, alpha: '100,100,100' } }; legendItem = legend.getItem(config.legendItemIds[i]); if (!legendItem) { config.legendItemIds.push(legend.createItem(colorManager)); legendItem = legend.getItem(config.legendItemIds[i]); legendItem.addEventListener('fc-click', legendItem.itemClickFn); } // remove hidden state of legend item legendItem.removeLegendState('hidden'); colorMap[i].legendItemId = legendItem && legendItem.getId(); legendItem.configure(lconfig); legendItem.setStateCosmetics('default', { symbol: { fill: (0, _lib.toRaphaelColor)(fillColor), rawFillColor: colorMap[i].code } }); } for (i = len; i < config.legendItemIds.length; i++) { legend.disposeItem(config.legendItemIds[i]); } config.legendItemIds.splice(len); }; /** * Show or hides legend items and fires legendUpdated event * when a the legend-item is clicked. * @param {Object} legendItem - the legend-item * @param {Object} colorObj - color map object with which legendItem is mapped */ ColorRange.prototype.legendInteractivity = function legendInteractivity(legendItem) { var colorManager = this, colorObj = colorManager.getFromEnv('colorRange').colorArr[legendItem.config.index]; colorManager.fireEvent('legendUpdate', { 'legendItem': legendItem, 'colorObj': colorObj, 'component': 'legend' }); }; /** * Returns a color obejct which contains color details. * @param {number} value * @returns {Object} color object containing color details */ ColorRange.prototype.getColor = function getColor(value) { var colorManager = this, colorrange = colorManager.datasource.colorrange, mapbycategory = colorManager.datasource.chart.mapbycategory; return !Number(mapbycategory) && Number(colorrange.gradient) ? { code: colorManager.getColorByValue(value) } : colorManager.getColorObj(value); }; ColorRange.prototype.getValueRatio = function getValueRatio() { return this.getFromEnv('colorRange').getValueRatio(); }; ColorRange.prototype.getCumulativeValueRatio = function getCumulativeValueRatio() { return this.getFromEnv('colorRange').getCumulativeValueRatio(); }; ColorRange.prototype.getBoxFill = function getBoxFill(isVertical) { return this.getFromEnv('colorRange').getBoxFill(isVertical); }; ColorRange.prototype.getColorByValue = function getColorByValue(value) { return this.getFromEnv('colorRange').getColorByValue(value); }; ColorRange.prototype.getColorObj = function getColorObj(value) { return this.getFromEnv('colorRange').getColorObj(value); }; return ColorRange; }(_componentInterface.ComponentInterface); exports['default'] = ColorRange; /***/ }), /* 940 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var getTransitColor = function getTransitColor(colorArr1, colorArr2, transitOffset) { var R1 = colorArr1[0], G1 = colorArr1[1], B1 = colorArr1[2], R = R1 + (colorArr2[0] - R1) * transitOffset, G = G1 + (colorArr2[1] - G1) * transitOffset, B = B1 + (colorArr2[2] - B1) * transitOffset; return { hex: (_lib.COLOR_BLACK + (R << 16 | G << 8 | B).toString(16)).slice(-6), rgb: [R, G, B] }; }, UNDEF = void 0; /** * Creates ColorBucket class for color range */ var ColorBucket = function (_ComponentInterface) { _inherits(ColorBucket, _ComponentInterface); /** * Constructor fn to intantiate ColorBucket object */ function ColorBucket() { _classCallCheck(this, ColorBucket); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); var colorBucket = _this; colorBucket.mapByCategory = false; colorBucket.colorArr = []; colorBucket.noValidRange = true; colorBucket.sortLegend = false; return _this; } /** * Set default configurations */ ColorBucket.prototype.__setDefaultConfig = function __setDefaultConfig() { _ComponentInterface.prototype.__setDefaultConfig.call(this); this.config.defaultObj = { code: 'CCCCCC', alpha: '100' }; }; /** * Sets the type of the component * @return {string} type */ ColorBucket.prototype.getType = function getType() { return 'colorComponent'; }; /** * Sets the name of the component * @return {string} name */ ColorBucket.prototype.getName = function getName() { return 'colorBucket'; }; /** * Configure the ColorBucket component * @param {Object} options consists of color range and it's dependencies */ ColorBucket.prototype.configure = function configure(options) { if (!options) { return; } var colorBucket = this, mapByCategory = colorBucket.mapByCategory, numberFormatter = options.numberFormatter, colorRange = options.colorRange || {}, color = (0, _lib.extend2)([], colorRange.color), chart = this.getLinkedParent(), dataSource = colorBucket.getFromEnv('dataSource'), paletteIndex = Math.min(Math.max((0, _lib.pluckNumber)(dataSource.chart.palette, 0) - 1, 0), 4), defaultPaletteOptions = chart.defaultPaletteOptions && chart.defaultPaletteOptions.paletteColors[paletteIndex], upperLimit = (0, _lib.pluckNumber)(numberFormatter.getCleanValue(colorRange.maxvalue), Infinity), lowerLimit = (0, _lib.pluckNumber)(numberFormatter.getCleanValue(colorRange.minvalue), -Infinity), colorArr = colorBucket.colorArr, colorCount = void 0, i = void 0, code = void 0, alpha = void 0, borderalpha = void 0, bordercolor = void 0, colorObj = void 0, tempvalue = void 0, maxValue = void 0, minValue = void 0, colorLabel = void 0; if (options.mapByCategory !== UNDEF) { mapByCategory = colorBucket.mapByCategory = !!Number(options.mapByCategory); } // filter out invalid color objects if (!mapByCategory) { color = color.filter(function (obj) { return obj.minvalue || obj.maxvalue; }); } else { color = color.filter(function (obj) { return obj.code || obj.color; }); } // create limits and labels for each color array if not defined color.forEach(function (obj) { if (obj.minvalue && obj.maxvalue && +obj.maxvalue < +obj.minvalue) { tempvalue = obj.maxvalue; obj.maxvalue = obj.minvalue; obj.minvalue = tempvalue; } if (!obj.minvalue) { obj.minvalue = minValue = lowerLimit; maxValue = numberFormatter.getCleanValue(obj.maxvalue); // range label denotes its range which can be set as the label of the color object obj.rangeLabel = minValue === -Infinity ? '<' + numberFormatter.dataLabels(maxValue) : numberFormatter.dataLabels(minValue) + '-' + numberFormatter.dataLabels(maxValue); } else if (!obj.maxvalue) { minValue = numberFormatter.getCleanValue(obj.minvalue); obj.maxvalue = maxValue = upperLimit; // range label denotes its range which can be set as the label of the color object obj.rangeLabel = maxValue === Infinity ? '>' + numberFormatter.dataLabels(minValue) : numberFormatter.dataLabels(minValue) + '-' + numberFormatter.dataLabels(maxValue); } else { minValue = numberFormatter.getCleanValue(obj.minvalue); maxValue = numberFormatter.getCleanValue(obj.maxvalue); // range label denotes its range which can be set as the label of the color object obj.rangeLabel = numberFormatter.dataLabels(minValue) + '-' + numberFormatter.dataLabels(maxValue); } }); // sort the new color Array at first with maxvalue and then with minvalue so that two objects with same // minvalue are sorted according to to their maxvalue color.sort(function (ob1, ob2) { return +ob1.minvalue === +ob2.minvalue ? ob1.maxvalue - ob2.maxvalue : ob1.minvalue - ob2.minvalue; }); if (color && (colorCount = color.length)) { colorArr.length = 0; for (i = 0; i < colorCount; i += 1) { colorObj = color[i]; code = (0, _lib.pluck)(colorObj.color, colorObj.code, defaultPaletteOptions && defaultPaletteOptions[i]); alpha = (0, _lib.pluck)(colorObj.alpha); bordercolor = (0, _lib.pluck)(colorObj.bordercolor); borderalpha = (0, _lib.pluck)(colorObj.borderalpha, 100); maxValue = (0, _lib.pluckNumber)(colorObj.maxvalue); minValue = (0, _lib.pluckNumber)(colorObj.minvalue); colorLabel = (0, _lib.pluck)(colorObj.label, colorObj.displayvalue, colorObj.rangeLabel); // add valid color if (code && maxValue >= minValue || mapByCategory && colorLabel) { colorArr.push({ code: code, alpha: alpha || '100', oriAlpha: alpha, maxvalue: maxValue, minvalue: minValue, label: (0, _lib.parseUnsafeString)(colorLabel), labelId: colorLabel.toLowerCase(), bordercolor: bordercolor, borderAlpha: borderalpha, name: colorObj.name }); } } colorBucket.sortedColorArr = colorBucket.colorArr.slice(0); } else { colorBucket.noValidRange = true; colorBucket.colorArr = []; colorBucket.sortedColorArr = []; } }; /** * Fetch color against a given value in a color range * @param {number} value value to get color * @return {Object} object consists of color code, alpha against provided value */ ColorBucket.prototype.getColorObj = function getColorObj(value) { // when value is not defined then it is not in range if (value === UNDEF) { return { outOfRange: true }; } var colorBucket = this, maxContainingRange = void 0, colorArr = colorBucket.sortedColorArr, i = colorBucket.gradient ? 1 : 0, colorObj = colorArr[i], transitOffset = void 0; // if gradient legend the get the transition color if (colorBucket.mapByCategory) { value = (0, _lib.parseUnsafeString)(value).toLowerCase() || value.toString().toLowerCase(); while (colorObj) { if (colorObj.labelId === value || colorObj.maxvalue >= value && colorObj.minvalue <= value) { return { code: colorObj.code, alpha: colorObj.alpha || '100', oriAlpha: colorObj.oriAlpha, seriesIndex: i, legendItemId: colorObj.legendItemId }; } i += 1; colorObj = colorArr[i]; } // out of range value return { outOfRange: true }; } else if (colorBucket.gradient) { // within range // return the color code if (colorBucket.scaleMin <= value && colorBucket.scaleMax >= value) { while (colorObj && colorObj.maxvalue < value) { i += 1; colorObj = colorArr[i]; } transitOffset = (value - colorObj.minvalue) / colorObj.range; return { code: getTransitColor(colorArr[i - 1].codeRGB, colorObj.codeRGB, transitOffset).hex }; } else { // outof range value return { outOfRange: true }; } } else { while (colorObj) { // if maxContainingRange is defined, then already a range is present whose maxValue is equal to the value. if (value < colorObj.minvalue && !maxContainingRange) { if (i === 0) { // if current color object is the first color object then return it return { code: colorObj.code, alpha: colorObj.alpha || '100', oriAlpha: colorObj.oriAlpha, seriesIndex: i, name: colorObj.name, label: colorObj.label, outOfRange: true, bordercolor: colorObj.bordercolor, borderalpha: colorObj.borderAlpha }; } else { // else return the previous color object return { code: colorArr[i - 1].code, alpha: colorArr[i - 1].alpha || '100', oriAlpha: colorArr[i - 1].oriAlpha, seriesIndex: i, name: colorArr[i - 1].name, label: colorArr[i - 1].label, outOfRange: true, bordercolor: colorArr[i - 1].bordercolor, borderalpha: colorArr[i - 1].borderAlpha }; } } if (value > colorObj.maxvalue && i === colorArr.length - 1) { // if it is the last color object then return it return { code: colorObj.code, alpha: colorObj.alpha || '100', oriAlpha: colorObj.oriAlpha, seriesIndex: i, name: colorObj.name, label: colorObj.label, outOfRange: true, bordercolor: colorObj.bordercolor, borderalpha: colorObj.borderAlpha }; } // lower limit is inclusive but upper limit is exclusive. if (colorObj.maxvalue > value && colorObj.minvalue <= value) { // if the value lies between any color range then return that color range return { code: colorObj.code, alpha: colorObj.alpha || '100', oriAlpha: colorObj.oriAlpha, seriesIndex: i, name: colorObj.name, label: colorObj.label, bordercolor: colorObj.bordercolor, borderalpha: colorObj.borderAlpha }; } else if (value === colorObj.maxvalue) { // if the value is equal to the maxvalue of the current range then store that range. maxContainingRange = { code: colorObj.code, alpha: colorObj.alpha || '100', oriAlpha: colorObj.oriAlpha, seriesIndex: i, name: colorObj.name, label: colorObj.label, bordercolor: colorObj.bordercolor, borderalpha: colorObj.borderAlpha }; } // if the last range is encountered and the maximum range is present whose maxValue is equal to the value then return it. if (i === colorArr.length - 1 && maxContainingRange) { return maxContainingRange; } i += 1; colorObj = colorArr[i]; } if (!colorArr.length) { // outof range value return { outOfRange: true }; } } }; /** * Return Array of color range for a given minimum and maximum value * @param {number} minValue minimum value of color range * @param {number} maxValue maximum value of color range * @return {Array} Array of color range */ ColorBucket.prototype.getColorRangeArr = function getColorRangeArr(minValue, maxValue) { var temp, colorArr = this.colorArr, i, l, minColorObj, lastMaxValue, maxColorObj, returnArr = [], colorObj, lastColorObj; if (!this.defaultAsigned) { if (minValue > maxValue) { // Swap temp = minValue; minValue = maxValue; maxValue = temp; } if (minValue < maxValue) { minColorObj = this.getColorObj(minValue); maxColorObj = this.getColorObj(maxValue); if (minColorObj && maxColorObj) { lastMaxValue = minValue; i = minColorObj.seriesIndex; l = maxColorObj.seriesIndex; for (; i <= l; i += 1) { colorObj = (0, _lib.extend2)({}, colorArr[i]); if (colorObj.minvalue !== lastMaxValue) { colorObj.minvalue = lastMaxValue; } returnArr.push(colorObj); lastColorObj = colorObj; lastMaxValue = colorObj.maxvalue; } lastColorObj && (lastColorObj.maxvalue = maxValue); } } } return returnArr; }; return ColorBucket; }(_componentInterface.ComponentInterface); exports['default'] = ColorBucket; /***/ }), /* 941 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _componentInterface = __webpack_require__(138); var _lib = __webpack_require__(125); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, COMMA_STR = ',', getColorBetween = function getColorBetween(range1, range2, value) { var value1 = range1.value, code1 = range1.code, rgb1 = (0, _lib.HEXtoRGB)(code1), value2 = range2.value, code2 = range2.code, rgb2 = (0, _lib.HEXtoRGB)(code2), diff, rgb; diff = value2 - value1; rgb = [Math.round(rgb1[0] + (rgb2[0] - rgb1[0]) / diff * (value - value1)), Math.round(rgb1[1] + (rgb2[1] - rgb1[1]) / diff * (value - value1)), Math.round(rgb1[2] + (rgb2[2] - rgb1[2]) / diff * (value - value1))]; return (0, _lib.RGBtoHex)(rgb); }; var GradientColorRange = function (_ComponentInterface) { _inherits(GradientColorRange, _ComponentInterface); function GradientColorRange() { _classCallCheck(this, GradientColorRange); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); _this.colorRange = {}; _this.valueRatio = {}; _this.data = {}; _this.mapByPercent = undefined; return _this; } /** * Sets the type of the component * @return {string} type */ GradientColorRange.prototype.getType = function getType() { return 'colorComponent'; }; /** * Sets the name of the component * @return {string} name */ GradientColorRange.prototype.getName = function getName() { return 'gradientColorRange'; }; GradientColorRange.prototype.configure = function configure(data) { if (!data) { return; } var gradientColorrange = this, index = void 0, length = void 0, range = void 0; gradientColorrange.data = data; gradientColorrange.appender = ''; range = gradientColorrange.colorRange = data.colorRange.sort(function (m, n) { return m.value - n.value; }); gradientColorrange.valueRatio = UNDEF; gradientColorrange.values = []; for (index = 0, length = range.length; index < length; index++) { gradientColorrange.values.push(range[index].value); } }; GradientColorRange.prototype.getValueRatio = function getValueRatio() { var colorRange = this.colorRange, currentRange, index, length = colorRange.length, ratio = this.valueRatio, maxValue = colorRange[length - 1].value, minValue = colorRange[0].value, range = maxValue - minValue, itemValuePercent, lastValue = 0; if (ratio) { return ratio; } ratio = this.valueRatio = []; for (index = 0; index < length; index++) { currentRange = colorRange[index]; itemValuePercent = (currentRange.value - minValue) / range; ratio.push((itemValuePercent - lastValue) * 100); lastValue = itemValuePercent; } return ratio; }; GradientColorRange.prototype.getCumulativeValueRatio = function getCumulativeValueRatio() { var colorRange = this.colorRange, currentRange, index, length = colorRange.length, firstValue = colorRange[0].value, lastValue = colorRange[length - 1].value, ratio = []; for (index = 0; index < length; index++) { currentRange = colorRange[index]; ratio.push((currentRange.value - firstValue) / (lastValue - firstValue) * 100); } return ratio; }; GradientColorRange.prototype.getBoxFill = function getBoxFill(isVertical) { var colorRange = this.colorRange, currentRange, index, length = colorRange.length, color = [], raphColorArg, angle; angle = isVertical ? 90 : 0; for (index = 0; index < length; index++) { currentRange = colorRange[index]; color.push(currentRange.code); } raphColorArg = { FCcolor: { alpha: '100,100,100', angle: angle, color: color.join(COMMA_STR), ratio: this.getValueRatio().join(COMMA_STR) } }; return (0, _lib.toRaphaelColor)(raphColorArg); }; GradientColorRange.prototype.getColorByValue = function getColorByValue(nVal) { var valueArr = this.values, colorRange = this.colorRange, length, index, rangeOutSideColor, color; if (nVal === UNDEF || nVal === null) { return; } for (index = 0, length = valueArr.length; index < length; index++) { if (nVal === valueArr[index]) { color = colorRange[index].code; break; } else if (!index && nVal < valueArr[index]) { rangeOutSideColor = true; break; } else if (index === length - 1 && nVal > valueArr[index]) { rangeOutSideColor = true; break; } else if (nVal > valueArr[index] && nVal < valueArr[index + 1]) { color = getColorBetween(colorRange[index], colorRange[index + 1], nVal); break; } } if (rangeOutSideColor) { return; } return color; }; return GradientColorRange; }(_componentInterface.ComponentInterface); exports['default'] = GradientColorRange; /***/ }), /* 942 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports['default'] = function (chart) { _decideLegendCreation(chart); }; var _lib = __webpack_require__(125); var _gradient = __webpack_require__(943); var _gradient2 = _interopRequireDefault(_gradient); var _discrete = __webpack_require__(463); var _discrete2 = _interopRequireDefault(_discrete); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * The function decides which legend to create * according to the chart configuration. * @param {Object} chart chart api instance */ function _decideLegendCreation(chart) { var colorrange = chart.getFromEnv('dataSource').colorrange, mapbycategory = chart.getFromEnv('dataSource').chart.mapbycategory, isMap = chart.defaultDatasetType === 'maps', isTreeMap = chart.getName() === 'TreeMap', legendType = void 0, legend = chart.getFromEnv('legend'), gLegend = chart.getFromEnv('gLegend'); if (!colorrange || !chart.config.showLegend) { legendType = 'none'; } else if (isMap) { if (colorrange.gradient && Number(colorrange.gradient)) { legendType = 'gradient'; } else if (colorrange.color) { legendType = 'icon'; } else { legendType = 'none'; } } else if (isTreeMap) { if (colorrange.gradient && colorrange.gradient != '0') { legendType = 'gradient'; } else { legendType = 'none'; } } else { if (colorrange.gradient && colorrange.gradient != '0' && !Number(mapbycategory)) { legendType = 'gradient'; } else { legendType = 'icon'; } } switch (legendType) { case 'gradient': // remove legend if any chart.deleteFromEnv('legend'); legend && legend.remove(); // create gradient legend, attach it as child of chart and add to env (0, _lib.componentFactory)(chart, _gradient2['default'], 'gLegend', 1); gLegend = chart.getChildren('gLegend')[0]; gLegend.configure(); chart.addToEnv('gLegend', gLegend); break; case 'icon': // remove gradient legend if any chart.deleteFromEnv('gLegend'); gLegend && gLegend.remove(); // create non gradient legend, attach it as child of chart and add to env (0, _lib.componentFactory)(chart, _discrete2['default'], 'legend', 1, { 'showLegend': true }); legend = chart.getChildren('legend')[0]; legend.configure(); chart.addToEnv('legend', legend); break; case 'none': chart.deleteFromEnv('gLegend'); chart.deleteFromEnv('legend'); gLegend && gLegend.remove(); legend && legend.remove(); } } /***/ }), /* 943 */ /***/ (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 _lib = __webpack_require__(125); var _componentInterface = __webpack_require__(138); function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } var UNDEF = void 0, compositionKeys = {}, TRACKER_FILL = 'rgba(192,192,192,' + (_lib.isIE ? 0.002 : 0.000001) + ')', legendManager = void 0, FORMER_SLIDER_INDEX = false, LATER_SLIDER_INDEX = true, PERCENT_STR = '%', COMMA_STR = ',', DEF_COLOR = '#000000', hasOwnProp = {}.hasOwnProperty, M = 'M', L = 'L', gLegendRef = void 0; // Utility functions /* * Recursively merges two objects. * Source is object from where the properties will be copied and sink is destination object where the props are to * be copied. If the property is already present in sink, it wont copy the property. * * Example: After merging the sink will be changed and returned * src = { | sink = { | sink = { * a: 1, | b: 33, | a: 1, * b: 2, | c: 44, | b: 33, * obj1: { | obj2: { | c: 44, * m: 1, | w: 11, | obj1: { * n: 2 | x: 22 | m: 1, * }, | } | n: 2 * obj2: { | | }, * x: 1, | | obj2: { * y: 2, | | w: 11, * z: 3 | | x: 22, * } | | y: 2, * } | | z: 3 * | | } * | | } * * @param: source {Object} - The object from where the props are to be copied * @param: sink {Object} - The object where the props are to be merged * @return {Object} - The reference to the sink object which was passed */ function merge(source, sink) { (function rec(source, sink) { var sourceVal, prop; for (prop in source) { // Iterates for every property in souce if (!hasOwnProp.call(source, prop)) { // Igoners if the property does not belong to the object directly, it might resides on the prototype // chain continue; } sourceVal = source[prop]; if (sink[prop] === UNDEF) { // Assigns the value / ref if the value of the same property is UNDEF (it's not checked whether // the key is directly or indirectly present on the object) in the sink. sink[prop] = sourceVal; } else if ((typeof sourceVal === 'undefined' ? 'undefined' : _typeof(sourceVal)) === 'object' && sourceVal !== null) { // If the value is another object recursively perform the merging. // @todo check if the value is function, array etc. If it happens this will execute unpredictively, // Its not implmented because it would more condition. rec(sourceVal, sink[prop]); } } })(source, sink); return sink; } /* * Takes care of sanity checking of the color to some extent. * If no color is passed, ie called as getValidHexColor() it returns the default color. If incorrect color is passed * it returns false. * * @param code {String} - color code in string * @return {String | Boolean} - false if invalid color is passed, otherwise the same color or default color if no * no color is passed */ function getValidHexColor(code) { var color = code || DEF_COLOR; return (0, _lib.getValidColor)(color) || DEF_COLOR; } /* * Returns the opposite LIGHT color of a color. If the color is alraedy light, wont get much difference. * * @param code {String} - color code in string * @return {String} - Lightest (approx) color code of the color sent */ function getOppositeColor(code) { return (0, _lib.getLightColor)(code, 1); } function normalizeFontSizeAppend(obj) { var fontSize = obj.fontSize + '', normalizeFontSize; if (!fontSize) { return obj; } normalizeFontSize = fontSize.replace(/(\d+)(px)*/, '$1px'); obj.fontSize = normalizeFontSize; return obj; } function isInvalid(arg) { if (arg === UNDEF || typeof arg === 'undefined' || arg === null || isNaN(arg)) { return true; } return false; } compositionKeys.CAPTION = 'CAPTION'; compositionKeys.LEGEND_BODY = 'LEGEND_BODY'; compositionKeys.AXIS_LABEL = 'LEGEND_LABEL'; compositionKeys.LEGEND_AXIS = 'LEGEND_AXIS'; compositionKeys.RANGE = 'RANGE'; compositionKeys.AXIS_VALUE = 'AXIS_VALUE'; legendManager = function () { var chart, defaultConf = {}; defaultConf.legendCarpetConf = { spreadFactor: 0.85, allowDrag: false, captionAlignment: 'center', padding: { v: 3, h: 3 }, style: { 'fill': '#e4d9c1', 'stroke': '#c4b89d' } }; defaultConf.legendCaptionConf = { spreadFactor: 0.2, padding: { v: 2, h: 2 }, style: { fill: '#786B50', fontFamily: 'sans-serif', fontSize: '12px', fontWeight: 'bold', fontStyle: 'normal' }, bound: { style: { stroke: 'none' } } }; defaultConf.legendBodyConf = { spreadFactor: 0.8, padding: { v: 2, h: 2 }, bound: { style: { stroke: 'none' } } }; defaultConf.legendAxisConf = { legendAxisHeight: 11, spreadFactor: 0.4, padding: { v: 1, h: 1 }, style: { stroke: 'none', 'stroke-opacity': 0, 'stroke-width': 1 }, line: { grooveLength: 3, offset: 8, style: { stroke: 'rgba(255, 255, 255, 0.65)', 'stroke-width': 1.5 } }, shadow: { style: { stroke: 'none', fill: (0, _lib.toRaphaelColor)({ FCcolor: { alpha: '25,0,0', angle: 360, color: '000000,FFFFFF,FFFFFF', ratio: '0,30,40' } }) } }, bound: { style: { stroke: 'none' } } }; defaultConf.sliderGroupConf = { showTooltip: 1, outerCircle: { rFactor: 1.4, style: { fill: TRACKER_FILL, stroke: '#757575', 'stroke-width': 3 } }, innerCircle: { rFactor: 0.65, style: { fill: TRACKER_FILL, stroke: '#FFFFFF' } } }; defaultConf.axisTextItemConf = { spreadFactor: 0.3, padding: { v: 1, h: 1 }, style: { fill: '#786B50', fontFamily: 'sans-serif', fontSize: '12px', fontWeight: 'normal', fontStyle: 'normal' } }; function normalizePreprocessedData(confArr) { var numberFormatter = chart.getFromEnv('number-formatter'), index, length, rawVal; for (index = 0, length = confArr.length; index < length; index++) { rawVal = confArr[index].maxvalue; if (!rawVal) { continue; } confArr[index].maxvalue = numberFormatter.getCleanValue(rawVal); } } return { init: function init(options) { chart = options.chart; // layers = chart.graphics; // components = chart.components; }, // setConf: function (conf) { // config = conf; // }, legacyDataParser: function legacyDataParser(data, extremes) { var colormanagerConf = {}, numberFormatter = chart.getFromEnv('number-formatter'), colorConfArr, colorConf, startColor, endColor, index, validColor, length, colorRange, value, dispValue, mapByPercent, isMaxValPresent; if (!data) { return false; } colormanagerConf.mapByPercent = mapByPercent = !!(0, _lib.pluckNumber)(data.mapbypercent, 0); colorConfArr = data.color || []; if (data.minvalue === UNDEF) { data.minvalue = extremes.min !== UNDEF ? mapByPercent ? 0 : extremes.min : 0; } if (data.maxvalue === UNDEF) { data.maxvalue = extremes.max !== UNDEF ? mapByPercent ? 100 : extremes.max : 100; } isMaxValPresent = false; for (index = 0, length = colorConfArr.length; index < length; index++) { if (colorConfArr[index].maxvalue) { isMaxValPresent = true; break; } } if (!isMaxValPresent) { colorConfArr = []; } startColor = data.code; colorRange = colormanagerConf.colorRange = []; colormanagerConf.gradient = !!(0, _lib.pluckNumber)(data.gradient, 1); // If no additional color array is provided as part of generating the gradient, creates the start and // end value to create the gradient if (!colorConfArr.length) { if (startColor) { // If start color is mentioned, create a gradient starting from default color to the mentioned // color endColor = getValidHexColor(startColor); startColor = getValidHexColor(); } else { // If no color is mentioned, create a gradient of two opposite color startColor = getValidHexColor(); endColor = getOppositeColor(startColor); } colorConfArr.push({ code: endColor, maxvalue: data.maxvalue, label: UNDEF }); } else { startColor = getValidHexColor(startColor); } normalizePreprocessedData(colorConfArr); colorConfArr = colorConfArr.sort(function (m, n) { return m.maxvalue - n.maxvalue; }); value = dispValue = data.minvalue && numberFormatter.getCleanValue(data.minvalue); dispValue = (value !== UNDEF || value !== null) && (mapByPercent ? value + PERCENT_STR : numberFormatter.legendValue(value)); colorRange.push({ code: (0, _lib.dehashify)(startColor), value: value, displayValue: dispValue, label: data.startlabel }); for (index = 0, length = colorConfArr.length; index < length; index++) { colorConf = colorConfArr[index]; validColor = getValidHexColor(colorConf.code || colorConf.color); value = dispValue = colorConf.maxvalue; if (isNaN(parseInt(value, 10))) { continue; } dispValue = (value !== UNDEF || value !== null) && (mapByPercent ? value + PERCENT_STR : numberFormatter.legendValue(value)); colorRange.push({ code: (0, _lib.dehashify)(validColor), value: value, displayValue: dispValue, label: colorConf.label || colorConf.displayvalue }); } colorRange[colorRange.length - 1].label = data.endlabel || colorConf.label; return colormanagerConf; }, getDefaultConf: function getDefaultConf(key) { return defaultConf[key]; } }; }(); var GLegend = function (_ComponentInterface) { _inherits(GLegend, _ComponentInterface); /** * Sets the type of the component * @return {string} type */ GLegend.prototype.getType = function getType() { return 'gradientLegend'; }; /** * Sets the name of the component * @return {string} name */ GLegend.prototype.getName = function getName() { return 'gLegend'; }; function GLegend() { _classCallCheck(this, GLegend); var _this = _possibleConstructorReturn(this, _ComponentInterface.call(this)); gLegendRef = _this; _this.enabled = false; _this.drawOptions = {}; _this.components = {}; return _this; } GLegend.prototype.setColorRange = function setColorRange(colorRange) { var cr = this.drawOptions.colorRange = colorRange; cr && cr._preparationGoneWrong && (this._dontPlot = true); }; GLegend.prototype.configureAttributes = function configureAttributes() { var componentAPI = this, chart = componentAPI.getFromEnv('chart'), chartAttrs = componentAPI.getFromEnv('dataSource').chart, conf = componentAPI.conf = {}, outCanvasBaseFont = chartAttrs.outcnvbasefont, outCanvasBaseFontSize = chartAttrs.outcnvbasefontsize, outCanvasBaseFontColor = chartAttrs.outcnvbasefontcolor, labelStyle = chart.config.dataLabelStyle, fColor, fFamily, fSize, fWeight, cfColor, cfFamily, cfSize, cfWeight, axisBorderColor, axisBorderAlpha; legendManager.init({ chart: chart }); // Extracts raw FC Chart data and parse it to prepare data for colorRange. This kind of acts like a // adapter. componentAPI.data = componentAPI.getFromEnv('dataSource').colorrange; if (componentAPI._dontPlot) { return; } // Starts prepaeparing the drawOptions object which is needed during the final drawing and space // management. componentAPI.drawOptions = { smartLabel: componentAPI.getFromEnv('smartLabel'), gLegend: componentAPI }; componentAPI._dontPlot = false; componentAPI._recalculateLogicalSpace = true; conf.caption = (0, _lib.pluck)(chartAttrs.legendcaption); conf.legendPosition = (0, _lib.pluck)(chartAttrs.legendposition, 'bottom').toLowerCase(); conf.showLegend = (0, _lib.pluckNumber)(chartAttrs.showlegend, 1); conf.interactiveLegend = (0, _lib.pluckNumber)(chartAttrs.interactivelegend, 1); conf.showLegendLabels = (0, _lib.pluckNumber)(chartAttrs.showlegendlabels, 1); fColor = chartAttrs.legenditemfontcolor || outCanvasBaseFontColor; fFamily = chartAttrs.legenditemfont || outCanvasBaseFont; fSize = chartAttrs.legenditemfontsize || outCanvasBaseFontSize; fWeight = (0, _lib.pluckNumber)(chartAttrs.legenditemfontbold, 0); cfColor = chartAttrs.legendcaptionfontcolor || outCanvasBaseFontColor; cfFamily = chartAttrs.legendcaptionfont || outCanvasBaseFont; cfSize = chartAttrs.legendcaptionfontsize || outCanvasBaseFontSize; cfWeight = (0, _lib.pluckNumber)(chartAttrs.legendcaptionfontbold, 1); axisBorderColor = chartAttrs.legendaxisbordercolor ? (0, _lib.hashify)((0, _lib.dehashify)(chartAttrs.legendaxisbordercolor)) : UNDEF; axisBorderAlpha = axisBorderColor ? (0, _lib.pluckNumber)(chartAttrs.legendaxisborderalpha, 100) / 100 : UNDEF; // We do this like this so that, it becomes easy to override the default configuartion. The default conf was // created in this format. conf.axisTextItemConf = { style: { fill: fColor ? (0, _lib.convertColor)((0, _lib.pluck)(fColor)) : labelStyle.color, fontFamily: fFamily ? (0, _lib.pluck)(fFamily) : labelStyle.fontFamily, fontSize: fSize ? (0, _lib.pluckNumber)(fSize) : labelStyle.fontSize.match(/\d+/)[0], fontWeight: fWeight ? 'bold' : labelStyle.fontWeight } }; conf.legendCaptionConf = { style: { fill: cfColor ? (0, _lib.convertColor)((0, _lib.pluck)(cfColor)) : labelStyle.color, fontFamily: cfFamily ? (0, _lib.pluck)(cfFamily) : labelStyle.fontFamily, fontSize: cfSize ? (0, _lib.pluckNumber)(cfSize) : labelStyle.fontSize.match(/\d+/)[0], fontWeight: cfWeight ? 'bold' : labelStyle.fontWeight, fontStyle: 'normal' } }; conf.legendAxisConf = { legendAxisHeight: 11, style: { stroke: axisBorderColor, 'stroke-opacity': axisBorderAlpha }, line: { style: { stroke: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.legendscalelinecolor, 'FFF8E9'), (0, _lib.pluckNumber)(chartAttrs.legendscalelinealpha, 100)), 'stroke-width': (0, _lib.pluckNumber)(chartAttrs.legendscalelinethickness) } } }; conf.sliderGroupConf = { showTooltip: (0, _lib.pluckNumber)(chartAttrs.showtooltip, 1), outerCircle: { rFactor: (0, _lib.pluckNumber)(chartAttrs.sliderdiameterfactor), style: { stroke: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.legendpointerbordercolor, '757575'), (0, _lib.pluckNumber)(chartAttrs.legendpointerborderalpha, 100)) } }, innerCircle: { rFactor: (0, _lib.pluckNumber)(chartAttrs.sliderholediameterfactor), style: { stroke: (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.legendpointercolor, 'FFFFFF'), (0, _lib.pluckNumber)(chartAttrs.legendpointeralpha, 100)) } } }; conf.legendCarpetConf = { spreadFactor: (0, _lib.pluckNumber)(chartAttrs.legendspreadfactor), allowDrag: !!(0, _lib.pluckNumber)(chartAttrs.legendallowdrag, 0), captionAlignment: (0, _lib.pluck)(chartAttrs.legendcaptionalignment, 'center'), style: { 'fill': (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.legendbgcolor, 'e4d9c1'), (0, _lib.pluckNumber)(chartAttrs.legendbgalpha, 100)), 'stroke': (0, _lib.convertColor)((0, _lib.pluck)(chartAttrs.legendbordercolor, 'c4b89d'), (0, _lib.pluckNumber)(chartAttrs.legendborderalpha, 100)), 'stroke-width': (0, _lib.pluckNumber)(chartAttrs.legendborderthickness, 1) } }; }; /* * This takes care of the instance creation of various component based on attrs. Dependency injection / * component injection is managed from here. * This is not meant to be called from outside. This gets called internally. */ GLegend.prototype.postConfigureInit = function postConfigureInit() { var componentAPI = this, conf = componentAPI.conf, caption, carpet, axis, sGroup, // gl, ovrdConf, ovrdTextConf, body, labels, values, captionConfig, axisConfig, bodyConfig; // Container for the component instances. componentAPI.elem = {}; // The details of the various components and their relationship is written at the top. if (conf.interactiveLegend) { // If interactiveLegend is attr is present, creates the sliders of the legend. // Override the default conf with the user given one. ovrdConf = merge(legendManager.getDefaultConf('sliderGroupConf'), conf.sliderGroupConf); if (this.sGroup) { sGroup = componentAPI.elem.sGroup = this.sGroup; sGroup.configure(ovrdConf); componentAPI.elem.sGroup.gLegend = componentAPI; } else { this.sGroup = componentAPI.elem.sGroup = sGroup = new SliderGroup(ovrdConf); sGroup.configure(ovrdConf); componentAPI.elem.sGroup.gLegend = componentAPI; } } else { this.sGroup && this.sGroup.dispose(); this.sGroup && delete this.sGroup; } ovrdConf = merge(legendManager.getDefaultConf('legendCarpetConf'), conf.legendCarpetConf); ovrdConf.legendPosition = conf.legendPosition; bodyConfig = legendManager.getDefaultConf('legendBodyConf'); if (conf.legendPosition === 'bottom') { // If the legend to be placed at bottom // The reference side would be width and will be covered the complete canvasWidth. // The max of other side is given by maxOtherSide. // The margin is taken from canvasLeft componentAPI.drawOptions.refSideKey = 'canvasWidth'; componentAPI.drawOptions.refOffsetKey = 'canvasLeft'; ovrdTextConf = merge(legendManager.getDefaultConf('axisTextItemConf'), conf.axisTextItemConf); bodyConfig.legendPosition = 'bottom'; axisConfig = merge(legendManager.getDefaultConf('legendAxisConf'), conf.legendAxisConf); axisConfig.legendPosition = 'bottom'; ovrdTextConf.legendPosition = 'bottom'; } else { // If the legend to be placed at bottom // The reference side would be height and will be covered the complete canvasWidth. // The max of other side is given by maxOtherSide. // The margin is taken from canvasTop componentAPI.drawOptions.refSideKey = 'canvasHeight'; componentAPI.drawOptions.refOffsetKey = 'canvasTop'; ovrdTextConf = merge(legendManager.getDefaultConf('axisTextItemConf'), conf.axisTextItemConf); bodyConfig.legendPosition = 'right'; axisConfig = merge(legendManager.getDefaultConf('legendAxisConf'), conf.legendAxisConf); axisConfig.legendPosition = 'right'; ovrdTextConf.legendPosition = 'right'; } if (!Object.keys(this.components).length) { // Creates a horizontal capet, axis, labels and values component this.components.LegendCarpet = new LegendCarpet(); this.components.LegendBody = new LegendBody(); this.components.LegendAxis = new LegendAxis(); this.components.LegendValues = new LegendValues(); conf.showLegendLabels && (this.components.LegendLabels = new LegendLabels()); } axis = this.components.LegendAxis; values = this.components.LegendValues; carpet = this.components.LegendCarpet; body = this.components.LegendBody; conf.showLegendLabels && (labels = this.components.LegendLabels); this.components.LegendCarpet.configure(ovrdConf); this.components.LegendValues.configure(ovrdTextConf); this.components.LegendAxis.configure(axisConfig); this.components.LegendBody.configure(componentAPI.drawOptions.colorRange, bodyConfig, ovrdTextConf); conf.showLegendLabels && labels.configure(ovrdTextConf); if (conf.caption) { // If caption is present, create a instance of the same captionConfig = merge(legendManager.getDefaultConf('legendCaptionConf'), conf.legendCaptionConf); if (this.componentCaption && Object.keys(this.componentCaption).length) { this.componentCaption.configure(conf.caption, captionConfig); } else { caption = this.componentCaption = new LegendCaption(); caption.configure(conf.caption, captionConfig); } carpet.addCompositions(this.componentCaption, compositionKeys.CAPTION); } else { carpet.removeCompositions(compositionKeys.CAPTION); this.componentCaption && this.componentCaption.dispose(); delete this.componentCaption; } // If the slider group is defined, inject as component. Slider group is component of axis. sGroup && axis.addCompositions(sGroup, compositionKeys.RANGE); // Adds component to the body if available labels && body.addCompositions(labels, compositionKeys.AXIS_LABEL); body.addCompositions(axis, compositionKeys.LEGEND_AXIS); body.addCompositions(values, compositionKeys.AXIS_VALUE); // Adds the body to the carpet carpet.addCompositions(body, compositionKeys.LEGEND_BODY); // Finally creates the gradient legend. componentAPI.elem.gl = new LegendBase(carpet); }; /** * Return current selection range in gradient legend * @return {Object} return minimum, maximum value of selected gradient legend */ GLegend.prototype.getValueRange = function getValueRange() { var componentAPI = this, rGroup = componentAPI.elem && componentAPI.elem.sGroup, sliders = rGroup.sliders, extremes = rGroup.extremes, minVal, maxVal; minVal = sliders['false'].currPos; maxVal = extremes[1] - extremes[0] + sliders['true'].currPos; return [{ min: rGroup.getValueFormPixel(minVal), max: rGroup.getValueFormPixel(maxVal) }]; }; GLegend.prototype._dispose = function _dispose() { var componentAPI = this; componentAPI.elem && componentAPI.elem.gl && componentAPI.elem.gl.dispose(); componentAPI.elem = {}; _ComponentInterface.prototype._dispose.call(this); }; /** * Returns the area taken by the glegend * * @returns {any} logicalArea taken by gradient legend * @memberof GLegend */ GLegend.prototype.getCalculatedLogicalSpace = function getCalculatedLogicalSpace() { return this._logicalArea; }; /** * Sets area to _logicalArea which is the total area taken by gLegend * * @param {any} area * @memberof GLegend */ GLegend.prototype.setCalculatedLogicalSpace = function setCalculatedLogicalSpace(area) { this._logicalArea = area; }; GLegend.prototype.getLogicalSpace = function getLogicalSpace(maxOtherSide) { var componentAPI = this, conf = componentAPI.conf, zeroArea = { height: 0, width: 0 }, logicalSpace, drawOptions = componentAPI.drawOptions, refSideKey, chartConfig = componentAPI.getFromEnv('chartConfig'), refOffsetKey; // @todo redundancy in calculating the reference side. Make it from a organized procedure call. if (!componentAPI._recalculateLogicalSpace) { refSideKey = drawOptions.refSideKey; refOffsetKey = drawOptions.refOffsetKey; componentAPI.drawOptions.refSide = chartConfig[refSideKey]; componentAPI.drawOptions.refOffset = chartConfig[refOffsetKey]; componentAPI.drawOptions.maxOtherSide = maxOtherSide || componentAPI.drawOptions.maxOtherSide; logicalSpace = componentAPI.elem.gl.getLogicalSpace(componentAPI.drawOptions, true); componentAPI.setCalculatedLogicalSpace(logicalSpace); return componentAPI.getCalculatedLogicalSpace() || zeroArea; } if (componentAPI._dontPlot) { return zeroArea; } componentAPI._recalculateLogicalSpace = false; componentAPI.postConfigureInit(); if (!conf.showLegend) { return zeroArea; } refSideKey = drawOptions.refSideKey; refOffsetKey = drawOptions.refOffsetKey; componentAPI.drawOptions.refSide = chartConfig[refSideKey]; componentAPI.drawOptions.refOffset = chartConfig[refOffsetKey]; componentAPI.drawOptions.maxOtherSide = maxOtherSide || componentAPI.drawOptions.maxOtherSide; if (componentAPI.elem.gl) { logicalSpace = componentAPI.elem.gl.getLogicalSpace(componentAPI.drawOptions, true); componentAPI.elem.gl && componentAPI.setCalculatedLogicalSpace(logicalSpace); } return componentAPI.getCalculatedLogicalSpace(); }; GLegend.prototype.resetLegend = function resetLegend() { var componentAPI = this, rGroup; rGroup = componentAPI.elem && componentAPI.elem.sGroup; if (rGroup) { rGroup.reset(); } }; /** * Stores the xpos, ypos, width and height of gLegend before drawing of chart * components. * * @memberof GLegend */ GLegend.prototype.allocatePosition = function allocatePosition() { var iapi = this.getFromEnv('chart'), config = iapi.config, gradientLegend = this, conf = gradientLegend.conf || {}, legendPosition = conf.legendPosition, canvasLeft = config.canvasLeft, canvasTop = config.canvasTop, canvasWidth = config.canvasWidth, canvasHeight = config.canvasHeight, marginBottom = config.marginBottom, marginRight = config.marginRight, spaceTakenByGradientLegend, spaceLeft, width, height, xPos, yPos; if (!iapi.config.gLegendEnabled) { return; } spaceTakenByGradientLegend = this.getCalculatedLogicalSpace(); width = conf.width = spaceTakenByGradientLegend.width; height = conf.height = spaceTakenByGradientLegend.height; if (legendPosition === 'bottom') { spaceLeft = canvasWidth - width; xPos = canvasLeft + (spaceLeft < 0 ? 0 : spaceLeft / 2); yPos = config.height - spaceTakenByGradientLegend.height - marginBottom - (config.actionBarHeight || 0); } else { spaceLeft = canvasHeight - height; yPos = canvasTop + (spaceLeft < 0 ? 0 : spaceLeft / 2); xPos = config.width - spaceTakenByGradientLegend.width - marginRight; } conf.xPos = xPos; conf.yPos = yPos; }; /** * Starts drawing of gradient legend * * @memberof GLegend */ GLegend.prototype.draw = function draw() { var iapi = this.getFromEnv('chart'), colorRangeObj = iapi.getFromEnv('dataSource').colorrange, gradientLegend = this, conf = gradientLegend.conf || {}, hasGradientLegend = iapi.hasGradientLegend; if (!iapi.config.gLegendEnabled) { return; } colorRangeObj && hasGradientLegend && gradientLegend.drawLegendComponent(conf.xPos, conf.yPos, { parentGroup: iapi.getContainer('parentgroup'), animationManager: iapi.getFromEnv('animationManager') }); }; GLegend.prototype.drawLegendComponent = function drawLegendComponent(x, y, options) { var componentAPI = this, conf = componentAPI.conf, measurement, node; if (componentAPI._dontPlot) { return; } if (!conf.showLegend) { componentAPI.enabled = false; return; } componentAPI.drawOptions.animationManager = options.animationManager; componentAPI.drawOptions.parentGroup = options.parentGroup; componentAPI.drawOptions.x = x; componentAPI.drawOptions.y = y; componentAPI.drawOptions.maxOtherSide = componentAPI.drawOptions.maxOtherSide || options.maxOtherSide; node = componentAPI.elem.gl.draw(componentAPI.drawOptions); measurement = node.getBBox(); conf.xPos = measurement.x; conf.yPos = measurement.y; conf.height = measurement.height; conf.width = measurement.width; componentAPI.enabled = true; }; return GLegend; }(_componentInterface.ComponentInterface); var LegendBase = function () { function LegendBase(carpet) { _classCallCheck(this, LegendBase); this.carpet = carpet; } LegendBase.prototype.draw = function draw(options) { return this.carpet.draw(options); }; LegendBase.prototype.getLogicalSpace = function getLogicalSpace(options, recalculate) { return this.carpet.getLogicalSpace(options, recalculate); }; LegendBase.prototype.dispose = function dispose() { this.carpet && this.carpet.group && this.carpet.group.remove(); }; return LegendBase; }(); var LegendCarpet = function () { function LegendCarpet(conf) { _classCallCheck(this, LegendCarpet); this.conf = conf; this._id = 'GL_CARPET'; // Save the components which are the building block of the whole legend. Like: The background rect, // text, slider, color axis etc. this.compositionsByCategory = {}; this.node = UNDEF; this.group = UNDEF; this._lSpace = UNDEF; this.autoRecalculate = false; this.groupName = 'fc-gradient-legend'; this.moveInstructions = {}; } LegendCarpet.prototype.configure = function configure(conf) { this.conf = conf; }; LegendCarpet.prototype.getName = function getName() { return 'LegendCarpet'; }; LegendCarpet.prototype.getType = function getType() { return 'legend'; }; LegendCarpet.prototype.addCompositions = function addCompositions(instance, category) { this.compositionsByCategory[category] = instance; }; LegendCarpet.prototype.removeCompositions = function removeCompositions(category) { delete this.compositionsByCategory[category]; }; LegendCarpet.prototype.getBoundingBox = function getBoundingBox(options) { var conf = this.conf, spreadFactor = conf.spreadFactor, refSide = options.refSide, alignment = options.alignment, refOffset = options.refOffset, x = options.x, y = options.y, lWidth, lHeight; if (this.conf.legendPosition === 'bottom') { lWidth = conf.width = refSide * spreadFactor; lHeight = options.maxOtherSide; if (alignment && (x === UNDEF || x === null)) { x = (refOffset + refSide) / 2 - lWidth / 2; } } else { lHeight = conf.height = refSide * spreadFactor; lWidth = options.maxOtherSide; if (alignment && (y === UNDEF || y === null)) { y = (refOffset + refSide) / 2 - lHeight / 2; } } return { width: lWidth, height: lHeight, x: x, y: y }; }; LegendCarpet.prototype.getPostCalcDecisionsH = function getPostCalcDecisionsH(bBox, componentsArea) { var conf = this.conf, padding = conf.padding, cat, totalHeightTaken = 0; this.moveInstructions = {}; for (cat in componentsArea) { totalHeightTaken += componentsArea[cat].height || 0; } bBox.height = totalHeightTaken + 2 * padding.v; }; LegendCarpet.prototype.getLogicalSpace = function getLogicalSpace(options, recalculate) { var lSpace = this._lSpace, categoryMap = ['CAPTION', 'LEGEND_BODY'], conf = this.conf, padding = conf.padding, compositionsByCategory = this.compositionsByCategory, composition, bBox, effectivePlotArea, compositionLSPace, compositionHeight = 0, componentsArea = {}, compositionPlotArea, // autoRecalculate, heightNotUsed = 0; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } /* else { autoRecalculate = false; } */ lSpace = this._lSpace = bBox = this.getBoundingBox(options); if (isInvalid(lSpace.x) || isInvalid(lSpace.y) || isInvalid(lSpace.height) || isInvalid(lSpace.width)) { this.autoRecalculate = true; } // Copy the props effectivePlotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea.height -= 2 * padding.v; effectivePlotArea.width -= 2 * padding.h; effectivePlotArea.x += padding.h; effectivePlotArea.y += padding.v; for (var i = 0; i < categoryMap.length; i++) { composition = compositionsByCategory[categoryMap[i]]; if (composition) { compositionPlotArea = merge(effectivePlotArea, {}); compositionPlotArea.y += compositionHeight; compositionHeight = effectivePlotArea.height * composition.conf.spreadFactor; compositionPlotArea.height = compositionHeight + heightNotUsed; compositionLSPace = composition.getLogicalSpace(merge(compositionPlotArea, {}), options, recalculate); heightNotUsed = compositionPlotArea.height - compositionLSPace.height; componentsArea[categoryMap[i]] = compositionLSPace; compositionHeight = compositionLSPace.height; } } this.getPostCalcDecisions(bBox, componentsArea); this._lSpace = bBox; return bBox; }; LegendCarpet.prototype.setupDragging = function setupDragging() { var group = this.group, dx = 0, dy = 0, idx = 0, idy = 0; group.css({ cursor: 'move' }); group.drag(function (_dx, _dy) { dx = _dx; dy = _dy; group.attr({ transform: 't' + (idx + dx) + ',' + (idy + dy) }); }, function () { idx += dx; idy += dy; }, _lib.stubFN); }; LegendCarpet.prototype.draw = function draw(options) { var conf = this.conf, ref = this, categoryMap = ['CAPTION', 'LEGEND_BODY'], compositionsByCategory = this.compositionsByCategory, animationManager = options.animationManager, parentGroup = options.parentGroup, group, // node, category, composition, lSpace; // compositionRes, this.getLogicalSpace(options, this.autoRecalculate); lSpace = this._lSpace; this.group = group = animationManager.setAnimation({ el: this.group || 'group', attr: { name: ref.groupName }, component: gLegendRef, container: parentGroup, label: 'carpetGroup' }); // The main rect outside all the composition this.node = animationManager.setAnimation({ el: this.node || 'rect', attr: lSpace, css: conf.style, component: gLegendRef, container: group, label: 'rect' }); for (var i = 0; i < categoryMap.length; i++) { composition = compositionsByCategory[categoryMap[i]]; if (composition) { composition.draw(conf.captionAlignment, lSpace, { animationManager: animationManager, colorRange: options.colorRange, numberFormatter: options.numberFormatter, parentLayer: group, smartLabel: options.smartLabel, moveInstructions: this.moveInstructions[category], gLegend: options.gLegend }); } } conf.allowDrag && this.setupDragging(); return this.node; }; LegendCarpet.prototype.getPostCalcDecisions = function getPostCalcDecisions(bBox, componentsArea) { return this.conf.legendPosition === 'bottom' ? this.getPostCalcDecisionsH(bBox, componentsArea) : this.getPostCalcDecisionsV(bBox, componentsArea); }; LegendCarpet.prototype.getPostCalcDecisionsV = function getPostCalcDecisionsV(bBox, componentsArea) { var conf = this.conf, padding = conf.padding, maxWidth = Number.NEGATIVE_INFINITY, width, cat, move = this.moveInstructions, diff; this.getPostCalcDecisionsH(bBox, componentsArea); for (cat in componentsArea) { width = componentsArea[cat].width; maxWidth = maxWidth < width ? width : maxWidth; } bBox.width = maxWidth + 2 * padding.h; for (cat in componentsArea) { width = componentsArea[cat].width; diff = maxWidth - width; if (diff) { move[cat] = 't' + diff / 2 + ',0'; } } }; return LegendCarpet; }(); var LegendCaption = function () { function LegendCaption(text, conf) { _classCallCheck(this, LegendCaption); this.rawText = text; this.conf = conf; this._id = 'GL_CAPTION'; this.node = UNDEF; this.bound = UNDEF; this._lSpace = UNDEF; this.LegendCaption = {}; this.LegendCaption.LEFT = { x: function x(smartText, boundingBox) { return boundingBox.x + smartText.width / 2 + 2; } }; this.LegendCaption.RIGHT = { x: function x(smartText, boundingBox) { return boundingBox.x + boundingBox.width - smartText.width / 2 - 2; } }; this.LegendCaption.CENTER = { x: function x() { var boundingBox = arguments[1]; return boundingBox.x + boundingBox.width / 2; } }; } LegendCaption.prototype.configure = function configure(text, conf) { this.rawText = text; this.conf = conf; }; LegendCaption.prototype.getName = function getName() { return 'LegendCaption'; }; LegendCaption.prototype.getType = function getType() { return 'caption'; }; LegendCaption.prototype.getLogicalSpace = function getLogicalSpace(bBox, options, recalculate) { var conf = this.conf, padding = conf.padding, lSpace = this._lSpace, text = this.rawText, chartConfig = options.gLegend.getFromEnv('chartConfig'), smartLabel, effectivePlotArea, smartText, copyOfStyle; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } lSpace = this._lSpace = { bound: { height: 0, width: 0 }, node: { logicArea: UNDEF, smartText: UNDEF } }; smartLabel = options.smartLabel; if (!text) { return lSpace.bound; } effectivePlotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea.height -= 2 * padding.v; effectivePlotArea.width -= 2 * padding.h; effectivePlotArea.x += padding.h; effectivePlotArea.y += padding.v; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); copyOfStyle = merge(this.conf.style, {}); normalizeFontSizeAppend(copyOfStyle); smartLabel.setStyle(this._metaStyle = copyOfStyle); smartText = smartLabel.getSmartText(text, effectivePlotArea.width, effectivePlotArea.height); effectivePlotArea.height = smartText.height; effectivePlotArea.width = smartText.width; bBox.height = smartText.height + 2 * padding.v; bBox.width = smartText.width + 2 * padding.h; lSpace.node.smartText = smartText; lSpace.node.logicArea = effectivePlotArea; lSpace.bound = bBox; return bBox; }; LegendCaption.prototype.draw = function draw() { var conf = this.conf, // smartLabel, layer, boundAttr = conf.bound || {}, group, bound, boundingArea, lSpace, normalizedX, x, bBox, options, node, animationManager; if (arguments.length >= 3) { x = arguments[0]; bBox = arguments[1]; options = arguments[2]; } else if (arguments.length >= 2) { x = arguments[0]; options = arguments[1]; } layer = options.parentLayer; animationManager = options.animationManager; // Separate group for caption and the bounding rect this.group = group = animationManager.setAnimation({ el: this.group || 'group', attr: { name: 'legend-caption' }, css: conf.style, component: gLegendRef, container: layer }); this.getLogicalSpace(bBox, options); lSpace = this._lSpace; node = lSpace.node; boundingArea = lSpace.bound; // Bounding rect this.bound = bound = animationManager.setAnimation({ el: this.bound || 'rect', attr: boundingArea, css: boundAttr.style, container: group, component: gLegendRef }); normalizedX = typeof x === 'string' ? this.LegendCaption[x.toUpperCase()].x(node.smartText, bBox || node.logicArea) : x; this.node = animationManager.setAnimation({ el: this.node || 'text', attr: { text: node.smartText.text, x: normalizedX, y: node.logicArea.y + node.smartText.height / 2, lineHeight: this._metaStyle.lineHeight, fill: conf.style.fill }, container: group, component: gLegendRef }); return { group: group, bound: bound, node: this.node }; }; LegendCaption.prototype.dispose = function dispose() { this.group.remove(); this.bound.remove(); this.node.remove(); }; return LegendCaption; }(); var LegendBody = function () { function LegendBody(colorRange, conf, childTextConf) { _classCallCheck(this, LegendBody); this.colorRange = colorRange; this.conf = conf; this.childTextConf = childTextConf; this._id = 'GL_BODY'; this.bound = UNDEF; this.group = UNDEF; this.compositionsByCategory = {}; this._lSpace = UNDEF; this.SC_STACK = [compositionKeys.AXIS_LABEL, compositionKeys.LEGEND_AXIS, compositionKeys.AXIS_VALUE]; this.DARW_STACK = [compositionKeys.AXIS_VALUE, compositionKeys.LEGEND_AXIS, compositionKeys.AXIS_LABEL]; } LegendBody.prototype.configure = function configure(colorRange, conf, childTextConf) { this.colorRange = colorRange; this.conf = conf; this.childTextConf = childTextConf; this.compositionsByCategory = {}; }; LegendBody.prototype.getName = function getName() { return 'LegendBody'; }; LegendBody.prototype.getType = function getType() { return 'legend'; }; LegendBody.prototype.addCompositions = function addCompositions(instance, category) { this.compositionsByCategory[category] = instance; }; LegendBody.prototype.getSpaceTaken = function getSpaceTaken(spaceObj) { return this.conf.legendPosition === 'bottom' ? spaceObj.height : spaceObj.width; }; LegendBody.prototype.getLogicalSpace = function getLogicalSpace(bBox, options, recalculate) { var lSpace = this._lSpace, conf = this.conf, padding = conf.padding, compositionsByCategory = this.compositionsByCategory, composition, compositionPlotArea, compositionAreaOffset, effectivePlotArea, getCompositionPlotArea, spaceTaken = 0, index, length; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } lSpace = this._lSpace = { bound: { height: 0, width: 0 }, node: { logicArea: UNDEF } }; effectivePlotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea.height -= 2 * padding.v; effectivePlotArea.width -= 2 * padding.h; effectivePlotArea.x += padding.h; effectivePlotArea.y += padding.v; getCompositionPlotArea = this.getCompositionPlotAreaFor(effectivePlotArea); options.colorRange = this.colorRange; for (index = 0, length = this.SC_STACK.length; index < length; index++) { if (!(composition = compositionsByCategory[this.SC_STACK[index]])) { continue; } compositionPlotArea = getCompositionPlotArea(compositionAreaOffset, composition.conf.spreadFactor); compositionAreaOffset = composition.getLogicalSpace(merge(compositionPlotArea, {}), options, recalculate); spaceTaken += this.getSpaceTaken(compositionAreaOffset); } this.updateEffectivePlotArea(bBox, effectivePlotArea, spaceTaken); lSpace.node.logicArea = effectivePlotArea; lSpace.bound = bBox; return bBox; }; LegendBody.prototype.draw = function draw() { var childTextConf = this.childTextConf, conf = this.conf, boundStyle = conf.bound.style || {}, compositionsByCategory = this.compositionsByCategory, animationManager, layer, bound, // colorRange, composition, legendBodyGroup, bBox, lSpace, // x, options, index, length; if (arguments.length >= 3) { // x = arguments[0]; bBox = arguments[1]; options = arguments[2]; } else if (arguments.length >= 2) { // x = arguments[0]; options = arguments[1]; } layer = options.parentLayer; // colorRange = options.colorRange; animationManager = options.animationManager; this.getLogicalSpace(bBox, options); lSpace = this._lSpace; this.group = legendBodyGroup = animationManager.setAnimation({ el: this.group || 'group', attr: { name: 'legend-body', transform: 't0,0' }, css: childTextConf.style, container: layer, component: gLegendRef }); this.bound = bound = animationManager.setAnimation({ el: this.bound || 'rect', attr: lSpace.bound, css: boundStyle, container: legendBodyGroup, component: gLegendRef }); options.colorRange = this.colorRange; options.parentLayer = legendBodyGroup; for (index = 0, length = this.DARW_STACK.length; index < length; index++) { if (!(composition = compositionsByCategory[this.DARW_STACK[index]])) { continue; } composition.draw(options); } if (options.moveInstructions) { legendBodyGroup.attr({ transform: options.moveInstructions }); } return { bound: bound, group: legendBodyGroup }; }; LegendBody.prototype.getCompositionPlotAreaFor = function getCompositionPlotAreaFor(effectivePlotArea) { var plotArea, isLPosBottom = this.conf.legendPosition === 'bottom'; plotArea = merge(effectivePlotArea, {}); return function (compositionAreaOffset, sf) { compositionAreaOffset = compositionAreaOffset || {}; if (isLPosBottom) { plotArea.y += compositionAreaOffset.height || 0; plotArea.height = effectivePlotArea.height * sf; } else { plotArea.x += compositionAreaOffset.width || 0; plotArea.width = effectivePlotArea.width * sf; } return plotArea; }; }; LegendBody.prototype.updateEffectivePlotArea = function updateEffectivePlotArea(bBox, effectivePlotArea, val) { var conf = this.conf, padding = conf.padding; if (this.conf.legendPosition === 'bottom') { effectivePlotArea.height = val; bBox.height = val + 2 * padding.v; } else { effectivePlotArea.width = val; bBox.width = val + 2 * padding.h; } }; return LegendBody; }(); var LegendLabels = function () { function LegendLabels(conf) { _classCallCheck(this, LegendLabels); this.conf = conf; this.node = []; this._id = 'GL_LABELS'; } LegendLabels.prototype.configure = function configure(conf) { this.conf = conf; }; LegendLabels.prototype.getType = function getType() { return 'label'; }; LegendLabels.prototype.getName = function getName() { return 'LegendLabel'; }; LegendLabels.prototype.getEffectivePlotArea = function getEffectivePlotArea(area) { var conf = this.conf, padding = conf.padding; // The logical rect inside which the composition are drawn area.height -= 2 * padding.v; area.width -= 2 * padding.h; area.x += padding.h; area.y += padding.v; return area; }; LegendLabels.prototype.getLogicalSpace = function getLogicalSpace(bBox, options, recalculate) { var isLegendPosBottom = this.conf.legendPosition === 'bottom', lSpace = this._lSpace, conf = this.conf, padding = conf.padding, cRange, smartLabel, crDataObj, index, length, labelHeights = [], leftBound, rightBound, plotArea, label, valueRatio, stop, zerothStop, lsTexts, maxHeight, effectivePlotArea, testSmartLabel, // noOfLabels = 0, nextRefPoint, currPoint, leftStop, smartText, ni, copyOfStyle, chartConfig = options.gLegend.getFromEnv('chartConfig'), normalizedDataArr = [], effectivePlotAreaWH; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } cRange = options.colorRange; smartLabel = options.smartLabel; valueRatio = cRange.getCumulativeValueRatio(); crDataObj = cRange.colorRange; lSpace = this._lSpace = { bound: { height: 0, width: 0 }, node: { logicArea: UNDEF, smartTexts: [] } }; lsTexts = lSpace.node.smartTexts; plotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea = this.getEffectivePlotArea(plotArea); effectivePlotAreaWH = isLegendPosBottom ? effectivePlotArea.width : effectivePlotArea.height; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); copyOfStyle = merge(conf.style, {}); normalizeFontSizeAppend(this._metaStyle = copyOfStyle); smartLabel.setStyle(copyOfStyle); testSmartLabel = smartLabel.getSmartText('W'); for (index = 0, length = crDataObj.length; index < length; index++) { label = crDataObj[index].label; if (!label) { lsTexts[index] = UNDEF; continue; } // noOfLabels++; normalizedDataArr.push({ oriIndex: index, label: label }); } length = normalizedDataArr.length; if (length === 0) { return { height: 0, width: 0 }; } if (length > 1) { stop = (valueRatio[normalizedDataArr[length - 1].oriIndex] - valueRatio[normalizedDataArr[0].oriIndex]) / 2 * effectivePlotAreaWH / 100; } else { stop = Math.max(valueRatio[normalizedDataArr[0].oriIndex], 100 - valueRatio[normalizedDataArr[0].oriIndex]) / 2 * effectivePlotAreaWH / 100; } zerothStop = stop; // first scale Label if (isLegendPosBottom) { smartText = smartLabel.getSmartText(normalizedDataArr[0].label, zerothStop, effectivePlotArea.height); smartText.x = valueRatio[normalizedDataArr[0].oriIndex] * effectivePlotArea.width / 100; leftBound = smartText.x + smartText.width; } else { smartText = smartLabel.getSmartText(normalizedDataArr[0].label, zerothStop, effectivePlotArea.width); smartText.y = valueRatio[normalizedDataArr[0].oriIndex] * effectivePlotArea.height / 100; leftBound = smartText.y + smartText.width; } labelHeights.push(smartText.height); lsTexts[normalizedDataArr[0].oriIndex] = smartText; // last scale label if (isLegendPosBottom) { smartText = smartLabel.getSmartText(normalizedDataArr[length - 1].label, zerothStop, effectivePlotArea.height); smartText.x = valueRatio[normalizedDataArr[length - 1].oriIndex] * effectivePlotArea.width / 100; rightBound = smartText.x - smartText.width; } else { smartText = smartLabel.getSmartText(normalizedDataArr[length - 1].label, zerothStop, effectivePlotArea.width); smartText.y = valueRatio[normalizedDataArr[length - 1].oriIndex] * effectivePlotArea.height / 100; rightBound = smartText.y - smartText.width; } labelHeights.push(smartText.height); lsTexts[normalizedDataArr[length - 1].oriIndex] = smartText; leftStop = leftBound; for (index = 1; index < length - 1; index++) { label = normalizedDataArr[index].label; ni = normalizedDataArr[index].oriIndex; smartText = UNDEF; nextRefPoint = index + 1 === length - 1 ? rightBound : valueRatio[normalizedDataArr[index + 1].oriIndex] * effectivePlotAreaWH / 100; currPoint = valueRatio[normalizedDataArr[index].oriIndex] * effectivePlotAreaWH / 100; stop = Math.min(currPoint - leftStop, nextRefPoint - currPoint); if (stop > 2 * testSmartLabel.width) { if (isLegendPosBottom) { smartText = smartLabel.getSmartText(label, stop, effectivePlotArea.height); smartText.x = valueRatio[ni] * effectivePlotArea.width / 100; } else { smartText = smartLabel.getSmartText(label, stop, effectivePlotArea.width); smartText.y = valueRatio[ni] * effectivePlotArea.height / 100; } leftStop = stop; labelHeights.push(smartText.height); } lsTexts[normalizedDataArr[index].oriIndex] = smartText; } maxHeight = Math.max.apply(Math, labelHeights); if (isLegendPosBottom) { effectivePlotArea.height = maxHeight; bBox.height = maxHeight + 2 * padding.v; } else { effectivePlotArea.width = maxHeight; bBox.width = maxHeight + 2 * padding.v; } lSpace.node.logicArea = effectivePlotArea; lSpace.bound = bBox; return bBox; }; LegendLabels.prototype.draw = function draw() { var isLegendPosBottom = this.conf.legendPosition === 'bottom', layer, bound, conf = this.conf, boundStyle = conf.bound && conf.bound.style || { stroke: 'none' }, legendLabelsGroup, bBox, smartText, lSpace, options, index, logicArea, lsTexts, length, pos = {}, animationManager; if (arguments.length >= 2 && arguments[1]) { bBox = arguments[0]; options = arguments[1]; } else if (arguments.length >= 1) { options = arguments[0]; } animationManager = options.animationManager; layer = options.parentLayer; this.getLogicalSpace(bBox, options); lSpace = this._lSpace; logicArea = lSpace.node.logicArea; lsTexts = lSpace.node.smartTexts; this.group = legendLabelsGroup = animationManager.setAnimation({ el: this.group || 'group', attr: { name: 'legend-labels' }, container: layer, component: gLegendRef }); this.bound = bound = animationManager.setAnimation({ el: this.bound || 'rect', attr: lSpace.bound, css: boundStyle, container: legendLabelsGroup, component: gLegendRef }); for (var i = 0; i < this.node.length; i++) { this.node[i].remove(); } this.node = []; for (index = 0, length = lsTexts.length; index < length; index++) { smartText = lsTexts[index]; if (!smartText) { continue; } if (isLegendPosBottom) { pos.y = logicArea.y + smartText.height / 2; if (index === length - 1) { pos.x = logicArea.x + smartText.x - smartText.width / 2; } else if (index) { pos.x = logicArea.x + smartText.x; } else { pos.x = logicArea.x + smartText.x + smartText.width / 2; } } else { pos.x = logicArea.x + smartText.height / 2; if (index === length - 1) { pos.y = logicArea.y + smartText.y - smartText.width / 2; } else if (index) { pos.y = logicArea.y + smartText.y; } else { pos.y = logicArea.y + smartText.y + smartText.width / 2; } } this.node.push(animationManager.setAnimation({ el: 'text', attr: { text: smartText.text, x: pos.x, y: pos.y, lineHeight: this._metaStyle.lineHeight, fill: conf.style.fill, transform: isLegendPosBottom ? 'R0' : 'R270,' + pos.x + ',' + pos.y }, container: legendLabelsGroup, component: gLegendRef })); } return { group: legendLabelsGroup, bound: bound, node: this.node }; }; return LegendLabels; }(); var LegendAxis = function () { function LegendAxis(conf) { _classCallCheck(this, LegendAxis); this.conf = conf; this._id = 'FL_AXIS'; this.node = UNDEF; this.group = UNDEF; this.shadow = UNDEF; this.markerLine = UNDEF; this.compositionsByCategory = {}; } LegendAxis.prototype.configure = function configure(conf) { this.conf = conf; }; LegendAxis.prototype.getName = function getName() { return 'LegendAxis'; }; LegendAxis.prototype.getType = function getType() { return 'axis'; }; LegendAxis.prototype.addCompositions = function addCompositions(instance, category) { this.compositionsByCategory[category] = instance; }; LegendAxis.prototype.getLogicalSpace = function getLogicalSpace() { var isLegendPosBottom = this.conf.legendPosition === 'bottom', bBox = arguments[0], recalculate = arguments[2], lSpace = this._lSpace, conf = this.conf, padding = conf.padding, spaceTakenLower, spaceTakenUpper, spaceTaken, axisThickness = conf.legendAxisHeight, compositionsByCategory = this.compositionsByCategory, sliderG, effectivePlotArea, slider, sliderSpace, sliderExtraDiam = 0; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } lSpace = this._lSpace = { bound: { height: 0, width: 0 }, node: { logicArea: UNDEF } }; effectivePlotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea.height -= 2 * padding.v; effectivePlotArea.width -= 2 * padding.h; effectivePlotArea.x += padding.h; effectivePlotArea.y += padding.v; spaceTakenLower = axisThickness / 2 + conf.line.offset; spaceTakenUpper = axisThickness / 2; sliderG = compositionsByCategory[compositionKeys.RANGE]; if (sliderG) { slider = sliderG.sliders['false']; sliderSpace = slider.conf.outerCircle.rFactor * axisThickness; spaceTakenUpper += sliderExtraDiam = Math.max(sliderSpace / 2 - axisThickness / 2, 0); } // @todo Change the height and width of bBox if (isLegendPosBottom) { effectivePlotArea.y += sliderExtraDiam; effectivePlotArea.height = spaceTaken = spaceTakenUpper + spaceTakenLower + sliderExtraDiam; bBox.height = spaceTaken + 2 * padding.v; } else { effectivePlotArea.x += sliderExtraDiam; effectivePlotArea.width = spaceTaken = spaceTakenUpper + spaceTakenLower + sliderExtraDiam; bBox.width = spaceTaken + 2 * padding.v; } lSpace.node.logicArea = effectivePlotArea; lSpace.bound = bBox; return bBox; }; LegendAxis.prototype.getDrawableAxisArea = function getDrawableAxisArea(parentBoundingRect) { var conf = this.conf, isLegendPosBottom = this.conf.legendPosition === 'bottom', x = parentBoundingRect.x, y = parentBoundingRect.y, width = isLegendPosBottom ? parentBoundingRect.width : conf.legendAxisHeight, height = isLegendPosBottom ? conf.legendAxisHeight : parentBoundingRect.height, r = conf.legendAxisHeight / 2; return { x: x, y: y, width: width, height: height, r: r }; }; // eslint-disable-next-line LegendAxis.prototype.preDrawingRangeParamV = function preDrawingRangeParamV(drawableArea) { var x = drawableArea.x + drawableArea.width / 2, calculationBase = drawableArea.width; return { x: x, calculationBase: calculationBase, rangeStart: drawableArea.y, rangeEnd: drawableArea.y + drawableArea.height, prop: 'x' }; }; // eslint-disable-next-line LegendAxis.prototype.preDrawingRangeParamH = function preDrawingRangeParamH(drawableArea) { var y = drawableArea.y + drawableArea.height / 2, calculationBase = drawableArea.height; return { y: y, calculationBase: calculationBase, rangeStart: drawableArea.x, rangeEnd: drawableArea.x + drawableArea.width, prop: 'y' }; }; LegendAxis.prototype.preDrawingRangeParam = function preDrawingRangeParam(drawableArea) { return this.conf.legendPosition === 'bottom' ? this.preDrawingRangeParamH(drawableArea) : this.preDrawingRangeParamV(drawableArea); }; LegendAxis.prototype.getScaleMarkerPathStrH = function getScaleMarkerPathStrH(oriAxisRect, valueRatio) { var axisRect = merge(oriAxisRect, {}), conf = this.conf, lineAttr = conf.line, index, length, ratio, covered, markerStartY, tickStr = '', lineStr = ''; axisRect.x += axisRect.r; axisRect.width -= 2 * axisRect.r; markerStartY = axisRect.y + axisRect.height; for (index = 0, length = valueRatio.length; index < length; index++) { ratio = valueRatio[index]; covered = axisRect.x + ratio * axisRect.width / 100; tickStr += M + covered + COMMA_STR + (markerStartY - lineAttr.grooveLength) + L + covered + COMMA_STR + (markerStartY + lineAttr.offset); } lineStr += M + axisRect.x + COMMA_STR + (markerStartY + lineAttr.offset) + L + (axisRect.x + axisRect.width) + COMMA_STR + (markerStartY + lineAttr.offset); return tickStr + lineStr; }; // eslint-disable-next-line LegendAxis.prototype.getColorGradientH = function getColorGradientH(colorRange) { return { axis: colorRange.getBoxFill(), shadow: (0, _lib.toRaphaelColor)({ FCcolor: { alpha: '25,0,0', angle: 90, color: '000000,FFFFFF,FFFFFF', ratio: '0,30,40' } }) }; }; LegendAxis.prototype.draw = function draw() { var layer, // bound, conf = this.conf, boundAttr = conf.bound || {}, lineAttr = conf.line, boundStyle = boundAttr.style || {}, // node, bBox, category, compositionsByCategory = this.compositionsByCategory, cRange, valueRatio, composition, // compositionMes, legendAxisGroup, rangeParams, grad, oriAxisRect, lSpace, options, animationManager, scaleLine; if (arguments.length >= 2) { bBox = arguments[0]; options = arguments[1]; } else if (arguments.length >= 1) { options = arguments[0]; } animationManager = options.animationManager; layer = options.parentLayer; cRange = options.colorRange; valueRatio = cRange.getCumulativeValueRatio(); this.getLogicalSpace(bBox, options); lSpace = this._lSpace; this.group = legendAxisGroup = animationManager.setAnimation({ el: this.group || 'group', attr: { name: 'legend-axis' }, container: layer, component: gLegendRef }); this.bound = animationManager.setAnimation({ el: this.bound || 'rect', attr: lSpace.bound, css: boundStyle, component: gLegendRef, container: legendAxisGroup }); oriAxisRect = this.getDrawableAxisArea(lSpace.node.logicArea); grad = this.getColorGradient(cRange); conf.style.fill = grad.axis; conf.shadow.style.fill = grad.shadow; this.node = animationManager.setAnimation({ el: this.node || 'rect', attr: oriAxisRect, css: conf.style, container: legendAxisGroup, component: gLegendRef }); this.shadow = animationManager.setAnimation({ el: this.shadow || 'rect', attr: oriAxisRect, css: conf.shadow.style, container: legendAxisGroup, component: gLegendRef }); scaleLine = this.getScaleMarkerPathStr(oriAxisRect, valueRatio); this.path = animationManager.setAnimation({ el: this.path || 'path', attr: { path: scaleLine }, css: lineAttr.style, container: legendAxisGroup, component: gLegendRef }); for (category in compositionsByCategory) { composition = compositionsByCategory[category]; switch (category) { case compositionKeys.RANGE: rangeParams = this.preDrawingRangeParam(oriAxisRect); options[rangeParams.prop] = rangeParams[rangeParams.prop]; options.key = rangeParams.prop; options.rCalcBase = rangeParams.calculationBase; options.parentLayer = legendAxisGroup; composition.draw(rangeParams.rangeStart, rangeParams.rangeEnd, options); } } }; LegendAxis.prototype.getScaleMarkerPathStr = function getScaleMarkerPathStr(oriAxisRect, valueRatio) { return this.conf.legendPosition === 'bottom' ? this.getScaleMarkerPathStrH(oriAxisRect, valueRatio) : this.getScaleMarkerPathStrV(oriAxisRect, valueRatio); }; LegendAxis.prototype.getColorGradient = function getColorGradient(colorRange) { return this.conf.legendPosition === 'bottom' ? this.getColorGradientH(colorRange) : this.getColorGradientV(colorRange); }; LegendAxis.prototype.getScaleMarkerPathStrV = function getScaleMarkerPathStrV(oriAxisRect, valueRatio) { var axisRect = merge(oriAxisRect, {}), conf = this.conf, lineAttr = conf.line, index, ratio, length, markerStartX, covered, tickStr = '', lineStr = ''; axisRect.y += axisRect.r; axisRect.height -= 2 * axisRect.r; markerStartX = axisRect.x + axisRect.width; for (index = 0, length = valueRatio.length; index < length; index++) { ratio = valueRatio[index]; covered = axisRect.y + ratio * axisRect.height / 100; tickStr += M + (markerStartX - lineAttr.grooveLength) + COMMA_STR + covered + L + (markerStartX + lineAttr.offset) + COMMA_STR + covered; } lineStr += M + (markerStartX + lineAttr.offset) + COMMA_STR + axisRect.y + L + (markerStartX + lineAttr.offset) + COMMA_STR + (axisRect.y + axisRect.height); return tickStr + lineStr; }; // eslint-disable-next-line LegendAxis.prototype.getColorGradientV = function getColorGradientV(colorRange) { return { axis: colorRange.getBoxFill(true), shadow: (0, _lib.toRaphaelColor)({ FCcolor: { alpha: '25,0,0', angle: 360, color: '000000,FFFFFF,FFFFFF', ratio: '0,30,40' } }) }; }; return LegendAxis; }(); var Slider = function () { function Slider(sliderIndex, options, id) { _classCallCheck(this, Slider); this.conf = options.conf; this.sliderIndex = sliderIndex; this.rangeGroup = options.sliderGroup; this._id = id; this.node = UNDEF; this.tracker = UNDEF; this.currPos = 0; this.swing = []; } Slider.prototype.configure = function configure(sliderIndex, options, id) { this.conf = options.conf; this.sliderIndex = sliderIndex; this.rangeGroup = options.sliderGroup; this._id = id; this.currPos = 0; this.swing = []; }; Slider.prototype.getType = function getType() { return 'slider'; }; Slider.prototype.getName = function getName() { return 'Slider'; }; Slider.prototype.updateSwingRange = function updateSwingRange(index, value) { this.swing[+index] = value; }; // @todo: Who should be responsible for reset, range or individual slider // Slider.prototype.reset = function () { // var node = this.node, // tracker = this.tracker, // conf = this.conf, // dragAPI; // if (!node) { // return; // } // node.attr({ // transform: 't0,0' // }); // this.currPos = 0; // this.swing = []; // }; Slider.prototype.draw = function draw(rangeStart, scaleVal, position, options) { var layer = options.parentLayer, self = this, animationManager = options.animationManager, conf = this.conf, ocConf = conf.outerCircle, icConf = conf.innerCircle, tooltext, chartConfig = animationManager.getFromEnv('chart').config, ocRadius = Math.ceil(ocConf.rFactor * options.rCalcBase / 2), icRadius = Math.ceil(icConf.rFactor * options.rCalcBase / 2), icThickness = ocRadius - icRadius, group, toolTipController = options.gLegend.getFromEnv('toolTipController'), sliderIndex = this.sliderIndex, dragAPI, strokeWidthOffset, x, y, tracker; conf.outerRadius = ocRadius; conf.innerRadius = icRadius; this._scaleVal = scaleVal; icConf.style['stroke-width'] = icThickness; strokeWidthOffset = Math.ceil(ocConf.style['stroke-width'] / 2); icRadius += strokeWidthOffset; group = this.node = animationManager.setAnimation({ el: this.node || 'group', attr: { 'name': 'fc-gl-slider', 'cursor': 'pointer', 'transform': 't0,0' }, container: layer, component: gLegendRef }); if (options.key === 'x') { x = position; y = rangeStart; y += sliderIndex ? -icRadius : +icRadius; } else { x = rangeStart; y = position; x += sliderIndex ? -icRadius : +icRadius; } this.oCircle = animationManager.setAnimation({ el: this.oCircle || 'circle', attr: { cx: x, cy: y, r: ocRadius }, css: ocConf.style, container: group, component: gLegendRef }); this.iCircle = animationManager.setAnimation({ el: this.iCircle || 'circle', attr: { cx: x, cy: y, r: icRadius }, css: icConf.style, container: group, component: gLegendRef }); tracker = this.tracker = animationManager.setAnimation({ el: this.tracker || 'circle', attr: { cx: x, cy: y, r: ocRadius + 5, fill: TRACKER_FILL, stroke: TRACKER_FILL, cursor: 'pointer' }, container: group, component: gLegendRef }); group.attr({ transform: options.key === 'x' ? 't0,' + self.currPos : 't' + self.currPos + ',' + 0 }); tooltext = chartConfig.showToolTip ? scaleVal : ''; toolTipController.enableToolTip(tracker, tooltext); this._dragAPI = dragAPI = this.getDragAPI(options.key === 'x'); tracker.undrag(); tracker.drag(dragAPI.dragging, dragAPI.dragStart, dragAPI.dragEnd); return { translateAscending: ocRadius + strokeWidthOffset }; }; Slider.prototype.getDragAPI = function getDragAPI(verticalDragging) { var self = this, node = self.node, index = self.sliderIndex, range = self.rangeGroup, swing, lastDisplacement, timeoutId, innerRadius = self.conf.innerRadius, spaceSaved = innerRadius, isDragged; return { dragging: function dragging(event) { var left, right, d, updatedText, posAfterDisplacement; event.stopPropagation(); if (verticalDragging) { d = event.data[1]; } else { d = event.data[0]; } if (index) { left = swing[0] - swing[1] + spaceSaved; right = 0; } else { left = 0; right = swing[1] - swing[0] - spaceSaved; } // position after displacement according to start position posAfterDisplacement = self.currPos + d; if (posAfterDisplacement < left) { // If drag exceeds leftmost position, pointer should not exceed the left end. d += left - posAfterDisplacement; } else if (posAfterDisplacement > right) { // If drag exceeds rightmost position, pointer should not exceed the right end. d -= posAfterDisplacement - right; } node.attr({ transform: verticalDragging ? 't0,' + (self.currPos + d) : 't' + (self.currPos + d) + ',' + 0 }); lastDisplacement = d; timeoutId && clearTimeout(timeoutId); timeoutId = setTimeout(function () { range.updateWhenInRest(self, self.currPos + d); }, 100); updatedText = range.updateWhenInMove(self, self.currPos + d); // update the data in tooltip element self.conf.showTooltip && self.tracker.data('__FC_tooltipText', updatedText); isDragged = true; return true; }, dragStart: function dragStart(event) { event.stopPropagation(); swing = self.swing; isDragged = false; range.dragStarted(self); }, dragEnd: function dragEnd() { var newPos; range.dragCompleted(self, isDragged, self.currPos + lastDisplacement); if (!isDragged) { return; } timeoutId && clearTimeout(timeoutId); timeoutId = setTimeout(function () { range.updateWhenInRest(self, self.currPos); }, 100); self.currPos += lastDisplacement; newPos = swing[+index] + self.currPos; range.updateRange(self, newPos); } }; }; Slider.prototype.dispose = function dispose() { this.node.remove(); this.oCircle.remove(); this.iCircle.remove(); this.tracker.remove(); delete this; }; return Slider; }(); var SliderGroup = function () { function SliderGroup(conf) { _classCallCheck(this, SliderGroup); var sliderConf = conf, options = {}; this._id = 'GL_SG1'; this.conf = conf; options.conf = sliderConf; this.extremes = []; this.sliders = {}; this.min = undefined; this.max = undefined; options.sliderGroup = this; this.valueRange = []; this.callbacks = []; this.sliders[FORMER_SLIDER_INDEX] = new Slider(FORMER_SLIDER_INDEX, options, this._id + '_' + +FORMER_SLIDER_INDEX); this.sliders[LATER_SLIDER_INDEX] = new Slider(LATER_SLIDER_INDEX, options, this._id + '_' + +LATER_SLIDER_INDEX); } SliderGroup.prototype.configure = function configure(conf) { var sliderConf = conf, options = {}; this.min = undefined; this.max = undefined; this.conf = conf; options.conf = sliderConf; options.sliderGroup = this; this.sliders[FORMER_SLIDER_INDEX].configure(FORMER_SLIDER_INDEX, options, this._id + '_' + +FORMER_SLIDER_INDEX); this.sliders[LATER_SLIDER_INDEX].configure(LATER_SLIDER_INDEX, options, this._id + '_' + +LATER_SLIDER_INDEX); }; SliderGroup.prototype.getType = function getType() { return 'slider'; }; SliderGroup.prototype.getName = function getName() { return 'SliderGroup'; }; SliderGroup.prototype.initRange = function initRange(slider, updatedRange) { var sliderIndex = slider.sliderIndex; this.extremes[+sliderIndex] = updatedRange; }; SliderGroup.prototype.updateRange = function updateRange(slider, updatedRange) { var sliderIndex = slider.sliderIndex, sliders = this.sliders, s = sliders[!sliderIndex]; s.updateSwingRange(sliderIndex, updatedRange); }; SliderGroup.prototype.reset = function reset() { var options = {}; options.conf = this.conf; options.sliderGroup = this; this.min = undefined; this.max = undefined; // @todo do it from a more generalized way this.sliders[FORMER_SLIDER_INDEX].configure(FORMER_SLIDER_INDEX, options, this._id + '_' + +FORMER_SLIDER_INDEX); this.sliders[LATER_SLIDER_INDEX].configure(LATER_SLIDER_INDEX, options, this._id + '_' + +LATER_SLIDER_INDEX); this.draw.apply(this, this._drawParams); }; SliderGroup.prototype.draw = function draw(rangeStart, rangeEnd, options) { var sliders = this.sliders, lSlider = sliders[FORMER_SLIDER_INDEX], rSlider = sliders[LATER_SLIDER_INDEX], cRange = options.colorRange, colorRange = cRange.colorRange, oneSliderMes, icConf, ocConf, icRadius, extremesRange, mapbypercent = cRange.data.mapByPercent, numberFormatter = options.gLegend.getFromEnv('number-formatter'), totalRange; this._fcChart = options.gLegend.getFromEnv('chart'); this.getValueFormPixel = function (valueStart, valueEnd, pixelStart, pixelEnd) { var unit = (valueEnd - valueStart) / (pixelEnd - pixelStart); this.getValueFormPixel = function (pixel) { return valueStart + unit * pixel; }; }; this.updateWhenInMove = function (numberFormatter, mapByPercent) { this.updateWhenInMove = function (slider, val) { var extremes = this.extremes, sliderIndex = slider.sliderIndex, nVal, value; if (sliderIndex) { nVal = extremes[1] - extremes[0] + val; } else { nVal = val; } value = this.getValueFormPixel(nVal); if (!mapByPercent) { value = numberFormatter.legendValue(value); } else { value = parseFloat(value).toFixed(2) + PERCENT_STR; } return value; }; }; this._drawParams = [rangeStart, rangeEnd, options]; this.updateWhenInMove(numberFormatter, mapbypercent); ocConf = lSlider.conf.outerCircle; icConf = lSlider.conf.innerCircle; icRadius = Math.ceil(icConf.rFactor * options.rCalcBase / 2); icRadius += Math.ceil(ocConf.style['stroke-width'] / 2); // calculate the extremes when drawn(resized/rendered) this.extremes[0] = rangeStart + icRadius; this.extremes[1] = rangeEnd - icRadius; extremesRange = this.extremes[1] - this.extremes[0]; // take the min and max values if present already(condition in resize) else take the limit from colorrange(condition on render) this.min = this.min ? this.min : colorRange[0].value; this.max = this.max ? this.max : colorRange[colorRange.length - 1].value; totalRange = colorRange[colorRange.length - 1].value - colorRange[0].value; // calculate the current position of both the sliders lSlider.currPos = extremesRange * (this.min - colorRange[0].value) / totalRange; rSlider.currPos = extremesRange * (this.max - colorRange[0].value) / totalRange - extremesRange; // draw the sliders oneSliderMes = lSlider.draw(rangeStart, mapbypercent ? numberFormatter.legendPercentValue(this.min) : numberFormatter.legendValue(this.min), options[options.key], options); oneSliderMes = rSlider.draw(rangeEnd, mapbypercent ? numberFormatter.legendPercentValue(this.max) : numberFormatter.legendValue(this.max), options[options.key], options); lSlider.swing = this.extremes.slice(0); rSlider.swing = this.extremes.slice(0); // update the swing values of both sliders (i.e. upto which range it can be moved) lSlider.swing[1] += rSlider.currPos; rSlider.swing[0] += lSlider.currPos; this.getValueFormPixel(colorRange[0].value, colorRange[colorRange.length - 1].value, this.extremes[0], this.extremes[1]); return oneSliderMes; }; SliderGroup.prototype.updateWhenInRest = function updateWhenInRest(slider, val) { var sliders = this.sliders, extremes = this.extremes, sliderIndex = slider.sliderIndex, lValue, rValue; if (sliderIndex) { lValue = sliders[!sliderIndex].currPos; rValue = extremes[1] - extremes[0] + val; } else { lValue = val; rValue = extremes[1] - extremes[0] + sliders[!sliderIndex].currPos; } // update the min and max values when slider comes to rest after dragging. this.min = Number(this.getValueFormPixel(lValue).toFixed(2)); this.max = Number(this.getValueFormPixel(rValue).toFixed(2)); this.gLegend.fireEvent('rangeUpdated', [{ min: this.min, max: this.max }]); }; SliderGroup.prototype.dragStarted = function dragStarted(self) { var sliders = this.sliders, extremes = this.extremes, conf = self.conf, chart = this._fcChart; chart.fireChartInstanceEvent('legendpointerdragstart', { pointerIndex: +self.sliderIndex, pointers: [{ value: this.getValueFormPixel(sliders['false'].currPos) }, { value: this.getValueFormPixel(extremes[1] - extremes[0] + sliders['true'].currPos) }], legendPointerHeight: conf.outerRadius, legendPointerWidth: conf.innerRadius, outerRadius: conf.outerRadius, innerRadius: conf.innerRadius }, [chart.id]); }; SliderGroup.prototype.dragCompleted = function dragCompleted(self, isDragged, newVal) { var sliders = this.sliders, extremes = this.extremes, conf = self.conf, minValue = this.getValueFormPixel(sliders['false'].currPos), maxValue = this.getValueFormPixel(extremes[1] - extremes[0] + sliders['true'].currPos), chart = this._fcChart, newMinValue, newMaxValue; if (!self.sliderIndex) { newMinValue = this.getValueFormPixel(newVal); newMaxValue = maxValue; } else { newMinValue = minValue; newMaxValue = this.getValueFormPixel(extremes[1] - extremes[0] + newVal); } if (isDragged) { chart.fireChartInstanceEvent('legendrangeupdated', { previousMinValue: minValue, previousMaxValue: maxValue, minValue: newMinValue, maxValue: newMaxValue }, [chart.id]); } chart.fireChartInstanceEvent('legendpointerdragstop', { pointerIndex: +self.sliderIndex, pointers: [{ value: newMinValue }, { value: newMaxValue }], legendPointerHeight: conf.outerRadius, legendPointerWidth: conf.innerRadius, outerRadius: conf.outerRadius, innerRadius: conf.innerRadius }, [chart.id]); }; SliderGroup.prototype.dispose = function dispose() { this.sliders[FORMER_SLIDER_INDEX].dispose(); this.sliders[LATER_SLIDER_INDEX].dispose(); }; return SliderGroup; }(); var LegendValues = function (_LegendLabels) { _inherits(LegendValues, _LegendLabels); function LegendValues() { _classCallCheck(this, LegendValues); var _this2 = _possibleConstructorReturn(this, _LegendLabels.call(this, arguments[0])); _this2._id = 'GL_VALUES'; _this2.node = []; return _this2; } LegendValues.prototype.configure = function configure(conf) { this.conf = conf; }; LegendValues.prototype.getName = function getName() { return 'LegendValues'; }; LegendValues.prototype.getType = function getType() { return 'legend'; }; LegendValues.prototype.getLogicalSpace = function getLogicalSpace(bBox, options, recalculate) { var isLegendPosBottom = this.conf.legendPosition === 'bottom', lSpace = this._lSpace, conf = this.conf, padding = conf.padding, chartConfig = options.gLegend.getFromEnv('chartConfig'), cRange, smartLabel, crDataObj, smartText, index, length, valueRatio, stop, nextRefPoint, currPoint, zerothStop, labelHeights = [], leftBound, leftStop, rightBound, labelWidths = [], topBound, topStop, bottomBound, maxHeight, maxWidth, effectivePlotArea, val, dispValue, testSmartLabel, copyOfStyle, lsTexts; if (lSpace && !recalculate) { lSpace.isImpure = true; // If logical space has already been calculated and recalculate flag is on, return without recalculating. return lSpace; } cRange = options.colorRange; smartLabel = options.smartLabel; crDataObj = cRange.colorRange; valueRatio = cRange.getCumulativeValueRatio(); lSpace = this._lSpace = { bound: { height: 0, width: 0 }, node: { logicArea: UNDEF, smartTexts: [] } }; lsTexts = lSpace.node.smartTexts; effectivePlotArea = merge(bBox, {}); // The logical rect inside which the composition are drawn effectivePlotArea.height -= 2 * padding.v; effectivePlotArea.width -= 2 * padding.h; effectivePlotArea.x += padding.h; effectivePlotArea.y += padding.v; smartLabel.useEllipsesOnOverflow(chartConfig.useEllipsesWhenOverflow); copyOfStyle = merge(conf.style, {}); normalizeFontSizeAppend(this._metaStyle = copyOfStyle); smartLabel.setStyle(copyOfStyle); testSmartLabel = smartLabel.getSmartText('W'); length = crDataObj.length; if (isLegendPosBottom) { zerothStop = stop = (valueRatio[length - 1] - valueRatio[0]) / 2 * effectivePlotArea.width / 100; // first scale Label dispValue = crDataObj[0].displayValue; smartText = smartLabel.getSmartText(typeof dispValue !== 'string' && dispValue !== UNDEF && dispValue.toString() || dispValue, zerothStop, effectivePlotArea.height); smartText.x = valueRatio[0] * effectivePlotArea.width / 100; leftBound = smartText.x + smartText.width; labelHeights.push(smartText.height); } else { zerothStop = stop = (valueRatio[length - 1] - valueRatio[0]) / 2 * effectivePlotArea.height / 100; // first scale Label smartText = smartLabel.getSmartText(crDataObj[0].displayValue, effectivePlotArea.width, zerothStop); smartText.y = valueRatio[0] * effectivePlotArea.height / 100; topBound = smartText.y + smartText.width; labelWidths.push(smartText.width); } lsTexts[0] = smartText; if (isLegendPosBottom) { // last scale label smartText = smartLabel.getSmartText(crDataObj[length - 1].displayValue, zerothStop, effectivePlotArea.height); smartText.x = valueRatio[length - 1] * effectivePlotArea.width / 100; rightBound = smartText.x - smartText.width; labelHeights.push(smartText.height); leftStop = leftBound; } else { smartText = smartLabel.getSmartText(crDataObj[length - 1].displayValue, effectivePlotArea.width, zerothStop); smartText.y = valueRatio[length - 1] * effectivePlotArea.height / 100; bottomBound = smartText.y - smartText.height; labelWidths.push(smartText.width); topStop = topBound; } lsTexts[length - 1] = smartText; for (index = 1; index < length - 1; index++) { smartText = UNDEF; val = crDataObj[index].displayValue; if (isLegendPosBottom) { nextRefPoint = index + 1 === length - 1 ? rightBound : valueRatio[index + 1] * effectivePlotArea.width / 100; currPoint = valueRatio[index] * effectivePlotArea.width / 100; stop = Math.min(currPoint - leftStop, nextRefPoint - currPoint); if (stop > 1.5 * testSmartLabel.width) { smartText = smartLabel.getSmartText(val, 2 * stop, effectivePlotArea.height); smartText.x = valueRatio[index] * effectivePlotArea.width / 100; leftStop = stop; labelHeights.push(smartText.height); } } else { nextRefPoint = index + 1 === length - 1 ? bottomBound : valueRatio[index + 1] * effectivePlotArea.height / 100; currPoint = valueRatio[index] * effectivePlotArea.height / 100; stop = Math.min(currPoint - topStop, nextRefPoint - currPoint); if (stop > 2 * testSmartLabel.height) { smartText = smartLabel.getSmartText(val, effectivePlotArea.width, 2 * stop); smartText.y = valueRatio[index] * effectivePlotArea.height / 100; topStop = stop; labelWidths.push(smartText.width); } } lsTexts[index] = smartText; } if (isLegendPosBottom) { maxHeight = Math.max.apply(Math, labelHeights); effectivePlotArea.height = maxHeight; bBox.height = maxHeight + 2 * padding.v; } else { maxWidth = Math.max.apply(Math, labelWidths); effectivePlotArea.width = maxWidth; bBox.width = maxWidth + 2 * padding.h; } lSpace.node.logicArea = effectivePlotArea; lSpace.bound = bBox; return bBox; }; LegendValues.prototype.draw = function draw() { var conf = this.conf, isLegendPosBottom = conf.legendPosition === 'bottom', boundStyle = conf.bound && conf.bound.style || { stroke: 'none' }, pos = {}, layer, bound, legendValuesGroup, bBox, lSpace, // smartLabel, logicArea, options, cRange, valueRatio, index, length, smartTexts, smartText, animationManager; if (arguments.length >= 2 && arguments[1]) { bBox = arguments[0]; options = arguments[1]; } else if (arguments.length >= 1) { options = arguments[0]; } animationManager = options.animationManager; layer = options.parentLayer; // smartLabel = options.smartLabel; cRange = options.colorRange; // numberFormatter = options.numberFormatter, valueRatio = cRange.getCumulativeValueRatio(); this.getLogicalSpace(bBox, options); lSpace = this._lSpace; logicArea = lSpace.node.logicArea; smartTexts = lSpace.node.smartTexts; this.group = legendValuesGroup = animationManager.setAnimation({ el: this.group || 'group', attr: { name: 'legend-values' }, container: layer, component: gLegendRef }); this.bound = bound = animationManager.setAnimation({ el: this.bound || 'rect', attr: lSpace.bound, css: boundStyle, container: legendValuesGroup, component: gLegendRef }); for (var i = 0; i < this.node.length; i++) { this.node[i].remove(); } this.node = []; for (index = 0, length = valueRatio.length; index < length; index++) { smartText = smartTexts[index]; if (!smartText) { continue; } if (isLegendPosBottom) { pos.y = logicArea.y + smartText.height / 2; if (index === length - 1) { pos.x = logicArea.x + smartText.x - smartText.width / 2; } else if (index) { pos.x = logicArea.x + smartText.x; } else { pos.x = logicArea.x + smartText.x + smartText.width / 2; } } else { pos.x = logicArea.x + smartText.width / 2; if (index === length - 1) { pos.y = logicArea.y + smartText.y - smartText.height / 2; } else if (index) { pos.y = logicArea.y + smartText.y; } else { pos.y = logicArea.y + smartText.y + smartText.height / 2; } } this.node.push(animationManager.setAnimation({ el: 'text', attr: { text: smartText.text, x: pos.x, y: pos.y, lineHeight: this._metaStyle.lineHeight, fill: conf.style.fill }, container: legendValuesGroup, component: gLegendRef })); } return { group: legendValuesGroup, bound: bound }; }; return LegendValues; }(LegendLabels); exports['default'] = GLegend; /***/ }), /* 944 */, /* 945 */, /* 946 */, /* 947 */, /* 948 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.getCoordinates = exports.getPlotFromPixel = exports.polarToCartesian = exports.cartesianToPolar = undefined; var _lib = __webpack_require__(125); var deg2Rad = function deg2Rad(theta) { return theta * (Math.PI / 180); }, rad2Deg = function rad2Deg(rad) { return rad * (180 / Math.PI); }, cartesianToPolar = function cartesianToPolar(x, y) { var r, theta; r = Math.sqrt(x * x + y * y); theta = rad2Deg(Math.atan(y / x)); if (x < 0 && y >= 0) { theta += 180; } else if (x < 0 && y < 0) { theta += 180; } else if (x > 0 && y < 0) { theta += 360; } return { radius: r, theta: deg2Rad(theta) }; }, polarToCartesian = function polarToCartesian(r, theta) { var degreeInRad = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var x, y; if (!degreeInRad) { theta = deg2Rad(theta); } x = r * Math.cos(theta); y = r * Math.sin(theta); return { x: x, y: y }; }, getCoordinates = function getCoordinates(values, axis) { var theta = void 0, scaleX = axis.getScale(), radius = values.radius, axisConfig = axis.config, centerX = axisConfig.axisDimention.centerX, centerY = axisConfig.axisDimention.centerY, point = void 0; radius = (0, _lib.pluckNumber)(radius, axisConfig.radius, 0); theta = scaleX.getRangeValue(values.theta); point = polarToCartesian(radius, theta); point.x += centerX; point.y += centerY; return point; }, getPlotFromPixel = function getPlotFromPixel(coordinates, axis) { var x = coordinates.x, y = coordinates.y, scaleX = axis.getScale(), theta = void 0, plot = void 0; plot = cartesianToPolar(x, y); theta = scaleX.getDomainValue(plot.theta); return rad2Deg(theta); }; exports.cartesianToPolar = cartesianToPolar; exports.polarToCartesian = polarToCartesian; exports.getPlotFromPixel = getPlotFromPixel; exports.getCoordinates = getCoordinates; /***/ }), /* 949 */, /* 950 */, /* 951 */, /* 952 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var fadeInAtAxisAppearing = [{ initialAttr: { opacity: 0 }, finalAttr: { opacity: 1 }, slot: 'axis' }]; exports['default'] = fadeInAtAxisAppearing; /***/ }), /* 953 */, /* 954 */, /* 955 */, /* 956 */, /* 957 */, /* 958 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _crossline = __webpack_require__(267); var _crossline2 = _interopRequireDefault(_crossline); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _crossline2['default']; /***/ }), /* 959 */, /* 960 */, /* 961 */, /* 962 */, /* 963 */, /* 964 */, /* 965 */, /* 966 */, /* 967 */, /* 968 */, /* 969 */, /* 970 */, /* 971 */, /* 972 */, /* 973 */, /* 974 */, /* 975 */, /* 976 */, /* 977 */, /* 978 */, /* 979 */, /* 980 */, /* 981 */, /* 982 */, /* 983 */, /* 984 */, /* 985 */, /* 986 */, /* 987 */, /* 988 */, /* 989 */, /* 990 */, /* 991 */, /* 992 */, /* 993 */, /* 994 */, /* 995 */, /* 996 */, /* 997 */, /* 998 */, /* 999 */, /* 1000 */, /* 1001 */, /* 1002 */, /* 1003 */, /* 1004 */, /* 1005 */, /* 1006 */, /* 1007 */, /* 1008 */, /* 1009 */, /* 1010 */, /* 1011 */, /* 1012 */, /* 1013 */, /* 1014 */, /* 1015 */, /* 1016 */, /* 1017 */, /* 1018 */, /* 1019 */, /* 1020 */, /* 1021 */, /* 1022 */, /* 1023 */, /* 1024 */, /* 1025 */, /* 1026 */, /* 1027 */, /* 1028 */, /* 1029 */, /* 1030 */, /* 1031 */, /* 1032 */, /* 1033 */, /* 1034 */, /* 1035 */, /* 1036 */, /* 1037 */, /* 1038 */, /* 1039 */, /* 1040 */, /* 1041 */, /* 1042 */, /* 1043 */, /* 1044 */, /* 1045 */, /* 1046 */, /* 1047 */, /* 1048 */, /* 1049 */, /* 1050 */, /* 1051 */, /* 1052 */, /* 1053 */, /* 1054 */, /* 1055 */, /* 1056 */, /* 1057 */, /* 1058 */, /* 1059 */, /* 1060 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.symbolList = undefined; var _dependencyManager = __webpack_require__(132); var Raphael = (0, _dependencyManager.getDep)('redraphael', 'plugin'), mathCos = Math.cos, mathSin = Math.sin, PI = Math.PI, symbolList = void 0; /* eslint require-jsdoc: 'error', valid-jsdoc: 'error' */ exports.symbolList = symbolList = { pinModeIcon: function pinModeIcon(posx, posy, rad) { var x = posx, y = posy, r = rad, r1 = r * 0.5, r2 = r - r1, x1 = x - r, x2 = x + r, x3 = x - r1, x4 = x + r1, x5 = x - 0.5, x6 = x + 0.5, x7 = x6 + 1, x8 = x6 + 1.5, y1 = y - r, y2 = y + r1, y3 = y - r1, y4 = y + r2, y5 = y + r + 0.5; return ['M', x1, y1, 'L', x3, y3, x3, y4, x1, y2, x5, y2, x, y5, x6, y2, x2, y2, x4, y4, x4, y3, x2, y1, x8, y1, x8, y3, x8, y4, x7, y4, x7, y3, x8, y3, x8, y1, 'Z']; }, zoomOutIcon: function zoomOutIcon(x, y, radius) { var icoX = x - radius * 0.2, icoY = y - radius * 0.2, rad = radius * 0.8, startAngle = Raphael.rad(43), endAngle = Raphael.rad(48), // to prevent cos and sin of start and end from becoming equal on 360 arcs startX = icoX + rad * mathCos(startAngle), startY = icoY + rad * mathSin(startAngle), endX = icoX + rad * mathCos(endAngle), endY = icoY + rad * mathSin(endAngle), handleHeight = radius, // the height of the handle handAngle = Raphael.rad(45), handX1 = startX + handleHeight * mathCos(handAngle), handY1 = startY + handleHeight * mathSin(handAngle), handX2 = endX + handleHeight * mathCos(handAngle), handY2 = endY + handleHeight * mathSin(handAngle), semiW = 2; return ['M', startX, startY, 'A', rad, rad, 0, 1, 0, endX, endY, 'Z', 'M', startX + 1, startY + 1, 'L', handX1, handY1, handX2, handY2, endX + 1, endY + 1, 'Z', 'M', icoX - semiW, icoY, 'L', icoX + semiW, icoY, 'Z']; }, resetIcon: function resetIcon(x, y, radius) { var r = radius, startX = x - r, startY = y, endAngle = (PI / 2 + PI) / 2, endX = x + r * mathCos(endAngle), endY = y + r * mathSin(endAngle), arrowLength = r * 2 / 3, paths = ['M', startX, startY, 'A', r, r, 0, 1, 1, endX, endY, 'L', endX + arrowLength, endY - 1, endX + 2, endY + arrowLength - 0.5, endX, endY]; return paths; }, zoomInIcon: function zoomInIcon(x, y, radius) { var icoX = x - radius * 0.2, icoY = y - radius * 0.2, rad = radius * 0.8, startAngle = Raphael.rad(43), // to prevent cos and sin of start and end from becoming equal on 360 arcs endAngle = Raphael.rad(48), startX = icoX + rad * mathCos(startAngle), startY = icoY + rad * mathSin(startAngle), endX = icoX + rad * mathCos(endAngle), endY = icoY + rad * mathSin(endAngle), handleHeight = radius, // the height of the handle handAngle = Raphael.rad(45), handX1 = startX + handleHeight * mathCos(handAngle), handY1 = startY + handleHeight * mathSin(handAngle), handX2 = endX + handleHeight * mathCos(handAngle) - 1, handY2 = endY + handleHeight * mathSin(handAngle) - 1, semiW = 2; return ['M', startX, startY, 'A', rad, rad, 0, 1, 0, endX, endY, 'Z', 'M', startX + 1, startY + 1, 'L', handX1, handY1, handX2, handY2, endX + 1, endY + 1, 'Z', 'M', icoX - semiW, icoY, 'L', icoX + semiW, icoY, 'Z', 'M', icoX, icoY - semiW, 'L', icoX, icoY + semiW, 'Z']; }, zoomModeIcon: function zoomModeIcon(cx, cy, radius) { var x = cx, path = [], y = cy, icoX = x - radius * 0.2, icoY = y - radius * 0.2, rad = radius * 0.8, startAngle = Raphael.rad(43), // to prevent cos and sin of start and end from becoming equal on 360 arcs endAngle = Raphael.rad(48), startX = icoX + rad * mathCos(startAngle), startY = icoY + rad * mathSin(startAngle), endX = icoX + rad * mathCos(endAngle), endY = icoY + rad * mathSin(endAngle), handleHeight = radius, // the height of the handle handAngle = Raphael.rad(45), handX1 = startX + handleHeight * mathCos(handAngle), handY1 = startY + handleHeight * mathSin(handAngle), handX2 = endX + handleHeight * mathCos(handAngle) - 1, handY2 = endY + handleHeight * mathSin(handAngle) - 1, semiW = 2; path = path.concat(['M', startX, startY, 'A', rad, rad, 0, 1, 0, endX, endY, 'Z', 'M', startX + 1, startY + 1, 'L', handX1, handY1, handX2, handY2, handX2 + 1, handY2 - 1, handX2 + 1.5, handY2 + 1.5, handX2 - 1, handY2 + 1, handX2, handY2, endX + 1, endY + 1, 'Z', 'M', icoX - semiW, icoY, 'L', icoX + semiW, icoY, 'Z', 'M', icoX, icoY - semiW, 'L', icoX, icoY + semiW, 'Z']); return path; }, panModeIcon: function panModeIcon(cx, cy, radius) { var x = cx - 45 / 4, y = cy; // draw the pan(move) icon. x = cx; radius *= 2.5; return [].concat(['M', x - radius / 16, y - radius / 8, 'L', x + radius / 16, y - radius / 8, 'L', x + radius / 16, y - radius / 3.2, 'L', x + 6 * radius / 32, y - 10 * radius / 32, 'L', x, y - radius / 2, 'L', x - 6 * radius / 32, y - 10 * radius / 32, 'L', x - radius / 16, y - radius / 3.2, 'Z', 'M', x + 4 * radius / 32, y - 2 * radius / 32, 'L', x + 10 * radius / 32, y - 2 * radius / 32, 'L', x + 10 * radius / 32, y - 6 * radius / 32, 'L', x + 16 * radius / 32, y, 'L', x + 10 * radius / 32, y + 6 * radius / 32, 'L', x + 10 * radius / 32, y + 2 * radius / 32, 'L', x + 4 * radius / 32, y + 2 * radius / 32, 'Z', 'M', x + 2 * radius / 32, y + 5 * radius / 32, 'L', x + 2 * radius / 32, y + 10 * radius / 32, 'L', x + 6 * radius / 32, y + 10 * radius / 32, 'L', x, y + 16 * radius / 32, 'L', x - 6 * radius / 32, y + 10 * radius / 32, 'L', x - 2 * radius / 32, y + 10 * radius / 32, 'L', x - 2 * radius / 32, y + 5 * radius / 32, 'Z', 'M', x - 4 * radius / 32, y - 2 * radius / 32, 'L', x - 10 * radius / 32, y - 2 * radius / 32, 'L', x - 10 * radius / 32, y - 6 * radius / 32, 'L', x - 16 * radius / 32, y, 'L', x - 10 * radius / 32, y + 6 * radius / 32, 'L', x - 10 * radius / 32, y + 2 * radius / 32, 'L', x - 4 * radius / 32, y + 2 * radius / 32, 'Z']); } }; exports.symbolList = symbolList; /***/ }), /* 1061 */, /* 1062 */, /* 1063 */, /* 1064 */, /* 1065 */, /* 1066 */, /* 1067 */, /* 1068 */, /* 1069 */, /* 1070 */, /* 1071 */, /* 1072 */, /* 1073 */, /* 1074 */, /* 1075 */, /* 1076 */, /* 1077 */, /* 1078 */, /* 1079 */, /* 1080 */, /* 1081 */, /* 1082 */, /* 1083 */, /* 1084 */, /* 1085 */, /* 1086 */, /* 1087 */, /* 1088 */, /* 1089 */, /* 1090 */, /* 1091 */, /* 1092 */, /* 1093 */, /* 1094 */, /* 1095 */, /* 1096 */, /* 1097 */, /* 1098 */, /* 1099 */, /* 1100 */, /* 1101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _columnMultiseries = __webpack_require__(516); var _columnMultiseries2 = _interopRequireDefault(_columnMultiseries); var _lib = __webpack_require__(125); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return 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) : _defaults(subClass, superClass); } /* eslint require-jsdoc: 'error', valid-jsdoc: ["error", { "requireReturn": false }] */ var UNDEF; /** * ColumnMultiSeriesgroup basically manages all the position of multiseries columns side by side. * suppose multiseries column chart contains 2 dataset now what will be the column width and * position to accomodate all the columns. This manager conveys the column width and position * for every column plots to its children */ var ColumnOverlappedgroup = function (_ColumnMultiSeriesgro) { _inherits(ColumnOverlappedgroup, _ColumnMultiSeriesgro); function ColumnOverlappedgroup() { _classCallCheck(this, ColumnOverlappedgroup); return _possibleConstructorReturn(this, _ColumnMultiSeriesgro.apply(this, arguments)); } /** * Sets the type of the component * @return {string} type */ ColumnOverlappedgroup.prototype.getType = function getType() { return 'group'; }; /** * Sets the name of the component * @return {string} name */ ColumnOverlappedgroup.prototype.getName = function getName() { return 'columnOverlappedGroup'; }; /** * function to calculate column position and width */ ColumnOverlappedgroup.prototype.setColumnPosition = function setColumnPosition() { var manager = this, chartAttr = manager.getFromEnv('chart-attrib'), xAxis = manager.getFromEnv('xAxis'), chart = manager.getFromEnv('chart'), oldNumOfColumns = manager.getFromEnv('numOfColumns'), definedGroupPadding = Math.max((0, _lib.pluckNumber)(chartAttr.plotspacepercent), 0), plotSpacePercent = Math.max((0, _lib.pluckNumber)(definedGroupPadding, 20) % 100, 0), groupPadding = plotSpacePercent / 200, xAxisZeroPos = xAxis.getPixel(0), xAxisFirstPos = xAxis.getPixel(1), maxColWidth = chart.isBar ? chart.config.maxBarHeight : chart.config.maxColWidth, groupMaxWidth = Math.abs(xAxisFirstPos - xAxisZeroPos), groupNetWidth = void 0, columnWidth = void 0, xPosFirst = void 0, xPosNext = void 0, isCrisp = true, groupNetHalfWidth = void 0, groupNetGapWidth = 4, count = 0, numOfColumns = 0; manager.addToEnv('groupMaxWidth', groupMaxWidth); manager._mapChildren(function (child) { if (!child.getState('removed') && child.getState('visible') !== false) { numOfColumns++; } }); manager.addToEnv('numOfColumns', numOfColumns); manager.addToEnv('numColDiff', (0, _lib.pluckNumber)(oldNumOfColumns - numOfColumns, 0)); if ((columnWidth = manager.getFromEnv('plotWidth')) === UNDEF) { columnWidth = (1 - definedGroupPadding * 0.01) * groupMaxWidth || Math.min(groupMaxWidth * (1 - groupPadding * 2), maxColWidth * (numOfColumns || 1)); } manager._mapChildren(function (child) { if (!child.getState('removed') && child.getState('visible') !== false) { child.addToEnv('plotWidth', columnWidth - columnWidth / numOfColumns * count); count++; } }); groupNetHalfWidth = groupNetWidth / 2; xPosFirst = xAxisZeroPos - groupNetHalfWidth; xPosNext = xAxisFirstPos - groupNetHalfWidth; if (xPosNext - (xPosFirst + groupNetWidth) < groupNetGapWidth) { isCrisp = false; } if (plotSpacePercent === 0) { isCrisp = true; } manager.addToEnv('isCrisp', isCrisp); }; return ColumnOverlappedgroup; }(_columnMultiseries2['default']); exports['default'] = ColumnOverlappedgroup; /***/ }) ])]); //# sourceMappingURL=http://localhost:3052/3.13.3-sr.1/map/source/fusioncharts.common.js.map