/*! * DevExtreme (dx.viz.debug.js) * Version: 17.1.5 * Build date: Tue Aug 01 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) { return installedModules[moduleId].exports } var module = installedModules[moduleId] = { exports: {}, id: moduleId, loaded: false }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.loaded = true; return module.exports } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.p = ""; return __webpack_require__(0) }([ /*!**************************!*\ !*** multi dx.viz.debug ***! \**************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! c:\Projects\DevExtreme\17.1\BuildLabel\Temp\DevExtreme.v17.1\repo\GitHub\js\bundles\dx.viz.js */ 659) }, , , , , /*!******************************************!*\ !*** ./js/bundles/modules/parts/core.js ***! \******************************************/ function(module, exports, __webpack_require__) { var DevExpress = __webpack_require__( /*! ../../../bundles/modules/core */ 6); DevExpress.framework = __webpack_require__( /*! ../../../bundles/modules/framework */ 91); __webpack_require__( /*! ../../../integration/angular */ 144); __webpack_require__( /*! ../../../integration/knockout */ 92); __webpack_require__( /*! ../../../localization/globalize/core */ 176); __webpack_require__( /*! ../../../localization/globalize/message */ 178); __webpack_require__( /*! ../../../localization/globalize/number */ 179); __webpack_require__( /*! ../../../localization/globalize/date */ 180); __webpack_require__( /*! ../../../localization/globalize/currency */ 181); __webpack_require__( /*! ../../../events/click */ 75); __webpack_require__( /*! ../../../events/contextmenu */ 165); __webpack_require__( /*! ../../../events/double_click */ 182); __webpack_require__( /*! ../../../events/drag */ 110); __webpack_require__( /*! ../../../events/hold */ 164); __webpack_require__( /*! ../../../events/hover */ 103); __webpack_require__( /*! ../../../events/pointer */ 76); __webpack_require__( /*! ../../../events/swipe */ 183); __webpack_require__( /*! ../../../events/transform */ 184); module.exports = DevExpress }, /*!************************************!*\ !*** ./js/bundles/modules/core.js ***! \************************************/ function(module, exports, __webpack_require__) { var DevExpress = window.DevExpress = window.DevExpress || {}; var errors = DevExpress.errors = __webpack_require__( /*! ../../core/errors */ 7); if (DevExpress._DEVEXTREME_BUNDLE_INITIALIZED) { throw errors.Error("E0024") } DevExpress._DEVEXTREME_BUNDLE_INITIALIZED = true; DevExpress.clientExporter = __webpack_require__( /*! ../../client_exporter */ 20); DevExpress.VERSION = __webpack_require__( /*! ../../core/version */ 19); DevExpress.Class = __webpack_require__( /*! ../../core/class */ 25); DevExpress.DOMComponent = __webpack_require__( /*! ../../core/dom_component */ 43); DevExpress.Component = __webpack_require__( /*! ../../core/component */ 48); DevExpress.registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57); DevExpress.devices = __webpack_require__( /*! ../../core/devices */ 53); DevExpress.Color = __webpack_require__( /*! ../../color */ 38); var $ = __webpack_require__( /*! ../../core/renderer */ 9); var compareVersions = __webpack_require__( /*! ../../core/utils/version */ 17).compare; if (compareVersions($.fn.jquery, [1, 10]) < 0) { throw errors.Error("E0012") } var animationFrame = __webpack_require__( /*! ../../animation/frame */ 59); DevExpress.requestAnimationFrame = function() { errors.log("W0000", "DevExpress.requestAnimationFrame", "15.2", "Use the 'DevExpress.utils.requestAnimationFrame' method instead."); return animationFrame.requestAnimationFrame.apply(animationFrame, arguments) }; DevExpress.cancelAnimationFrame = function() { errors.log("W0000", "DevExpress.cancelAnimationFrame", "15.2", "Use the 'DevExpress.utils.cancelAnimationFrame' method instead."); return animationFrame.cancelAnimationFrame.apply(animationFrame, arguments) }; DevExpress.EventsMixin = __webpack_require__( /*! ../../core/events_mixin */ 51); DevExpress.utils = {}; DevExpress.utils.requestAnimationFrame = animationFrame.requestAnimationFrame; DevExpress.utils.cancelAnimationFrame = animationFrame.cancelAnimationFrame; DevExpress.utils.initMobileViewport = __webpack_require__( /*! ../../mobile/init_mobile_viewport/init_mobile_viewport */ 60).initMobileViewport; DevExpress.utils.extendFromObject = __webpack_require__( /*! ../../core/utils/extend */ 11).extendFromObject; DevExpress.utils.createComponents = __webpack_require__( /*! ../../core/utils/dom */ 56).createComponents; DevExpress.utils.triggerShownEvent = __webpack_require__( /*! ../../core/utils/dom */ 56).triggerShownEvent; DevExpress.utils.triggerHidingEvent = __webpack_require__( /*! ../../core/utils/dom */ 56).triggerHidingEvent; DevExpress.utils.resetActiveElement = __webpack_require__( /*! ../../core/utils/dom */ 56).resetActiveElement; DevExpress.utils.findBestMatches = __webpack_require__( /*! ../../core/utils/common */ 14).findBestMatches; DevExpress.createQueue = __webpack_require__( /*! ../../core/utils/queue */ 62).create; DevExpress.utils.dom = __webpack_require__( /*! ../../core/utils/dom */ 56); DevExpress.utils.common = __webpack_require__( /*! ../../core/utils/common */ 14); DevExpress.utils.date = __webpack_require__( /*! ../../core/utils/date */ 63); DevExpress.utils.browser = __webpack_require__( /*! ../../core/utils/browser */ 23); DevExpress.utils.inflector = __webpack_require__( /*! ../../core/utils/inflector */ 39); DevExpress.utils.resizeCallbacks = __webpack_require__( /*! ../../core/utils/window */ 44).resizeCallbacks; DevExpress.utils.console = __webpack_require__( /*! ../../core/utils/console */ 13); DevExpress.utils.string = __webpack_require__( /*! ../../core/utils/string */ 18); DevExpress.utils.support = __webpack_require__( /*! ../../core/utils/support */ 61); DevExpress.processHardwareBackButton = __webpack_require__( /*! ../../mobile/process_hardware_back_button */ 64); DevExpress.viewPort = __webpack_require__( /*! ../../core/utils/view_port */ 55).value; DevExpress.hideTopOverlay = __webpack_require__( /*! ../../mobile/hide_top_overlay */ 65); DevExpress.formatHelper = __webpack_require__( /*! ../../format_helper */ 66); var config = DevExpress.config = __webpack_require__( /*! ../../core/config */ 15); Object.defineProperty(DevExpress, "rtlEnabled", { get: function() { errors.log("W0003", "DevExpress", "rtlEnabled", "16.1", "Use the 'DevExpress.config' method instead"); return config().rtlEnabled }, set: function(value) { errors.log("W0003", "DevExpress", "rtlEnabled", "16.1", "Use the 'DevExpress.config' method instead"); config({ rtlEnabled: value }) } }); Object.defineProperty(DevExpress, "designMode", { get: function() { return config().designMode }, set: function(value) { config({ designMode: value }) } }); DevExpress.animationPresets = __webpack_require__( /*! ../../animation/presets/presets */ 67).presets; DevExpress.fx = __webpack_require__( /*! ../../animation/fx */ 68); DevExpress.TransitionExecutor = __webpack_require__( /*! ../../animation/transition_executor/transition_executor */ 74).TransitionExecutor; DevExpress.AnimationPresetCollection = __webpack_require__( /*! ../../animation/presets/presets */ 67).PresetCollection; module.exports = DevExpress.events = {}; DevExpress.events.click = __webpack_require__( /*! ../../events/click */ 75); DevExpress.events.utils = __webpack_require__( /*! ../../events/utils */ 71); DevExpress.events.GestureEmitter = __webpack_require__( /*! ../../events/gesture/emitter.gesture */ 86); DevExpress.localization = __webpack_require__( /*! ../../localization */ 88); module.exports = DevExpress }, /*!***************************!*\ !*** ./js/core/errors.js ***! \***************************/ function(module, exports, __webpack_require__) { var errorUtils = __webpack_require__( /*! ./utils/error */ 8); module.exports = errorUtils({ E0001: "Method is not implemented", E0002: "Member name collision: {0}", E0003: "A class must be instantiated using the 'new' keyword", E0004: "The NAME property of the component is not specified", E0005: "Unknown device", E0006: "Unknown endpoint key is requested", E0007: "'Invalidate' method is called outside the update transaction", E0008: "Type of the option name is not appropriate to create an action", E0009: "Component '{0}' has not been initialized for an element", E0010: "Animation configuration with the '{0}' type requires '{1}' configuration as {2}", E0011: "Unknown animation type '{0}'", E0012: "jQuery version is too old. Please upgrade jQuery to 1.10.0 or later", E0013: "KnockoutJS version is too old. Please upgrade KnockoutJS to 2.3.0 or later", E0014: "The 'release' method shouldn't be called for an unlocked Lock object", E0015: "Queued task returned an unexpected result", E0017: "Event namespace is not defined", E0018: "DevExpress.ui.DevExpressPopup widget is required", E0020: "Template engine '{0}' is not supported", E0021: "Unknown theme is set: {0}", E0022: "LINK[rel=DevExpress-theme] tags must go before DevExpress included scripts", E0023: "Template name is not specified", E0024: "DevExtreme bundle already included", E0100: "Unknown validation type is detected", E0101: "Misconfigured range validation rule is detected", E0102: "Misconfigured comparison validation rule is detected", E0110: "Unknown validation group is detected", E0120: "Adapter for a DevExpressValidator component cannot be configured", E0121: "The onCustomItemCreating action should return an item or Promise of jQuery Deferred object resolved when an item is created", E4016: "The compileSetter(expr) method is called with 'self' passed as a parameter", W0000: "'{0}' is deprecated in {1}. {2}", W0001: "{0} - '{1}' option is deprecated in {2}. {3}", W0002: "{0} - '{1}' method is deprecated in {2}. {3}", W0003: "{0} - '{1}' property is deprecated in {2}. {3}", W0004: "Timeout for theme loading is over: {0}", W0005: "'{0}' event is deprecated in {1}. {2}", W0006: "Invalid recurrence rule: '{0}'", W0007: "'{0}' Globalize culture is not defined", W0008: "Invalid view name: '{0}'", W0009: "Invalid time zone name: '{0}'", W0010: "{0} is deprecated in {1}. {2}", W0011: "Number parsing is invoked while the parser is not defined", W0012: "Date parsing is invoked while the parser is not defined", W0013: "'{0}' file is deprecated in {1}. {2}" }) }, /*!********************************!*\ !*** ./js/core/utils/error.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ./extend */ 11).extend, consoleUtils = __webpack_require__( /*! ./console */ 13), stringUtils = __webpack_require__( /*! ./string */ 18), version = __webpack_require__( /*! ../version */ 19); var ERROR_URL = "http://js.devexpress.com/error/" + version.split(".").slice(0, 2).join("_") + "/"; module.exports = function(baseErrors, errors) { var exports = { ERROR_MESSAGES: extend(errors, baseErrors), Error: function() { return makeError($.makeArray(arguments)) }, log: function(id) { var method = "log"; if (/^E\d+$/.test(id)) { method = "error" } else { if (/^W\d+$/.test(id)) { method = "warn" } } consoleUtils.logger[method]("log" === method ? id : combineMessage($.makeArray(arguments))) } }; var combineMessage = function(args) { var id = args[0]; args = args.slice(1); return formatMessage(id, formatDetails(id, args)) }; var formatDetails = function(id, args) { args = [exports.ERROR_MESSAGES[id]].concat(args); return stringUtils.format.apply(this, args).replace(/\.*\s*?$/, "") }; var formatMessage = function(id, details) { return stringUtils.format.apply(this, ["{0} - {1}. See:\n{2}", id, details, ERROR_URL + id]) }; var makeError = function(args) { var id, details, message; id = args[0]; args = args.slice(1); details = formatDetails(id, args); message = formatMessage(id, details); return extend(new Error(message), { __id: id, __details: details }) }; return exports } }, /*!*****************************!*\ !*** ./js/core/renderer.js ***! \*****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! jquery */ 10); module.exports = $ }, /*!*************************!*\ !*** external "jQuery" ***! \*************************/ function(module, exports) { module.exports = jQuery }, /*!*********************************!*\ !*** ./js/core/utils/extend.js ***! \*********************************/ function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__( /*! ./type */ 12).isPlainObject; var extendFromObject = function(target, source, overrideExistingValues) { target = target || {}; for (var prop in source) { if (source.hasOwnProperty(prop)) { var value = source[prop]; if (!(prop in target) || overrideExistingValues) { target[prop] = value } } } return target }; var extend = function(target) { target = target || {}; var i = 1, deep = false; if ("boolean" === typeof target) { deep = target; target = arguments[1] || {}; i++ } for (; i < arguments.length; i++) { var source = arguments[i]; if (null == source) { continue } for (var key in source) { var clone, targetValue = target[key], sourceValue = source[key], sourceValueIsArray = false; if (target === sourceValue) { continue } if (deep && sourceValue && (isPlainObject(sourceValue) || (sourceValueIsArray = Array.isArray(sourceValue)))) { if (sourceValueIsArray) { clone = targetValue && Array.isArray(targetValue) ? targetValue : [] } else { clone = targetValue && isPlainObject(targetValue) ? targetValue : {} } target[key] = extend(deep, clone, sourceValue) } else { if (void 0 !== sourceValue) { target[key] = sourceValue } } } } return target }; exports.extend = extend; exports.extendFromObject = extendFromObject }, /*!*******************************!*\ !*** ./js/core/utils/type.js ***! \*******************************/ function(module, exports) { var isEmptyObject = function(object) { var property; for (property in object) { return false } return true }; var isPlainObject = function(object) { if (!object || "[object Object]" !== Object.prototype.toString.call(object)) { return false } var proto = Object.getPrototypeOf(object), ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; return "function" === typeof ctor && Object.toString.call(ctor) === Object.toString.call(Object) }; exports.isEmptyObject = isEmptyObject; exports.isPlainObject = isPlainObject }, /*!**********************************!*\ !*** ./js/core/utils/console.js ***! \**********************************/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__( /*! ./common */ 14).isFunction; var logger = function() { var console = window.console; function info(text) { if (!console || !isFunction(console.info)) { return } console.info(text) } function warn(text) { if (!console || !isFunction(console.warn)) { return } console.warn(text) } function error(text) { if (!console || !isFunction(console.error)) { return } console.error(text) } return { info: info, warn: warn, error: error } }(); var debug = function() { function assert(condition, message) { if (!condition) { throw new Error(message) } } function assertParam(parameter, message) { assert(null !== parameter && void 0 !== parameter, message) } return { assert: assert, assertParam: assertParam } }(); exports.logger = logger; exports.debug = debug }, /*!*********************************!*\ !*** ./js/core/utils/common.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), config = __webpack_require__( /*! ../config */ 15), deferredUtils = __webpack_require__( /*! ../../integration/jquery/deferred */ 16); var type = function(object) { var types = { "[object Array]": "array", "[object Date]": "date", "[object Object]": "object", "[object Null]": "null" }, typeOfObject = Object.prototype.toString.call(object); return "object" === typeof object ? types[typeOfObject] || "object" : typeof object }; var isDefined = function(object) { return null !== object && void 0 !== object }; var isString = function(object) { return "string" === typeof object }; var isNumeric = function(object) { return "number" === typeof object && isFinite(object) || !isNaN(object - parseFloat(object)) }; var isObject = function(object) { return "object" === type(object) }; var isDate = function(object) { return "date" === type(object) }; var isBoolean = function(object) { return "boolean" === typeof object }; var isFunction = function(object) { return "function" === typeof object }; var isPrimitive = function(value) { return ["object", "array", "function"].indexOf(type(value)) === -1 }; var isExponential = function(value) { return isNumeric(value) && value.toString().indexOf("e") !== -1 }; var isWindow = function(object) { return null != object && object === object.window }; var ensureDefined = function(value, defaultValue) { return isDefined(value) ? value : defaultValue }; var executeAsync = function(action, context) { var timerId, deferred = $.Deferred(), normalizedContext = context || this, task = { promise: deferred.promise(), abort: function() { clearTimeout(timerId); deferred.rejectWith(normalizedContext) } }, callback = function() { var result = action.call(normalizedContext); if (result && result.done && isFunction(result.done)) { result.done(function() { deferred.resolveWith(normalizedContext) }) } else { deferred.resolveWith(normalizedContext) } }; timerId = (arguments[2] || setTimeout)(callback, "number" === typeof context ? context : 0); return task }; var delayedFuncs = []; var delayedNames = []; var delayedDeferreds = []; var executingName; var deferExecute = function(name, func, deferred) { if (executingName && executingName !== name) { delayedFuncs.push(func); delayedNames.push(name); deferred = deferred || $.Deferred(); delayedDeferreds.push(deferred); return deferred } else { var oldExecutingName = executingName, currentDelayedCount = delayedDeferreds.length; executingName = name; var result = func(); if (!result) { if (delayedDeferreds.length > currentDelayedCount) { result = deferredUtils.when.apply($, delayedDeferreds.slice(currentDelayedCount)) } else { if (deferred) { deferred.resolve() } } } executingName = oldExecutingName; if (deferred && result && result.done) { result.done(deferred.resolve).fail(deferred.reject) } if (!executingName && delayedFuncs.length) { ("render" === delayedNames.shift() ? deferRender : deferUpdate)(delayedFuncs.shift(), delayedDeferreds.shift()) } return result } }; var deferRender = function(func, deferred) { return deferExecute("render", func, deferred) }; var deferUpdate = function(func, deferred) { return deferExecute("update", func, deferred) }; var deferRenderer = function(func) { return function() { var that = this; return deferExecute("render", function() { return func.call(that) }) } }; var deferUpdater = function(func) { return function() { var that = this; return deferExecute("update", function() { return func.call(that) }) } }; var findBestMatches = function(targetFilter, items, mapFn) { var bestMatches = [], maxMatchCount = 0; $.each(items, function(index, itemSrc) { var matchCount = 0, item = mapFn ? mapFn(itemSrc) : itemSrc; $.each(targetFilter, function(paramName, targetValue) { var value = item[paramName]; if (void 0 === value) { return } if (match(value, targetValue)) { matchCount++; return } matchCount = -1; return false }); if (matchCount < maxMatchCount) { return } if (matchCount > maxMatchCount) { bestMatches.length = 0; maxMatchCount = matchCount } bestMatches.push(itemSrc) }); return bestMatches }; var match = function(value, targetValue) { if (Array.isArray(value) && Array.isArray(targetValue)) { var mismatch = false; $.each(value, function(index, valueItem) { if (valueItem !== targetValue[index]) { mismatch = true; return false } }); if (mismatch) { return false } return true } if (value === targetValue) { return true } return false }; var splitPair = function(raw) { switch (typeof raw) { case "string": return raw.split(/\s+/, 2); case "object": return [raw.x || raw.h, raw.y || raw.v]; case "number": return [raw]; default: return raw } }; var splitQuad = function(raw) { switch (typeof raw) { case "string": return raw.split(/\s+/, 4); case "object": return [raw.x || raw.h || raw.left, raw.y || raw.v || raw.top, raw.x || raw.h || raw.right, raw.y || raw.v || raw.bottom]; case "number": return [raw]; default: return raw } }; var normalizeKey = function(id) { var key = isString(id) ? id : id.toString(), arr = key.match(/[^a-zA-Z0-9_]/g); arr && $.each(arr, function(_, sign) { key = key.replace(sign, "__" + sign.charCodeAt() + "__") }); return key }; var denormalizeKey = function(key) { var arr = key.match(/__\d+__/g); arr && arr.forEach(function(char) { var charCode = parseInt(char.replace("__", "")); key = key.replace(char, String.fromCharCode(charCode)) }); return key }; var isArraysEqualByValue = function(array1, array2, deep) { if (array1.length !== array2.length) { return false } for (var i = 0; i < array1.length; i++) { if (!equalByValue(array1[i], array2[i], deep + 1)) { return false } } return true }; var isObjectsEqualByValue = function(object1, object2, deep) { for (var propertyName in object1) { if (object1.hasOwnProperty(propertyName) && !equalByValue(object1[propertyName], object2[propertyName], deep + 1)) { return false } } for (propertyName in object2) { if (!(propertyName in object1)) { return false } } return true }; var equalByValue = function(object1, object2, deep) { if (object1 === object2) { return true } var maxDeep = 3; deep = deep || 0; if (deep >= maxDeep) { return true } if (isObject(object1) && isObject(object2)) { return isObjectsEqualByValue(object1, object2, deep) } else { if (Array.isArray(object1) && Array.isArray(object2)) { return isArraysEqualByValue(object1, object2, deep) } else { if (isDate(object1) && isDate(object2)) { return object1.getTime() === object2.getTime() } } } return false }; var getKeyHash = function(key) { if (isObject(key) || Array.isArray(key)) { try { var keyHash = JSON.stringify(key); return "{}" === keyHash ? key : keyHash } catch (e) { return key } } return key }; var escapeRegExp = function(string) { return string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") }; var applyServerDecimalSeparator = function(value) { var separator = config().serverDecimalSeparator; if (isDefined(value)) { value = value.toString().replace(".", separator) } return value }; var noop = function() {}; var grep = function(elements, checkFunction, invert) { var check, result = [], expectedCheck = !invert; for (var i = 0; i < elements.length; i++) { check = !!checkFunction(elements[i], i); if (check === expectedCheck) { result.push(elements[i]) } } return result }; exports.type = type; exports.isDefined = isDefined; exports.isString = isString; exports.isNumeric = isNumeric; exports.isObject = isObject; exports.isDate = isDate; exports.isBoolean = isBoolean; exports.isFunction = isFunction; exports.isPrimitive = isPrimitive; exports.isExponential = isExponential; exports.isWindow = isWindow; exports.ensureDefined = ensureDefined; exports.executeAsync = executeAsync; exports.deferRender = deferRender; exports.deferRenderer = deferRenderer; exports.deferUpdate = deferUpdate; exports.deferUpdater = deferUpdater; exports.splitPair = splitPair; exports.splitQuad = splitQuad; exports.findBestMatches = findBestMatches; exports.normalizeKey = normalizeKey; exports.denormalizeKey = denormalizeKey; exports.equalByValue = equalByValue; exports.getKeyHash = getKeyHash; exports.escapeRegExp = escapeRegExp; exports.applyServerDecimalSeparator = applyServerDecimalSeparator; exports.noop = noop; exports.grep = grep }, /*!***************************!*\ !*** ./js/core/config.js ***! \***************************/ function(module, exports, __webpack_require__) { var extendUtils = __webpack_require__( /*! ./utils/extend */ 11), config = { rtlEnabled: false, defaultCurrency: "USD", designMode: false, serverDecimalSeparator: ".", forceIsoDateParsing: true, wrapActionsBeforeExecute: false }; module.exports = function() { if (!arguments.length) { return config } extendUtils.extend(config, arguments[0]) } }, /*!*******************************************!*\ !*** ./js/integration/jquery/deferred.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), compareVersion = __webpack_require__( /*! ../../core/utils/version */ 17).compare; exports.fromPromise = function(promise, context) { var isDeferred = promise && commonUtils.isFunction(promise.done) && commonUtils.isFunction(promise.fail); if (isDeferred) { return promise } var d = $.Deferred(); promise.then(function() { d.resolveWith.apply(d, [context].concat([$.makeArray(arguments)])) }, function() { d.rejectWith.apply(d, [context].concat([$.makeArray(arguments)])) }); return d }; exports.when = compareVersion($.fn.jquery, [3]) < 0 ? $.when : function(singleArg) { if (0 === arguments.length) { return $.Deferred().resolve() } else { if (1 === arguments.length) { return singleArg && singleArg.then ? singleArg : $.Deferred().resolve(singleArg) } else { return $.when.apply($, arguments) } } } }, /*!**********************************!*\ !*** ./js/core/utils/version.js ***! \**********************************/ function(module, exports) { exports.compare = function(x, y, maxLevel) { function normalizeArg(value) { if ("string" === typeof value) { return value.split(".") } if ("number" === typeof value) { return [value] } return value } x = normalizeArg(x); y = normalizeArg(y); var length = Math.max(x.length, y.length); if (isFinite(maxLevel)) { length = Math.min(length, maxLevel) } for (var i = 0; i < length; i++) { var xItem = parseInt(x[i] || 0, 10), yItem = parseInt(y[i] || 0, 10); if (xItem < yItem) { return -1 } if (xItem > yItem) { return 1 } } return 0 } }, /*!*********************************!*\ !*** ./js/core/utils/string.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ./common */ 14); var encodeHtml = function() { var encodeRegExp = [new RegExp("&", "g"), new RegExp('"', "g"), new RegExp("'", "g"), new RegExp("<", "g"), new RegExp(">", "g")]; return function(str) { return String(str).replace(encodeRegExp[0], "&").replace(encodeRegExp[1], """).replace(encodeRegExp[2], "'").replace(encodeRegExp[3], "<").replace(encodeRegExp[4], ">") } }(); var pairToObject = function(raw) { var pair = commonUtils.splitPair(raw), h = parseInt(pair && pair[0], 10), v = parseInt(pair && pair[1], 10); if (!isFinite(h)) { h = 0 } if (!isFinite(v)) { v = h } return { h: h, v: v } }; var quadToObject = function(raw) { var quad = commonUtils.splitQuad(raw), left = parseInt(quad && quad[0], 10), top = parseInt(quad && quad[1], 10), right = parseInt(quad && quad[2], 10), bottom = parseInt(quad && quad[3], 10); if (!isFinite(left)) { left = 0 } if (!isFinite(top)) { top = left } if (!isFinite(right)) { right = left } if (!isFinite(bottom)) { bottom = top } return { top: top, right: right, bottom: bottom, left: left } }; var stringFormat = function() { var replaceDollarCount, reg, value, s = arguments[0], values = $.makeArray(arguments).slice(1); if (commonUtils.isFunction(s)) { return s.apply(this, values) } for (var i = 0; i < values.length; i++) { reg = new RegExp("\\{" + i + "\\}", "gm"); value = values[i]; if ("string" === commonUtils.type(value) && value.indexOf("$") >= 0) { replaceDollarCount = "$".replace("$", "$$").length; value = value.replace("$", 1 === replaceDollarCount ? "$$$$" : "$$") } s = s.replace(reg, value) } return s }; var replaceAll = function() { var quote = function(str) { return (str + "").replace(/([\+\*\?\\\.\[\^\]\$\(\)\{\}\><\|\=\!\:])/g, "\\$1") }; return function(text, searchToken, replacementToken) { return text.replace(new RegExp("(" + quote(searchToken) + ")", "gi"), replacementToken) } }(); var isEmpty = function() { var SPACE_REGEXP = /\s/g; return function(text) { return !text || !text.replace(SPACE_REGEXP, "") } }(); exports.encodeHtml = encodeHtml; exports.pairToObject = pairToObject; exports.quadToObject = quadToObject; exports.format = stringFormat; exports.replaceAll = replaceAll; exports.isEmpty = isEmpty }, /*!****************************!*\ !*** ./js/core/version.js ***! \****************************/ function(module, exports) { module.exports = "17.1.5" }, /*!*******************************!*\ !*** ./js/client_exporter.js ***! \*******************************/ function(module, exports, __webpack_require__) { var fileSaver = __webpack_require__( /*! ./client_exporter/file_saver */ 21).fileSaver, _isFunction = __webpack_require__( /*! ./core/utils/common */ 14).isFunction; exports.export = function(data, options, getData) { if (!data) { return } var exportingAction = options.exportingAction, exportedAction = options.exportedAction, fileSavingAction = options.fileSavingAction, eventArgs = { fileName: options.fileName, format: options.format, cancel: false }; _isFunction(exportingAction) && exportingAction(eventArgs); if (!eventArgs.cancel) { getData(data, options, function(blob) { _isFunction(exportedAction) && exportedAction(); if (_isFunction(fileSavingAction)) { eventArgs.data = blob; fileSavingAction(eventArgs) } if (!eventArgs.cancel) { fileSaver.saveAs(eventArgs.fileName, options.format, blob, options.proxyUrl) } }) } }; exports.fileSaver = fileSaver; exports.excel = { creator: __webpack_require__( /*! ./client_exporter/excel_creator */ 24).ExcelCreator, getData: __webpack_require__( /*! ./client_exporter/excel_creator */ 24).getData, formatConverter: __webpack_require__( /*! ./client_exporter/excel_format_converter */ 31) }; exports.excel.__internals = __webpack_require__( /*! ./client_exporter/excel_creator */ 24).__internals; exports.image = { creator: __webpack_require__( /*! ./client_exporter/image_creator */ 37).imageCreator, getData: __webpack_require__( /*! ./client_exporter/image_creator */ 37).getData }; exports.pdf = { getData: __webpack_require__( /*! ./client_exporter/pdf_creator */ 40).getData }; exports.svg = { creator: __webpack_require__( /*! ./client_exporter/svg_creator */ 41).svgCreator, getData: __webpack_require__( /*! ./client_exporter/svg_creator */ 41).getData } }, /*!******************************************!*\ !*** ./js/client_exporter/file_saver.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ../ui/widget/ui.errors */ 22), browser = __webpack_require__( /*! ../core/utils/browser */ 23), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), FILE_EXTESIONS = { EXCEL: "xlsx", CSS: "css", PNG: "png", JPEG: "jpeg", GIF: "gif", SVG: "svg", PDF: "pdf" }; var MIME_TYPES = exports.MIME_TYPES = { CSS: "text/css", EXCEL: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", PNG: "image/png", JPEG: "image/jpeg", GIF: "image/gif", SVG: "image/svg+xml", PDF: "application/pdf" }; exports.fileSaver = { _getDataUri: function(format, data) { return "data:" + MIME_TYPES[format] + ";base64," + data }, _linkDownloader: function(fileName, href, callback) { var exportLinkElement = document.createElement("a"), attributes = { download: fileName, href: href }; if (commonUtils.isDefined(callback)) { attributes.onclick = callback } document.body.appendChild(exportLinkElement); $(exportLinkElement).css({ display: "none" }).text("load").attr(attributes)[0].click(); return exportLinkElement }, _formDownloader: function(proxyUrl, fileName, contentType, data, callback) { var formAttributes = { method: "post", action: proxyUrl, enctype: "multipart/form-data" }, exportForm = $("<form>").css({ display: "none" }).attr(formAttributes); if (commonUtils.isDefined(callback)) { exportForm.submit(callback) } exportForm.append('<input type="hidden" name="fileName" value="' + fileName + '" />'); exportForm.append('<input type="hidden" name="contentType" value="' + contentType + '" />'); exportForm.append('<input type="hidden" name="data" value="' + data + '" />'); exportForm.appendTo("body"); exportForm.submit(); if (exportForm.submit()) { exportForm.remove() } return exportForm }, _saveByProxy: function(proxyUrl, fileName, format, data, callback) { return this._formDownloader(proxyUrl, fileName, MIME_TYPES[format], data, callback) }, _winJSBlobSave: function(blob, fileName, format) { var savePicker = new Windows.Storage.Pickers.FileSavePicker; savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary; savePicker.fileTypeChoices.insert(MIME_TYPES[format], ["." + FILE_EXTESIONS[format]]); savePicker.suggestedFileName = fileName; savePicker.pickSaveFileAsync().then(function(file) { if (file) { file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function(outputStream) { var inputStream = blob.msDetachStream(); Windows.Storage.Streams.RandomAccessStream.copyAsync(inputStream, outputStream).then(function() { outputStream.flushAsync().done(function() { inputStream.close(); outputStream.close() }) }) }) } }) }, _saveBlobAs: function(fileName, format, data, linkClick) { this._blobSaved = false; if (commonUtils.isDefined(navigator.msSaveOrOpenBlob)) { navigator.msSaveOrOpenBlob(data, fileName); this._blobSaved = true } else { if (commonUtils.isDefined(window.WinJS)) { this._winJSBlobSave(data, fileName, format); this._blobSaved = true } else { var URL = window.URL || window.webkitURL || window.mozURL || window.msURL || window.oURL; linkClick = commonUtils.isDefined(linkClick) ? linkClick : function() { var link = $("#dxExportLink"); URL.revokeObjectURL(link.attr("href")); link.remove() }; if (commonUtils.isDefined(URL)) { return this._linkDownloader(fileName, URL.createObjectURL(data), linkClick) } } } }, saveAs: function(fileName, format, data, proxyURL, linkClick) { fileName += "." + FILE_EXTESIONS[format]; if (commonUtils.isFunction(window.Blob)) { this._saveBlobAs(fileName, format, data) } else { if (commonUtils.isDefined(proxyURL) && !commonUtils.isDefined(navigator.userAgent.match(/iPad/i))) { this._saveByProxy(proxyURL, fileName, format, data) } else { if (!commonUtils.isDefined(navigator.userAgent.match(/iPad/i))) { errors.log("E1034") } if (browser.msie && parseInt(browser.version) < 10) { return } this._linkDownloader(fileName, this._getDataUri(format, data), linkClick) } } } } }, /*!***********************************!*\ !*** ./js/ui/widget/ui.errors.js ***! \***********************************/ function(module, exports, __webpack_require__) { var errorUtils = __webpack_require__( /*! ../../core/utils/error */ 8), errors = __webpack_require__( /*! ../../core/errors */ 7); module.exports = errorUtils(errors.ERROR_MESSAGES, { E1001: "Module '{0}'. Controller '{1}' is already registered", E1002: "Module '{0}'. Controller '{1}' does not inherit from DevExpress.ui.dxDataGrid.Controller", E1003: "Module '{0}'. View '{1}' is already registered", E1004: "Module '{0}'. View '{1}' does not inherit from DevExpress.ui.dxDataGrid.View", E1005: "Public method '{0}' is already registered", E1006: "Public method '{0}.{1}' does not exist", E1007: "State storing cannot be provided due to the restrictions of the browser", E1010: "The template does not contain the TextBox widget", E1011: 'Items cannot be deleted from the List. Implement the "remove" function in the data store', E1012: "Editing type '{0}' with the name '{1}' is unsupported", E1016: "Unexpected type of data source is provided for a lookup column", E1018: "The 'collapseAll' method cannot be called if you use a remote data source", E1019: "Search mode '{0}' is unavailable", E1020: "The type cannot be changed after initialization", E1021: "{0} '{1}' you are trying to remove does not exist", E1022: 'The "markers" option is given an invalid value. Assign an array instead', E1023: 'The "routes" option is given an invalid value. Assign an array instead', E1025: "This layout is too complex to render", E1026: 'The "calculateCustomSummary" function is missing from a field whose "summaryType" option is set to "custom"', E1030: "Unknown ScrollView refresh strategy: '{0}'", E1031: "Unknown subscription in the Scheduler widget: '{0}'", E1032: "Unknown start date in an appointment: '{0}'", E1033: "Unknown step in the date navigator: '{0}'", E1034: "The browser does not implement an API for saving files", E1035: "The editor cannot be created because of an internal error: {0}", E1036: "Validation rules are not defined for any form item", E1037: "Invalid structure of grouped data", E1038: "The browser does not support local storages for local web pages", E1039: "A cell's position cannot be calculated", E1040: "The '{0}' key value is not unique within the data array", E1041: "The JSZip script is referenced after DevExtreme scripts", E1042: 'Deferred selection cannot be performed. Set the "key" field for the data store', E1043: "Changes cannot be processed due to the incorrectly set key", E1044: "The key field specified by the keyExpr option does not match the key field specified in the data store", E1045: "Editing requires the key field to be specified in the data store", E1046: "The '{0}' key field is not found in data objects", W1001: 'The "key" option cannot be modified after initialization', W1002: "An item with the key '{0}' does not exist", W1003: "A group with the key '{0}' in which you are trying to select items does not exist", W1004: "The item '{0}' you are trying to select in the group '{1}' does not exist", W1005: "Due to column data types being unspecified, data has been loaded twice in order to apply initial filter settings. To resolve this issue, specify data types for all grid columns.", W1006: "The map service returned the '{0}' error", W1007: "No item with key {0} was found in the data source, but this key was used as the parent key for item {1}", W1008: "Cannot scroll to the '{0}' date because it does not exist on the current view" }) }, /*!**********************************!*\ !*** ./js/core/utils/browser.js ***! \**********************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ./extend */ 11).extend; var webkitRegExp = /(webkit)[ \/]([\w.]+)/, ieRegExp = /(msie) (\d{1,2}\.\d)/, ie11RegExp = /(trident).*rv:(\d{1,2}\.\d)/, msEdge = /(edge)\/((\d+)?[\w\.]+)/, safari = /(safari)/i, mozillaRegExp = /(mozilla)(?:.*? rv:([\w.]+))/; var browserFromUA = function(ua) { ua = ua.toLowerCase(); var result = {}, matches = ieRegExp.exec(ua) || ie11RegExp.exec(ua) || msEdge.exec(ua) || ua.indexOf("compatible") < 0 && mozillaRegExp.exec(ua) || webkitRegExp.exec(ua) || [], browserName = matches[1], browserVersion = matches[2]; if ("webkit" === browserName && ua.indexOf("chrome") < 0 && safari.exec(ua)) { browserName = "safari"; result.webkit = true; browserVersion = /Version\/([0-9.]+)/i.exec(ua); browserVersion = browserVersion && browserVersion[1] } if ("trident" === browserName || "edge" === browserName) { browserName = "msie" } if (browserName) { result[browserName] = true; result.version = browserVersion } return result }; module.exports = extend({ _fromUA: browserFromUA }, browserFromUA(navigator.userAgent)) }, /*!*********************************************!*\ !*** ./js/client_exporter/excel_creator.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var Class = __webpack_require__( /*! ../core/class */ 25), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, errors = __webpack_require__( /*! ../ui/widget/ui.errors */ 22), stringUtils = __webpack_require__( /*! ../core/utils/string */ 18), JSZip = __webpack_require__( /*! jszip */ 30), fileSaver = __webpack_require__( /*! ./file_saver */ 21), excelFormatConverter = __webpack_require__( /*! ./excel_format_converter */ 31), XML_TAG = '<?xml version="1.0" encoding="utf-8"?>', GROUP_SHEET_PR_XML = '<sheetPr><outlinePr summaryBelow="0"/></sheetPr>', SINGLE_SHEET_PR_XML = "<sheetPr/>", BASE_STYLE_XML = '<fonts count="2"><font><sz val="11"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font><font><b/><sz val="11"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border><left style="thin"><color rgb="FFD3D3D3"/></left><right style="thin"><color rgb="FFD3D3D3"/></right><top style="thin"><color rgb="FFD3D3D3"/></top><bottom style="thin"><color rgb="FFD3D3D3"/></bottom></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>', OPEN_XML_FORMAT_URL = "http://schemas.openxmlformats.org", RELATIONSHIP_PART_NAME = "rels", XL_FOLDER_NAME = "xl", WORKBOOK_FILE_NAME = "workbook.xml", CONTENTTYPES_FILE_NAME = "[Content_Types].xml", SHAREDSTRING_FILE_NAME = "sharedStrings.xml", STYLE_FILE_NAME = "styles.xml", WORKSHEETS_FOLDER = "worksheets", WORKSHEET_FILE_NAME = "sheet1.xml", VALID_TYPES = { "boolean": "b", date: "d", number: "n", string: "s" }, EXCEL_START_TIME = Date.UTC(1899, 11, 30), DAYS_COUNT_BEFORE_29_FEB_1900 = 60, BOLD_STYLES_COUNT = 4, MAX_DIGIT_WIDTH_IN_PIXELS = 7, CUSTOM_FORMAT_START_INDEX = 165; exports.ExcelCreator = Class.inherit({ _getXMLTag: function(tagName, attributes, content) { var i, attr, result = "<" + tagName, length = attributes.length; for (i = 0; i < length; i++) { attr = attributes[i]; result = result + " " + attr.name + '="' + attr.value + '"' } return commonUtils.isDefined(content) ? result + ">" + content + "</" + tagName + ">" : result + " />" }, _getCellIndex: function(rowIndex, cellIndex) { var charCode, sheetIndex = "", max = 26; if (this._maxIndex[0] < Number(rowIndex)) { this._maxIndex[0] = Number(rowIndex) } if (this._maxIndex[1] < Number(cellIndex)) { this._maxIndex[1] = Number(cellIndex) } while (true) { charCode = 65 + (cellIndex >= max ? cellIndex % max : Math.ceil(cellIndex)); sheetIndex = String.fromCharCode(charCode) + sheetIndex; if (cellIndex >= max) { cellIndex = Math.floor(cellIndex / max) - 1 } else { break } } return sheetIndex + rowIndex }, _getDataType: function(dataType) { return VALID_TYPES[dataType] || "s" }, _formatObjectConverter: function(format, precision, dataType) { var result = { format: format, precision: precision, dataType: dataType }; if (commonUtils.isObject(format)) { return extend(result, format, { format: format.type, currency: format.currency }) } return result }, _appendFormat: function(format, precision, dataType) { var currency, newFormat = this._formatObjectConverter(format, precision, dataType); format = newFormat.format; precision = newFormat.precision; currency = newFormat.currency; dataType = newFormat.dataType; format = excelFormatConverter.convertFormat(format, precision, dataType, currency); if (format) { if (inArray(format, this._styleFormat) === -1) { this._styleFormat.push(format) } return inArray(format, this._styleFormat) + 1 } }, _appendString: function(value) { if (commonUtils.isDefined(value)) { value = String(value); if (value.length) { value = stringUtils.encodeHtml(value); if (void 0 === this._stringHash[value]) { this._stringHash[value] = this._stringArray.length; this._stringArray.push(value) } return this._stringHash[value] } } }, _getExcelDateValue: function(date) { var days, totalTime; if (commonUtils.isDate(date)) { days = Math.floor((Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - EXCEL_START_TIME) / 864e5); if (days < DAYS_COUNT_BEFORE_29_FEB_1900) { days-- } totalTime = (3600 * date.getHours() + 60 * date.getMinutes() + date.getSeconds()) / 86400; return days + totalTime } }, _prepareValue: function(rowIndex, cellIndex) { var dataProvider = this._dataProvider, value = dataProvider.getCellValue(rowIndex, cellIndex), type = this._getDataType(dataProvider.getCellType(rowIndex, cellIndex)), formatID = this._styleArray[this._dataProvider.getStyleId(rowIndex, cellIndex)].formatID, format = commonUtils.isNumeric(formatID) ? this._styleFormat[formatID - 1] : null; if ("d" === type && !commonUtils.isDate(value)) { type = "s" } switch (type) { case "s": value = this._appendString(value); break; case "d": value = this._getExcelDateValue(value, format); type = "n" } return { value: value, type: type } }, _getDataArray: function() { var rowIndex, cellIndex, cellsArray, cellData, cellsLength, that = this, result = [], dataProvider = that._dataProvider, rowsLength = dataProvider.getRowsCount(), columns = dataProvider.getColumns(); for (rowIndex = 0; rowIndex < rowsLength; rowIndex++) { cellsArray = []; cellsLength = columns.length; for (cellIndex = 0; cellIndex !== cellsLength; cellIndex++) { cellData = that._prepareValue(rowIndex, cellIndex); cellsArray.push({ style: dataProvider.getStyleId(rowIndex, cellIndex), value: cellData.value, type: cellData.type }) } if (!that._needSheetPr && dataProvider.getGroupLevel(rowIndex) > 0) { that._needSheetPr = true } result.push(cellsArray) } return result }, _getBoldStyleID: function(alignment) { for (var i = 0; i < BOLD_STYLES_COUNT - 1; i++) { if (this._styleArray[i].alignment === alignment) { return i } } }, _calculateWidth: function(pixelsWidth) { pixelsWidth = parseInt(pixelsWidth, 10); if (!pixelsWidth || pixelsWidth < 5) { pixelsWidth = 100 } return Math.min(255, Math.floor((pixelsWidth - 5) / MAX_DIGIT_WIDTH_IN_PIXELS * 100 + .5) / 100) }, _prepareStyleData: function() { var that = this, styles = that._dataProvider.getStyles(); that._dataProvider.getColumns().forEach(function(column) { that._colsArray.push(that._calculateWidth(column.width)) }); styles.forEach(function(style) { that._styleArray.push({ bold: !!style.bold, alignment: style.alignment || "left", formatID: that._appendFormat(style.format, style.precision, style.dataType), wrapText: style.wrapText }) }) }, _prepareCellData: function() { this._cellsArray = this._getDataArray() }, _createXMLRelationships: function(xmlRelationships) { return this._getXMLTag("Relationships", [{ name: "xmlns", value: OPEN_XML_FORMAT_URL + "/package/2006/relationships" }], xmlRelationships) }, _createXMLRelationship: function(id, type, target) { return this._getXMLTag("Relationship", [{ name: "Id", value: "rId" + id }, { name: "Type", value: OPEN_XML_FORMAT_URL + "/officeDocument/2006/relationships/" + type }, { name: "Target", value: target }]) }, _getWorkbookContent: function() { var content = '<bookViews><workbookView xWindow="0" yWindow="0" windowWidth="0" windowHeight="0"/></bookViews><sheets><sheet name="Sheet" sheetId="1" r:id="rId1" /></sheets><definedNames><definedName name="_xlnm.Print_Titles" localSheetId="0">Sheet!$1:$1</definedName><definedName name="_xlnm._FilterDatabase" hidden="0" localSheetId="0">Sheet!$A$1:$F$6332</definedName></definedNames>'; return XML_TAG + this._getXMLTag("workbook", [{ name: "xmlns:r", value: OPEN_XML_FORMAT_URL + "/officeDocument/2006/relationships" }, { name: "xmlns", value: OPEN_XML_FORMAT_URL + "/spreadsheetml/2006/main" }], content) }, _getContentTypesContent: function() { return XML_TAG + '<Types xmlns="' + OPEN_XML_FORMAT_URL + '/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Default Extension="xml" ContentType="application/xml" /><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" /><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" /><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" /><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" /></Types>' }, _generateStylesXML: function() { var formatIndex, that = this, folder = that._zip.folder(XL_FOLDER_NAME), xmlStyles = [], XML = ""; for (formatIndex = 0; formatIndex < that._styleFormat.length; formatIndex++) { that._styleFormat[formatIndex] = that._getXMLTag("numFmt", [{ name: "numFmtId", value: Number(formatIndex) + CUSTOM_FORMAT_START_INDEX }, { name: "formatCode", value: that._styleFormat[formatIndex] }]) } XML = XML + that._getXMLTag("numFmts", [{ name: "count", value: that._styleFormat.length }], that._styleFormat.join("")) + BASE_STYLE_XML; this._styleArray.forEach(function(style) { xmlStyles.push(that._getXMLTag("xf", [{ name: "xfId", value: 0 }, { name: "applyAlignment", value: 1 }, { name: "fontId", value: Number(!!style.bold) }, { name: "applyNumberFormat", value: commonUtils.isDefined(style.formatID) ? 1 : 0 }, { name: "numFmtId", value: commonUtils.isDefined(style.formatID) ? Number(style.formatID) + CUSTOM_FORMAT_START_INDEX - 1 : 0 }], that._getXMLTag("alignment", [{ name: "vertical", value: "top" }, { name: "wrapText", value: Number(!!style.wrapText) }, { name: "horizontal", value: style.alignment }]))) }); XML += that._getXMLTag("cellXfs", [{ name: "count", value: xmlStyles.length }], xmlStyles.join("")); XML += that._getXMLTag("cellStyles", [{ name: "count", value: 1 }], that._getXMLTag("cellStyle", [{ name: "name", value: "Normal" }, { name: "xfId", value: 0 }, { name: "builtinId", value: 0 }])); XML = XML_TAG + that._getXMLTag("styleSheet", [{ name: "xmlns", value: OPEN_XML_FORMAT_URL + "/spreadsheetml/2006/main" }], XML); folder.file(STYLE_FILE_NAME, XML); that._styleArray = [] }, _generateStringsXML: function() { var stringIndex, folder = this._zip.folder(XL_FOLDER_NAME), stringsLength = this._stringArray.length, sharedStringXml = XML_TAG; for (stringIndex = 0; stringIndex < stringsLength; stringIndex++) { this._stringArray[stringIndex] = this._getXMLTag("si", [], this._getXMLTag("t", [], this._stringArray[stringIndex])) } sharedStringXml += this._getXMLTag("sst", [{ name: "xmlns", value: OPEN_XML_FORMAT_URL + "/spreadsheetml/2006/main" }, { name: "count", value: this._stringArray.length }, { name: "uniqueCount", value: this._stringArray.length }], this._stringArray.join("")); folder.file(SHAREDSTRING_FILE_NAME, sharedStringXml); this._stringArray = [] }, _getPaneXML: function() { var attributes = [{ name: "activePane", value: "bottomLeft" }, { name: "state", value: "frozen" }], frozenArea = this._dataProvider.getFrozenArea(); if (!(frozenArea.x || frozenArea.y)) { return "" } if (frozenArea.x) { attributes.push({ name: "xSplit", value: frozenArea.x }) } if (frozenArea.y) { attributes.push({ name: "ySplit", value: frozenArea.y }) } attributes.push({ name: "topLeftCell", value: this._getCellIndex(frozenArea.y + 1, frozenArea.x) }); return this._getXMLTag("pane", attributes) }, _generateWorksheetXML: function() { var colIndex, rowIndex, cellData, xmlCells, maxCellIndex, cellsLength, counter = 0, xmlRows = [], rowsLength = this._cellsArray.length, colsLength = this._colsArray.length, rSpans = "1:" + colsLength, headerRowCount = this._dataProvider.getHeaderRowCount ? this._dataProvider.getHeaderRowCount() : 1, xmlResult = [ ['<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">', this._needSheetPr ? GROUP_SHEET_PR_XML : SINGLE_SHEET_PR_XML, '<dimension ref="A1:', this._getCellIndex(this._maxIndex[0], this._maxIndex[1]) + '"/><sheetViews><sheetView ' + (this._rtlEnabled ? 'rightToLeft="1" ' : "") + 'tabSelected="1" workbookViewId="0">' + this._getPaneXML() + '</sheetView></sheetViews><sheetFormatPr defaultRowHeight="15" outlineLevelRow="', this._dataProvider.getRowsCount() > 0 ? this._dataProvider.getGroupLevel(0) : 0, '" x14ac:dyDescent="0.25"/>'].join("") ]; for (colIndex = 0; colIndex < colsLength; colIndex++) { this._colsArray[colIndex] = this._getXMLTag("col", [{ name: "width", value: this._colsArray[colIndex] }, { name: "min", value: Number(colIndex) + 1 }, { name: "max", value: Number(colIndex) + 1 }]) } xmlResult.push(this._getXMLTag("cols", [], this._colsArray.join("")) + "<sheetData>"); for (rowIndex = 0; rowIndex < rowsLength; rowIndex++) { xmlCells = []; cellsLength = this._cellsArray[rowIndex].length; for (colIndex = 0; colIndex < cellsLength; colIndex++) { rowIndex = Number(rowIndex); cellData = this._cellsArray[rowIndex][colIndex]; xmlCells.push(this._getXMLTag("c", [{ name: "r", value: this._getCellIndex(rowIndex + 1, colIndex) }, { name: "s", value: cellData.style }, { name: "t", value: cellData.type }], commonUtils.isDefined(cellData.value) ? this._getXMLTag("v", [], cellData.value) : null)) } xmlRows.push(this._getXMLTag("row", [{ name: "r", value: Number(rowIndex) + 1 }, { name: "spans", value: rSpans }, { name: "outlineLevel", value: rowIndex >= headerRowCount ? this._dataProvider.getGroupLevel(rowIndex) : 0 }, { name: "x14ac:dyDescent", value: "0.25" }], xmlCells.join(""))); this._cellsArray[rowIndex] = null; if (counter++ > 1e4) { xmlResult.push(xmlRows.join("")); xmlRows = []; counter = 0 } } xmlResult.push(xmlRows.join("")); xmlRows = []; maxCellIndex = this._getCellIndex(this._maxIndex[0], this._maxIndex[1]); xmlResult.push("</sheetData>" + (this._options.autoFilterEnabled ? '<autoFilter ref="A' + this._dataProvider.getHeaderRowCount() + ":" + maxCellIndex + '" />' : "") + this._generateMergingXML() + '<ignoredErrors><ignoredError sqref="A1:' + maxCellIndex + '" numberStoredAsText="1" /></ignoredErrors></worksheet>'); this._zip.folder(XL_FOLDER_NAME).folder(WORKSHEETS_FOLDER).file(WORKSHEET_FILE_NAME, xmlResult.join("")); this._colsArray = []; this._cellsArray = []; xmlResult = [] }, _generateMergingXML: function() { var k, l, cellIndex, rowIndex, mergeArrayLength, mergeIndex, rowsLength = commonUtils.isDefined(this._dataProvider.getHeaderRowCount) ? this._dataProvider.getHeaderRowCount() : this._dataProvider.getRowsCount(), columnsLength = this._dataProvider.getColumns().length, usedArea = [], mergeArray = [], mergeXML = ""; for (rowIndex = 0; rowIndex < rowsLength; rowIndex++) { for (cellIndex = 0; cellIndex !== columnsLength; cellIndex++) { if (!commonUtils.isDefined(usedArea[rowIndex]) || !commonUtils.isDefined(usedArea[rowIndex][cellIndex])) { var cellMerge = this._dataProvider.getCellMerging(rowIndex, cellIndex); if (cellMerge.colspan || cellMerge.rowspan) { mergeArray.push({ start: this._getCellIndex(rowIndex + 1, cellIndex), end: this._getCellIndex(rowIndex + 1 + (cellMerge.rowspan || 0), cellIndex + (cellMerge.colspan || 0)) }); for (k = rowIndex; k <= rowIndex + cellMerge.rowspan || 0; k++) { for (l = cellIndex; l <= cellIndex + cellMerge.colspan || 0; l++) { if (!commonUtils.isDefined(usedArea[k])) { usedArea[k] = [] } usedArea[k][l] = true } } } } } } mergeArrayLength = mergeArray.length; for (mergeIndex = 0; mergeIndex < mergeArrayLength; mergeIndex++) { mergeXML += this._getXMLTag("mergeCell", [{ name: "ref", value: mergeArray[mergeIndex].start + ":" + mergeArray[mergeIndex].end }]) } return mergeXML.length ? this._getXMLTag("mergeCells", [{ name: "count", value: mergeArrayLength }], mergeXML) : "" }, _generateCommonXML: function() { var xmlRelationships, relsFileContent = XML_TAG + this._createXMLRelationships(this._createXMLRelationship(1, "officeDocument", "xl/" + WORKBOOK_FILE_NAME)), folder = this._zip.folder(XL_FOLDER_NAME), relsXML = XML_TAG; this._zip.folder("_" + RELATIONSHIP_PART_NAME).file("." + RELATIONSHIP_PART_NAME, relsFileContent); xmlRelationships = this._createXMLRelationship(1, "worksheet", "worksheets/" + WORKSHEET_FILE_NAME) + this._createXMLRelationship(2, "styles", STYLE_FILE_NAME) + this._createXMLRelationship(3, "sharedStrings", SHAREDSTRING_FILE_NAME); relsXML += this._createXMLRelationships(xmlRelationships); folder.folder("_" + RELATIONSHIP_PART_NAME).file(WORKBOOK_FILE_NAME + ".rels", relsXML); folder.file(WORKBOOK_FILE_NAME, this._getWorkbookContent()); this._zip.file(CONTENTTYPES_FILE_NAME, this._getContentTypesContent()) }, _generateContent: function() { this._prepareStyleData(); this._prepareCellData(); this._generateWorkXML(); this._generateCommonXML() }, _generateWorkXML: function() { this._generateStylesXML(); this._generateStringsXML(); this._generateWorksheetXML() }, ctor: function(dataProvider, options) { this._rtlEnabled = options && !!options.rtlEnabled; this._options = options; this._maxIndex = [1, 2]; this._stringArray = []; this._stringHash = {}; this._styleArray = []; this._colsArray = []; this._cellsArray = []; this._styleFormat = []; this._needSheetPr = false; this._dataProvider = dataProvider; if (commonUtils.isDefined(JSZip)) { this._zip = new JSZip } else { this._zip = null } }, _checkZipState: function() { if (!this._zip) { throw errors.Error("E1041") } }, ready: function() { return this._dataProvider.ready() }, getData: function(isBlob) { var options = { type: isBlob ? "blob" : "base64", compression: "DEFLATE", mimeType: fileSaver.MIME_TYPES.EXCEL }; this._checkZipState(); this._generateContent(); return this._zip.generateAsync ? this._zip.generateAsync(options) : this._zip.generate(options) } }); exports.getData = function(data, options, callback) { var excelCreator = new exports.ExcelCreator(data, options); excelCreator._checkZipState(); excelCreator.ready().done(function() { if (excelCreator._zip.generateAsync) { excelCreator.getData(commonUtils.isFunction(window.Blob)).then(callback) } else { callback(excelCreator.getData(commonUtils.isFunction(window.Blob))) } }) }; exports.__internals = { CONTENTTYPES_FILE_NAME: CONTENTTYPES_FILE_NAME, RELATIONSHIP_PART_NAME: RELATIONSHIP_PART_NAME, XL_FOLDER_NAME: XL_FOLDER_NAME, WORKBOOK_FILE_NAME: WORKBOOK_FILE_NAME, STYLE_FILE_NAME: STYLE_FILE_NAME, WORKSHEET_FILE_NAME: WORKSHEET_FILE_NAME, WORKSHEETS_FOLDER: WORKSHEETS_FOLDER, SHAREDSTRING_FILE_NAME: SHAREDSTRING_FILE_NAME, GROUP_SHEET_PR_XML: GROUP_SHEET_PR_XML, SINGLE_SHEET_PR_XML: SINGLE_SHEET_PR_XML } }, /*!**************************!*\ !*** ./js/core/class.js ***! \**************************/ function(module, exports, __webpack_require__) { var errors = __webpack_require__( /*! ./errors */ 7); var wrapOverridden = function(baseProto, methodName, method) { return function() { var prevCallBase = this.callBase; this.callBase = baseProto[methodName]; try { return method.apply(this, arguments) } finally { this.callBase = prevCallBase } } }; var clonePrototype = function(obj) { var func = function() {}; func.prototype = obj.prototype; return new func }; var redefine = function(members) { var overridden, memberName, member, that = this; if (!members) { return that } for (memberName in members) { member = members[memberName]; overridden = "function" === typeof that.prototype[memberName] && "function" === typeof member; that.prototype[memberName] = overridden ? wrapOverridden(that.parent.prototype, memberName, member) : member } return that }; var include = function() { var argument, name, i, classObj = this; for (i = 0; i < arguments.length; i++) { argument = arguments[i]; if (argument.ctor) { classObj._includedCtors.push(argument.ctor) } if (argument.postCtor) { classObj._includedPostCtors.push(argument.postCtor) } for (name in argument) { if ("ctor" === name || "postCtor" === name) { continue } if (name in classObj.prototype) { throw errors.Error("E0002", name) } classObj.prototype[name] = argument[name] } } return classObj }; var subclassOf = function(parentClass) { if (this.parent === parentClass) { return true } if (!this.parent || !this.parent.subclassOf) { return false } return this.parent.subclassOf(parentClass) }; var abstract = function() { throw errors.Error("E0001") }; var copyStatic = function() { var hasOwn = Object.prototype.hasOwnProperty; return function(source, destination) { for (var key in source) { if (!hasOwn.call(source, key)) { return } destination[key] = source[key] } } }(); var classImpl = function() {}; classImpl.inherit = function(members) { var inheritor = function() { if (!this || this === window || "function" !== typeof this.constructor) { throw errors.Error("E0003") } var i, instance = this, ctor = instance.ctor, includedCtors = instance.constructor._includedCtors, includedPostCtors = instance.constructor._includedPostCtors; for (i = 0; i < includedCtors.length; i++) { includedCtors[i].call(instance) } if (ctor) { ctor.apply(instance, arguments) } for (i = 0; i < includedPostCtors.length; i++) { includedPostCtors[i].call(instance) } }; inheritor.prototype = clonePrototype(this); copyStatic(this, inheritor); inheritor.inherit = this.inherit; inheritor.abstract = abstract; inheritor.redefine = redefine; inheritor.include = include; inheritor.subclassOf = subclassOf; inheritor.parent = this; inheritor._includedCtors = this._includedCtors ? this._includedCtors.slice(0) : []; inheritor._includedPostCtors = this._includedPostCtors ? this._includedPostCtors.slice(0) : []; inheritor.prototype.constructor = inheritor; inheritor.redefine(members); return inheritor }; classImpl.abstract = abstract; module.exports = classImpl }, /*!********************************!*\ !*** ./js/core/utils/array.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ./common */ 14), objectUtils = __webpack_require__( /*! ./object */ 27); var isEmpty = function(entity) { return Array.isArray(entity) && !entity.length }; var wrapToArray = function(entity) { return Array.isArray(entity) ? entity : [entity] }; var intersection = function(a, b) { if (!Array.isArray(a) || 0 === a.length || !Array.isArray(b) || 0 === b.length) { return [] } var result = []; $.each(a, function(_, value) { var index = inArray(value, b); if (index !== -1) { result.push(value) } }); return result }; var removeDuplicates = function(from, what) { if (!Array.isArray(from) || 0 === from.length) { return [] } if (!Array.isArray(what) || 0 === what.length) { return from.slice() } var result = []; $.each(from, function(_, value) { var index = inArray(value, what); if (index === -1) { result.push(value) } }); return result }; var normalizeIndexes = function(items, indexParameterName, currentItem, needIndexCallback) { var indexedItems = {}, parameterIndex = 0; $.each(items, function(index, item) { index = item[indexParameterName]; if (commonUtils.isDefined(index)) { indexedItems[index] = indexedItems[index] || []; if (item === currentItem) { indexedItems[index].unshift(item) } else { indexedItems[index].push(item) } delete item[indexParameterName] } }); objectUtils.orderEach(indexedItems, function(index, items) { $.each(items, function() { if (index >= 0) { this[indexParameterName] = parameterIndex++ } }) }); $.each(items, function() { if (!commonUtils.isDefined(this[indexParameterName]) && (!needIndexCallback || needIndexCallback(this))) { this[indexParameterName] = parameterIndex++ } }); return parameterIndex }; var inArray = function(value, object) { if (!object) { return -1 } var array = Array.isArray(object) ? object : object.toArray(); return array.indexOf(value) }; exports.isEmpty = isEmpty; exports.wrapToArray = wrapToArray; exports.intersection = intersection; exports.removeDuplicates = removeDuplicates; exports.normalizeIndexes = normalizeIndexes; exports.inArray = inArray }, /*!*********************************!*\ !*** ./js/core/utils/object.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ./common */ 14), typeUtils = __webpack_require__( /*! ./type */ 12), variableWrapper = __webpack_require__( /*! ./variable_wrapper */ 28); var clone = function() { function Clone() {} return function(obj) { Clone.prototype = obj; return new Clone } }(); var orderEach = function(map, func) { var key, i, keys = []; for (key in map) { if (map.hasOwnProperty(key)) { keys.push(key) } } keys.sort(function(x, y) { var isNumberX = commonUtils.isNumeric(x), isNumberY = commonUtils.isNumeric(y); if (isNumberX && isNumberY) { return x - y } if (isNumberX && !isNumberY) { return -1 } if (!isNumberX && isNumberY) { return 1 } if (x < y) { return -1 } if (x > y) { return 1 } return 0 }); for (i = 0; i < keys.length; i++) { key = keys[i]; func(key, map[key]) } }; var assignValueToProperty = function(target, property, value, assignByReference) { if (!assignByReference && variableWrapper.isWrapped(target[property])) { variableWrapper.assign(target[property], value) } else { target[property] = value } }; var deepExtendArraySafe = function(target, changes, extendComplexObject, assignByReference) { var prevValue, newValue; for (var name in changes) { prevValue = target[name]; newValue = changes[name]; if (target === newValue) { continue } if (typeUtils.isPlainObject(newValue) && !(newValue instanceof $.Event)) { var goDeeper = extendComplexObject ? commonUtils.isObject(prevValue) : typeUtils.isPlainObject(prevValue); newValue = deepExtendArraySafe(goDeeper ? prevValue : {}, newValue, extendComplexObject, assignByReference) } if (void 0 !== newValue) { assignValueToProperty(target, name, newValue, assignByReference) } } return target }; exports.clone = clone; exports.orderEach = orderEach; exports.deepExtendArraySafe = deepExtendArraySafe }, /*!*******************************************!*\ !*** ./js/core/utils/variable_wrapper.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var logger = __webpack_require__( /*! ./console */ 13).logger, dependencyInjector = __webpack_require__( /*! ./dependency_injector */ 29); module.exports = dependencyInjector({ isWrapped: function() { return false }, isWritableWrapped: function() { return false }, wrap: function(value) { return value }, unwrap: function(value) { return value }, assign: function() { logger.error("Method 'assign' should not be used for not wrapped variables. Use 'isWrapped' method for ensuring.") } }) }, /*!**********************************************!*\ !*** ./js/core/utils/dependency_injector.js ***! \**********************************************/ function(module, exports, __webpack_require__) { module.exports = function(object) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ./extend */ 11).extend, isFunction = __webpack_require__( /*! ./common */ 14).isFunction, Class = __webpack_require__( /*! ../class */ 25); var BaseClass = Class.inherit(object), InjectedClass = BaseClass, instance = new InjectedClass(object), initialFields = {}; var injectFields = function(injectionObject, initial) { $.each(injectionObject, function(key) { if (isFunction(instance[key])) { if (initial || !object[key]) { object[key] = function() { return instance[key].apply(object, arguments) } } } else { if (initial) { initialFields[key] = object[key] } object[key] = instance[key] } }) }; injectFields(object, true); object.inject = function(injectionObject) { InjectedClass = InjectedClass.inherit(injectionObject); instance = new InjectedClass; injectFields(injectionObject) }; object.resetInjection = function() { extend(object, initialFields); InjectedClass = BaseClass; instance = new BaseClass }; return object } }, /*!*******************************!*\ !*** external "window.JSZip" ***! \*******************************/ function(module, exports) { module.exports = window.JSZip }, /*!******************************************************!*\ !*** ./js/client_exporter/excel_format_converter.js ***! \******************************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), stringUtils = __webpack_require__( /*! ../core/utils/string */ 18), numberFormatter = __webpack_require__( /*! ../localization/number */ 32), dateLocalization = __webpack_require__( /*! ../localization/date */ 33), getLanguageID = __webpack_require__( /*! ../localization/language_codes */ 35).getLanguageId, UNSUPPORTED_FORMAT_MAPPING = { quarter: "shortDate", quarterAndYear: "shortDate", minute: "longTime", millisecond: "longTime" }, FORMAT_SEPARATORS = " .,:;/\\<>()-", ARABIC_ZERO_CODE = 1632, DEFINED_NUMBER_FORMTATS = { thousands: "#,##0{0},"K"", millions: "#,##0{0},,"M"", billions: "#,##0{0},,,"B"", trillions: "#,##0{0},,,,"T"", percent: "0{0}%", decimal: "#{0}", fixedpoint: "#,##0{0}", exponential: "0{0}E+00", currency: " " }; __webpack_require__( /*! ../localization/currency */ 36); var excelFormatConverter = module.exports = { _applyPrecision: function(format, precision) { var result, i; if (precision > 0) { result = "decimal" !== format ? "." : ""; for (i = 0; i < precision; i++) { result += "0" } return result } return "" }, _getCurrencyFormat: function(currency) { return numberFormatter.getOpenXmlCurrencyFormat(currency) }, _isDigit: function(char) { var code = char && char.charCodeAt(0); return char >= "0" && char <= "9" || code >= ARABIC_ZERO_CODE && code < ARABIC_ZERO_CODE + 10 }, _getDifference: function(defaultPattern, patterns, processedIndexes) { var isDigit, i = 0, that = this, result = []; var patternsFilter = function(pattern) { return defaultPattern[i] !== pattern[i] }; if (!Array.isArray(patterns)) { patterns = [patterns] } for (i = 0; i < defaultPattern.length; i++) { if (processedIndexes.indexOf(i) < 0 && patterns.filter(patternsFilter).length) { do { isDigit = that._isDigit(defaultPattern[i]); if (!result.length && !isDigit && that._isDigit(patterns[0][i])) { break } result.push(i); processedIndexes.unshift(i); i++ } while (defaultPattern[i] && FORMAT_SEPARATORS.indexOf(defaultPattern[i]) < 0 && isDigit === that._isDigit(defaultPattern[i])); break } } if (1 === result.length && ("0" === defaultPattern[processedIndexes[0] - 1] || "Ù " === defaultPattern[processedIndexes[0] - 1])) { processedIndexes.unshift(processedIndexes[0] - 1) } return result }, _replaceCharsCore: function(pattern, indexes, char, patternPositions) { var baseCharIndex = indexes[0]; var patternIndex = baseCharIndex < patternPositions.length ? patternPositions[baseCharIndex] : baseCharIndex; indexes.forEach(function(_, index) { pattern = pattern.substr(0, patternIndex + index) + (char.length > 1 ? char[index] : char) + pattern.substr(patternIndex + index + 1) }); if (1 === indexes.length) { pattern = pattern.replace("0" + char, char + char); pattern = pattern.replace("Ù " + char, char + char) } return pattern }, _replaceChars: function(pattern, indexes, char, patternPositions) { var i, index, patternIndex; if (!this._isDigit(pattern[indexes[0]] || "0")) { var letterCount = Math.max(indexes.length <= 3 ? 3 : 4, char.length); while (indexes.length > letterCount) { index = indexes.pop(); patternIndex = patternPositions[index]; patternPositions[index] = -1; for (i = index + 1; i < patternPositions.length; i++) { patternPositions[i]-- } pattern = pattern.substr(0, patternIndex) + pattern.substr(patternIndex + 1) } index = indexes[indexes.length - 1] + 1, patternIndex = index < patternPositions.length ? patternPositions[index] : index; while (indexes.length < letterCount) { indexes.push(indexes[indexes.length - 1] + 1); for (i = index; i < patternPositions.length; i++) { patternPositions[i]++ } pattern = pattern.substr(0, patternIndex) + " " + pattern.substr(patternIndex) } } pattern = this._replaceCharsCore(pattern, indexes, char, patternPositions); return pattern }, _format: function(value, format) { if (Array.isArray(value)) { return value.map(function(value) { return (dateLocalization.format(value, format) || "").toString() }) } return (dateLocalization.format(value, format) || "").toString() }, _escapeChars: function(pattern, defaultPattern, processedIndexes, patternPositions) { var escapeIndexes = defaultPattern.split("").map(function(char, index) { if (processedIndexes.indexOf(index) < 0 && (FORMAT_SEPARATORS.indexOf(char) < 0 || "/" === char)) { return patternPositions[index] } return -1 }); pattern = pattern.split("").map(function(char, index) { if (escapeIndexes.indexOf(index) >= 0) { return "\\" + char } return char }).join(""); pattern = pattern.replace("AM\\/PM", "AM/PM"); return pattern }, _hasArabicDigits: function(text) { var code; for (var i = 0; i < text.length; i++) { code = text.charCodeAt(i); if (code >= ARABIC_ZERO_CODE && code < ARABIC_ZERO_CODE + 10) { return true } } return false }, _convertDateFormat: function(format) { format = UNSUPPORTED_FORMAT_MAPPING[format && format.type || format] || format; var that = this, processedIndexes = [], defaultPattern = that._format(new Date(2009, 8, 8, 6, 5, 4), format), patternPositions = defaultPattern.split("").map(function(_, index) { return index }), result = defaultPattern, datePatterns = [{ date: new Date(2009, 8, 8, 6, 5, 2), pattern: "s" }, { date: new Date(2009, 8, 8, 6, 2, 4), pattern: "m" }, { date: new Date(2009, 8, 8, 2, 5, 4), pattern: "H" }, { date: new Date(2009, 8, 8, 18, 5, 4), pattern: "AM/PM" }, { date: new Date(2009, 8, 1, 6, 5, 4), pattern: "d" }, { date: [new Date(2009, 8, 2, 6, 5, 4), new Date(2009, 8, 3, 6, 5, 4), new Date(2009, 8, 4, 6, 5, 4)], pattern: "d" }, { date: new Date(2009, 9, 6, 6, 5, 4), pattern: "M" }, { date: new Date(1998, 8, 8, 6, 5, 4), pattern: "y" }]; if (!result) { return } datePatterns.forEach(function(test) { var diff = that._getDifference(defaultPattern, that._format(test.date, format), processedIndexes); result = that._replaceChars(result, diff, test.pattern, patternPositions) }); result = that._escapeChars(result, defaultPattern, processedIndexes, patternPositions); result = that._getLanguageInfo(defaultPattern) + result; return result }, _getLanguageInfo: function(defaultPattern) { var languageID = getLanguageID(), languageIDStr = languageID ? languageID.toString(16) : "", languageInfo = ""; if (this._hasArabicDigits(defaultPattern)) { while (languageIDStr.length < 3) { languageIDStr = "0" + languageIDStr } languageInfo = "[$-2010" + languageIDStr + "]" } else { if (languageIDStr) { languageInfo = "[$-" + languageIDStr + "]" } } return languageInfo }, _convertNumberFormat: function(format, precision, currency) { var result, excelFormat = "currency" === format ? this._getCurrencyFormat(currency) : DEFINED_NUMBER_FORMTATS[format.toLowerCase()]; if (excelFormat) { result = stringUtils.format(excelFormat, this._applyPrecision(format, precision)) } return result }, convertFormat: function(format, precision, type, currency) { if (commonUtils.isDefined(format)) { if ("date" === type) { return excelFormatConverter._convertDateFormat(format) } else { if (commonUtils.isString(format) && DEFINED_NUMBER_FORMTATS[format.toLowerCase()]) { return excelFormatConverter._convertNumberFormat(format, precision, currency) } } } } } }, /*!***********************************!*\ !*** ./js/localization/number.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), dependencyInjector = __webpack_require__( /*! ../core/utils/dependency_injector */ 29), inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, isPlainObject = __webpack_require__( /*! ../core/utils/type */ 12).isPlainObject, errors = __webpack_require__( /*! ../core/errors */ 7); var MAX_LARGE_NUMBER_POWER = 4, DECIMAL_BASE = 10; var NUMERIC_FORMATS = ["currency", "fixedpoint", "exponential", "percent", "decimal"]; var LargeNumberFormatPostfixes = { 1: "K", 2: "M", 3: "B", 4: "T" }; var LargeNumberFormatPowers = { largenumber: "auto", thousands: 1, millions: 2, billions: 3, trillions: 4 }; var numberLocalization = dependencyInjector({ numericFormats: NUMERIC_FORMATS, defaultLargeNumberFormatPostfixes: LargeNumberFormatPostfixes, _parseNumberFormatString: function(formatType) { var formatList, formatObject = {}; if (!formatType || "string" !== typeof formatType) { return } formatList = formatType.split(" "); $.each(formatList, function(index, value) { if (inArray(value, NUMERIC_FORMATS) > -1) { formatObject.formatType = value } else { if (value in LargeNumberFormatPowers) { formatObject.power = LargeNumberFormatPowers[value] } } }); if (formatObject.power && !formatObject.formatType) { formatObject.formatType = "fixedpoint" } if (formatObject.formatType) { return formatObject } }, _calculateNumberPower: function(value, base, minPower, maxPower) { var number = Math.abs(value), power = 0; if (number > 1) { while (number && number >= base && (void 0 === maxPower || power < maxPower)) { power++; number /= base } } else { if (number > 0 && number < 1) { while (number < 1 && (void 0 === minPower || power > minPower)) { power--; number *= base } } } return power }, _getNumberByPower: function(number, power, base) { var result = number; while (power > 0) { result /= base; power-- } while (power < 0) { result *= base; power++ } return result }, _formatNumber: function(value, formatObject, formatConfig) { var powerPostfix; var result; if ("auto" === formatObject.power) { formatObject.power = this._calculateNumberPower(value, 1e3, 0, MAX_LARGE_NUMBER_POWER) } if (formatObject.power) { value = this._getNumberByPower(value, formatObject.power, 1e3) } powerPostfix = this.defaultLargeNumberFormatPostfixes[formatObject.power] || ""; result = this._formatNumberCore(value, formatObject.formatType, formatConfig); result = result.replace(/(\d|.$)(\D*)$/, "$1" + powerPostfix + "$2"); return result }, _formatNumberExponential: function(value, formatConfig) { var powString, power = this._calculateNumberPower(value, DECIMAL_BASE), number = this._getNumberByPower(value, power, DECIMAL_BASE); if (void 0 === formatConfig.precision) { formatConfig.precision = 1 } if (number.toFixed(formatConfig.precision || 0) >= DECIMAL_BASE) { power++; number /= DECIMAL_BASE } powString = (power >= 0 ? "+" : "") + power.toString(); return this._formatNumberCore(number, "fixedpoint", formatConfig) + "E" + powString }, _addZeroes: function(value, precision) { var multiplier = Math.pow(10, precision); value = (value * multiplier >>> 0) / multiplier; var result = value.toString(); while (result.length < precision) { result = "0" + result } return result }, _addGroupSeparators: function(value) { var parts = value.toString().split("."); return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "") }, _formatNumberCore: function(value, format, formatConfig) { if ("exponential" === format) { return this._formatNumberExponential(value, formatConfig) } if ("decimal" !== format && null !== formatConfig.precision) { formatConfig.precision = formatConfig.precision || 0 } if ("percent" === format) { value = 100 * value } if (void 0 !== formatConfig.precision) { if ("decimal" === format) { value = this._addZeroes(value, formatConfig.precision) } else { value = null === formatConfig.precision ? value.toPrecision() : value.toFixed(formatConfig.precision) } } if ("decimal" !== format) { value = this._addGroupSeparators(value) } if ("percent" === format) { value += "%" } return value.toString() }, _normalizeFormat: function(format) { if (!format) { return {} } if ("function" === typeof format) { return format } if (!isPlainObject(format)) { format = { type: format } } if (format.type) { format.type = format.type.toLowerCase() } return format }, format: function(value, format) { if ("number" !== typeof value) { return value } if ("number" === typeof format) { return value } format = format && format.formatter || format; if ("function" === typeof format) { return format(value) } format = this._normalizeFormat(format); if (!format.type) { format.type = "decimal" } var numberConfig = this._parseNumberFormatString(format.type); if (!numberConfig) { return } return this._formatNumber(value, numberConfig, format) }, parse: function(text, format) { if (!text) { return } if (format && format.parser) { return format.parser(text) } if (format) { errors.log("W0011") } return parseFloat(text.replace(/^\D+|,+/g, "")) } }); module.exports = numberLocalization }, /*!*********************************!*\ !*** ./js/localization/date.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), numberLocalization = __webpack_require__( /*! ./number */ 32), dependencyInjector = __webpack_require__( /*! ../core/utils/dependency_injector */ 29), isString = __webpack_require__( /*! ../core/utils/common */ 14).isString, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, errors = __webpack_require__( /*! ../core/errors */ 7); __webpack_require__( /*! ./core */ 34); var FORMATS_TO_PATTERN_MAP = { shortdate: "M/d/y", shorttime: "h:mm a", longdate: "EEEE, MMMM d, y", longtime: "h:mm:ss a", monthandday: "MMMM d", monthandyear: "MMMM y", quarterandyear: "QQQ y", day: "d", year: "y", shortdateshorttime: "M/d/y, h:mm a", mediumdatemediumtime: "MMMM d, h:mm a", longdatelongtime: "EEEE, MMMM d, y, h:mm:ss a", month: "LLLL", shortyear: "yy", dayofweek: "EEEE", quarter: "QQQ", hour: "HH", minute: "mm", second: "ss", millisecond: "SSS", "datetime-local": "yyyy-MM-ddTHH':'mm':'ss" }; var parseTime = function(text) { var now = new Date, parts = text.split(" "), time = parts[0].split(":"), hours = Number(time[0]), minutes = Number(time[1]), second = Number(time[2]) || 0, pm = /^pm$/i.test(parts[1]), isValid = second < 60 && minutes < 60 && hours > 0 && hours < 13; if (!isValid) { return null } if (!pm && 12 === hours) { hours = 0 } if (pm && 12 !== hours) { hours += 12 } return new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, second) }; var removeTimezoneOffset = function(date) { return new Date(date.valueOf() + 60 * date.getTimezoneOffset() * 1e3) }; var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var amPm = function(date) { return date.getHours() >= 12 ? "PM" : "AM" }; var getTwelveHourTimeFormat = function(hours) { return hours % 12 || 12 }; var formatNumber = function(number, precision) { return numberLocalization.format(number, { type: "decimal", precision: precision }) }; var FORMATTERS = { millisecond: function(date) { return formatNumber(date.getMilliseconds(date), 3) }, second: function(date) { return formatNumber(date.getSeconds(), 2) }, minute: function(date) { return formatNumber(date.getMinutes(), 2) }, h: function(date) { return formatNumber(getTwelveHourTimeFormat(date.getHours()), 1) }, hh: function(date) { return formatNumber(getTwelveHourTimeFormat(date.getHours()), 2) }, hour: function(date) { return formatNumber(date.getHours(), 2) }, day: function(date) { return String(date.getDate()) }, dayofweek: function(date) { return days[date.getDay()] }, M: function(date) { return date.getMonth() + 1 }, MM: function(date) { return formatNumber(date.getMonth() + 1, 2) }, month: function(date) { return months[date.getMonth()] }, year: function(date) { return String(date.getFullYear()) }, shortyear: function(date) { return String(date.getFullYear()).substr(2, 2) }, shorttime: function(date) { return FORMATTERS.h(date) + ":" + FORMATTERS.minute(date) + " " + amPm(date) }, shortdate: function(date) { return [FORMATTERS.M(date), FORMATTERS.day(date), FORMATTERS.year(date)].join("/") }, shortdateshorttime: function(date) { return [FORMATTERS.shortdate(date), FORMATTERS.shorttime(date)].join(", ") }, mediumdatemediumtime: function(date) { return [FORMATTERS.monthandday(date), FORMATTERS.shorttime(date)].join(", ") }, monthandyear: function(date) { return [FORMATTERS.month(date), FORMATTERS.year(date)].join(" ") }, monthandday: function(date) { return [FORMATTERS.month(date), FORMATTERS.day(date)].join(" ") }, longdate: function(date) { return FORMATTERS.dayofweek(date) + ", " + FORMATTERS.month(date) + " " + FORMATTERS.day(date) + ", " + FORMATTERS.year(date) }, longtime: function(date) { return [FORMATTERS.h(date), FORMATTERS.minute(date), FORMATTERS.second(date)].join(":") + " " + amPm(date) }, longdatelongtime: function(date) { return [FORMATTERS.longdate(date), FORMATTERS.longtime(date)].join(", ") }, d: function(date) { return formatNumber(date.getDate(), 1) }, dd: function(date) { return formatNumber(date.getDate(), 2) }, "d MMMM": function(date) { return FORMATTERS.day(date) + " " + FORMATTERS.month(date) }, "yyyy/M/d": function(date) { return [FORMATTERS.year(date), FORMATTERS.M(date), FORMATTERS.day(date)].join("/") }, "yyyy/MM/dd": function(date) { return [FORMATTERS.year(date), FORMATTERS.MM(date), FORMATTERS.dd(date)].join("/") }, "dd.MM.yyyy": function(date) { return [FORMATTERS.dd(date), FORMATTERS.MM(date), FORMATTERS.year(date)].join(".") }, "HH:mm": function(date) { return [FORMATTERS.hour(date), FORMATTERS.minute(date)].join(":") }, "HH:mm:ss": function(date) { return [FORMATTERS["HH:mm"](date), FORMATTERS.second(date)].join(":") }, "h:mm:ss": function(date) { return [FORMATTERS.h(date), FORMATTERS.minute(date), FORMATTERS.second(date)].join(":") }, "h:mm:ss:SSS": function(date) { return [FORMATTERS.h(date), FORMATTERS.minute(date), FORMATTERS.second(date), FORMATTERS.SSS(date)].join(":") }, "yyyy/MM/dd HH:mm:ss": function(date) { return [FORMATTERS["yyyy/MM/dd"](date), FORMATTERS["HH:mm:ss"](date)].join(" ") }, "yyyy-MM-dd hh:mm:ss.SSS a": function(date) { return [ [FORMATTERS.year(date), FORMATTERS.MM(date), FORMATTERS.dd(date)].join("-"), [FORMATTERS.hh(date), FORMATTERS.minute(date), FORMATTERS.second(date)].join(":") + "." + FORMATTERS.SSS(date), amPm(date) ].join(" ") }, "yyyy-MM-dd": function(date) { return [FORMATTERS.year(date), FORMATTERS.MM(date), FORMATTERS.dd(date)].join("-") }, yyyyMMddTHHmmss: function(date) { return [FORMATTERS.year(date), FORMATTERS.MM(date), FORMATTERS.dd(date), "T", FORMATTERS.hour(date), FORMATTERS.minute(date), FORMATTERS.second(date)].join("") }, "datetime-local": function(date) { return FORMATTERS["yyyy-MM-dd"](date) + "T" + FORMATTERS["HH:mm:ss"](date) }, "yyyy-MM-ddTHH:mm:ssZ": function(date) { return FORMATTERS["datetime-local"](date) + "Z" }, "yyyy-MM-ddTHH:mmZ": function(date) { return FORMATTERS["yyyy-MM-dd"](date) + "T" + FORMATTERS.hour(date) + ":" + FORMATTERS.minute(date) + "Z" }, "dd/MM/yyyy": function(date) { return [FORMATTERS.dd(date), FORMATTERS.MM(date), FORMATTERS.year(date)].join("/") }, "yyyy MMMM d": function(date) { return [FORMATTERS.year(date), FORMATTERS.month(date), FORMATTERS.day(date)].join(" ") }, "EEEE, d": function(date) { return [FORMATTERS.dayofweek(date), FORMATTERS.d(date)].join(", ") }, "EEEE MM yy": function(date) { return [FORMATTERS.dayofweek(date), FORMATTERS.MM(date), FORMATTERS.shortyear(date)].join(" ") }, "d MMMM yyyy": function(date) { return [FORMATTERS.day(date), FORMATTERS.month(date), FORMATTERS.year(date)].join(" ") }, E: function(date) { return cutCaptions([FORMATTERS.dayofweek(date)], "abbreviated")[0] }, EEE: function(date) { return FORMATTERS.E(date) }, "EEE hh": function(date) { return [FORMATTERS.EEE(date), FORMATTERS.hh(date)].join(" ") }, "ss SSS": function(date) { return [FORMATTERS.second(date), FORMATTERS.SSS(date)].join(" ") }, quarter: function(date) { var month = date.getMonth(); if (month >= 0 && month < 3) { return "Q1" } if (month > 2 && month < 6) { return "Q2" } if (month > 5 && month < 9) { return "Q3" } return "Q4" }, quarterandyear: function(date) { return FORMATTERS.quarter(date) + " " + FORMATTERS.year(date) } }; var parseWithoutTimezone = function(text) { if ("Z" !== text.slice(-1)) { text += "Z" } return removeTimezoneOffset(new Date(text)) }; var PARSERS = { day: function(text) { var now = new Date; return new Date(now.getFullYear(), now.getMonth(), Number(text)) }, hour: function(text) { var now = new Date; return new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(text)) }, minute: function(text) { var now = new Date; return new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), Number(text)) }, month: function(text) { return new Date((new Date).getFullYear(), inArray(text, months)) }, monthandday: function(text) { var parts = text.split(" "), result = PARSERS.month(parts[0]); result.setDate(Number(parts[1])); return result }, monthandyear: function(text) { var parts = text.split(" "), result = PARSERS.month(parts[0]); result.setYear(Number(parts[1])); return result }, year: function(text) { var date = new Date(new Date(0)); date.setUTCFullYear(Number(text)); return removeTimezoneOffset(date) }, second: function(text) { var now = new Date; return new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), Number(text)) }, shortyear: function(text) { var MAX_YEAR_IN_XXI_CENTURY = 36; var year = Number(text); if (year > MAX_YEAR_IN_XXI_CENTURY) { year += 1900 } else { year += 2e3 } return PARSERS.year(year) }, shortdate: function(text) { if (!/^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/\d{1,4}/.test(text)) { return } var parts = text.split("/"); var date = new Date(Number(parts[2]), Number(parts[0]) - 1, Number(parts[1])); if (parts[2].length < 3) { date.setFullYear(Number(parts[2]), Number(parts[0]) - 1, Number(parts[1])) } return date }, longtime: function(text) { return parseTime(text) }, shorttime: function(text) { return parseTime(text) }, millisecond: function(text) { return new Date(Number(text)) }, "yyyy MMMM d": function(text) { var parts = text.split(" "); if (3 !== parts.length) { return } return new Date(Number(parts[0]), inArray(parts[1], months), Number(parts[2])) }, "HH:mm": function(text) { var parts = text.split(":"); return new Date(0, 0, 0, Number(parts[0]), Number(parts[1]), 0, 0) }, "yyyy-MM-ddTHH:mm:ssZ": parseWithoutTimezone, "yyyy-MM-ddTHH:mmZ": parseWithoutTimezone, "datetime-local": parseWithoutTimezone, mediumdatemediumtime: function(text) { var parts = text.split(", "), dateParts = parts[0].split(" "), timeParts = parts[1].split(" "); var amPm = 2 === timeParts.length ? timeParts.pop() : void 0; var result = PARSERS.month(dateParts[0]); result.setDate(Number(dateParts[1])); timeParts = timeParts[0].split(":"); var hours = Number(timeParts[0]); switch (String(amPm).toLowerCase()) { case "am": hours = 12 === hours ? 0 : hours; break; case "pm": hours = 12 === hours ? 12 : hours + 12 } result.setHours(hours); result.setMinutes(Number(timeParts[1])); return result } }; $.each(FORMATS_TO_PATTERN_MAP, function(key, value) { value = value.replace(/'/g, ""); FORMATTERS[value] = FORMATTERS[key]; PARSERS[value] = PARSERS[key] }); var getByFormat = function(obj, format) { return isString(format) && (obj[format.toLowerCase()] || obj[format.replace(/'/g, "")]) }; var cutCaptions = function(captions, format) { var lengthByFormat = { abbreviated: 3, "short": 2, narrow: 1 }; return $.map(captions, function(caption) { return caption.substr(0, lengthByFormat[format]) }) }; var possiblePartPatterns = { year: ["y", "yy", "yyyy"], day: ["d", "dd"], month: ["M", "MM", "MMM", "MMMM"], hours: ["H", "HH", "h", "hh", "ah"], minutes: ["m", "mm"], seconds: ["s", "ss"], milliseconds: ["S", "SS", "SSS"] }; var dateLocalization = dependencyInjector({ _getPatternByFormat: function(format) { return FORMATS_TO_PATTERN_MAP[format.toLowerCase()] }, _expandPattern: function(pattern) { return this._getPatternByFormat(pattern) || pattern }, formatUsesMonthName: function(format) { return this._expandPattern(format).indexOf("MMMM") !== -1 }, formatUsesDayName: function(format) { return this._expandPattern(format).indexOf("EEEE") !== -1 }, getFormatParts: function(format) { var pattern = this._getPatternByFormat(format) || format, result = []; $.each(pattern.split(/\W+/), function(_, formatPart) { $.each(possiblePartPatterns, function(partName, possiblePatterns) { if (inArray(formatPart, possiblePatterns) > -1) { result.push(partName) } }) }); return result }, getMonthNames: function(format) { return cutCaptions(months, format) }, getDayNames: function(format) { return cutCaptions(days, format) }, getTimeSeparator: function() { return ":" }, format: function(date, format) { if (!date) { return } if (!format) { return date } var formatter; if ("function" === typeof format) { formatter = format } else { if (format.formatter) { formatter = format.formatter } else { format = format.type || format; formatter = getByFormat(FORMATTERS, format) } } if (!formatter) { return } return formatter(date) }, parse: function(text, format) { var result, parser; if (!text) { return } if (!format) { return new Date(text) } if (format.parser) { return format.parser(text) } if (format.type || format.formatter) { format = format.type } if (format && "function" !== typeof format) { parser = getByFormat(PARSERS, format) } if (parser) { result = parser(text) } else { errors.log("W0012"); result = new Date(text) } if (!result || isNaN(result.getTime())) { return } return result }, firstDayOfWeekIndex: function() { return 0 } }); module.exports = dateLocalization }, /*!*********************************!*\ !*** ./js/localization/core.js ***! \*********************************/ function(module, exports, __webpack_require__) { var dependencyInjector = __webpack_require__( /*! ../core/utils/dependency_injector */ 29); module.exports = dependencyInjector({ locale: function() { var currentLocale = "en"; return function(locale) { if (!locale) { return currentLocale } currentLocale = locale } }() }) }, /*!*******************************************!*\ !*** ./js/localization/language_codes.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var locale = __webpack_require__( /*! ./core */ 34).locale, LANGUAGE_CODES = { ar: 1, bg: 2, ca: 3, "zh-Hans": 4, cs: 5, da: 6, de: 7, el: 8, en: 9, es: 10, fi: 11, fr: 12, he: 13, hu: 14, is: 15, it: 16, ja: 17, ko: 18, nl: 19, no: 20, pl: 21, pt: 22, rm: 23, ro: 24, ru: 25, hr: 26, sk: 27, sq: 28, sv: 29, th: 30, tr: 31, ur: 32, id: 33, uk: 34, be: 35, sl: 36, et: 37, lv: 38, lt: 39, tg: 40, fa: 41, vi: 42, hy: 43, az: 44, eu: 45, hsb: 46, mk: 47, tn: 50, xh: 52, zu: 53, af: 54, ka: 55, fo: 56, hi: 57, mt: 58, se: 59, ga: 60, ms: 62, kk: 63, ky: 64, sw: 65, tk: 66, uz: 67, tt: 68, bn: 69, pa: 70, gu: 71, or: 72, ta: 73, te: 74, kn: 75, ml: 76, as: 77, mr: 78, sa: 79, mn: 80, bo: 81, cy: 82, km: 83, lo: 84, gl: 86, kok: 87, syr: 90, si: 91, iu: 93, am: 94, tzm: 95, ne: 97, fy: 98, ps: 99, fil: 100, dv: 101, ha: 104, yo: 106, quz: 107, nso: 108, ba: 109, lb: 110, kl: 111, ig: 112, ii: 120, arn: 122, moh: 124, br: 126, ug: 128, mi: 129, oc: 130, co: 131, gsw: 132, sah: 133, qut: 134, rw: 135, wo: 136, prs: 140, gd: 145, "ar-SA": 1025, "bg-BG": 1026, "ca-ES": 1027, "zh-TW": 1028, "cs-CZ": 1029, "da-DK": 1030, "de-DE": 1031, "el-GR": 1032, "en-US": 1033, "fi-FI": 1035, "fr-FR": 1036, "he-IL": 1037, "hu-HU": 1038, "is-IS": 1039, "it-IT": 1040, "ja-JP": 1041, "ko-KR": 1042, "nl-NL": 1043, "nb-NO": 1044, "pl-PL": 1045, "pt-BR": 1046, "rm-CH": 1047, "ro-RO": 1048, "ru-RU": 1049, "hr-HR": 1050, "sk-SK": 1051, "sq-AL": 1052, "sv-SE": 1053, "th-TH": 1054, "tr-TR": 1055, "ur-PK": 1056, "id-ID": 1057, "uk-UA": 1058, "be-BY": 1059, "sl-SI": 1060, "et-EE": 1061, "lv-LV": 1062, "lt-LT": 1063, "tg-Cyrl-TJ": 1064, "fa-IR": 1065, "vi-VN": 1066, "hy-AM": 1067, "az-Latn-AZ": 1068, "eu-ES": 1069, "hsb-DE": 1070, "mk-MK": 1071, "tn-ZA": 1074, "xh-ZA": 1076, "zu-ZA": 1077, "af-ZA": 1078, "ka-GE": 1079, "fo-FO": 1080, "hi-IN": 1081, "mt-MT": 1082, "se-NO": 1083, "ms-MY": 1086, "kk-KZ": 1087, "ky-KG": 1088, "sw-KE": 1089, "tk-TM": 1090, "uz-Latn-UZ": 1091, "tt-RU": 1092, "bn-IN": 1093, "pa-IN": 1094, "gu-IN": 1095, "or-IN": 1096, "ta-IN": 1097, "te-IN": 1098, "kn-IN": 1099, "ml-IN": 1100, "as-IN": 1101, "mr-IN": 1102, "sa-IN": 1103, "mn-MN": 1104, "bo-CN": 1105, "cy-GB": 1106, "km-KH": 1107, "lo-LA": 1108, "gl-ES": 1110, "kok-IN": 1111, "syr-SY": 1114, "si-LK": 1115, "iu-Cans-CA": 1117, "am-ET": 1118, "ne-NP": 1121, "fy-NL": 1122, "ps-AF": 1123, "fil-PH": 1124, "dv-MV": 1125, "ha-Latn-NG": 1128, "yo-NG": 1130, "quz-BO": 1131, "nso-ZA": 1132, "ba-RU": 1133, "lb-LU": 1134, "kl-GL": 1135, "ig-NG": 1136, "ii-CN": 1144, "arn-CL": 1146, "moh-CA": 1148, "br-FR": 1150, "ug-CN": 1152, "mi-NZ": 1153, "oc-FR": 1154, "co-FR": 1155, "gsw-FR": 1156, "sah-RU": 1157, "qut-GT": 1158, "rw-RW": 1159, "wo-SN": 1160, "prs-AF": 1164, "gd-GB": 1169, "ar-IQ": 2049, "zh-CN": 2052, "de-CH": 2055, "en-GB": 2057, "es-MX": 2058, "fr-BE": 2060, "it-CH": 2064, "nl-BE": 2067, "nn-NO": 2068, "pt-PT": 2070, "sr-Latn-CS": 2074, "sv-FI": 2077, "az-Cyrl-AZ": 2092, "dsb-DE": 2094, "se-SE": 2107, "ga-IE": 2108, "ms-BN": 2110, "uz-Cyrl-UZ": 2115, "bn-BD": 2117, "mn-Mong-CN": 2128, "iu-Latn-CA": 2141, "tzm-Latn-DZ": 2143, "quz-EC": 2155, "ar-EG": 3073, "zh-HK": 3076, "de-AT": 3079, "en-AU": 3081, "es-ES": 3082, "fr-CA": 3084, "sr-Cyrl-CS": 3098, "se-FI": 3131, "quz-PE": 3179, "ar-LY": 4097, "zh-SG": 4100, "de-LU": 4103, "en-CA": 4105, "es-GT": 4106, "fr-CH": 4108, "hr-BA": 4122, "smj-NO": 4155, "ar-DZ": 5121, "zh-MO": 5124, "de-LI": 5127, "en-NZ": 5129, "es-CR": 5130, "fr-LU": 5132, "bs-Latn-BA": 5146, "smj-SE": 5179, "ar-MA": 6145, "en-IE": 6153, "es-PA": 6154, "fr-MC": 6156, "sr-Latn-BA": 6170, "sma-NO": 6203, "ar-TN": 7169, "en-ZA": 7177, "es-DO": 7178, "sr-Cyrl-BA": 7194, "sma-SE": 7227, "ar-OM": 8193, "en-JM": 8201, "es-VE": 8202, "bs-Cyrl-BA": 8218, "sms-FI": 8251, "ar-YE": 9217, "en-029": 9225, "es-CO": 9226, "sr-Latn-RS": 9242, "smn-FI": 9275, "ar-SY": 10241, "en-BZ": 10249, "es-PE": 10250, "sr-Cyrl-RS": 10266, "ar-JO": 11265, "en-TT": 11273, "es-AR": 11274, "sr-Latn-ME": 11290, "ar-LB": 12289, "en-ZW": 12297, "es-EC": 12298, "sr-Cyrl-ME": 12314, "ar-KW": 13313, "en-PH": 13321, "es-CL": 13322, "ar-AE": 14337, "es-UY": 14346, "ar-BH": 15361, "es-PY": 15370, "ar-QA": 16385, "en-IN": 16393, "es-BO": 16394, "en-MY": 17417, "es-SV": 17418, "en-SG": 18441, "es-HN": 18442, "es-NI": 19466, "es-PR": 20490, "es-US": 21514, "bs-Cyrl": 25626, "bs-Latn": 26650, "sr-Cyrl": 27674, "sr-Latn": 28698, smn: 28731, "az-Cyrl": 29740, sms: 29755, zh: 30724, nn: 30740, bs: 30746, "az-Latn": 30764, sma: 30779, "uz-Cyrl": 30787, "mn-Cyrl": 30800, "iu-Cans": 30813, "zh-Hant": 31748, nb: 31764, sr: 31770, "tg-Cyrl": 31784, dsb: 31790, smj: 31803, "uz-Latn": 31811, "mn-Mong": 31824, "iu-Latn": 31837, "tzm-Latn": 31839, "ha-Latn": 31848 }; exports.getLanguageId = function() { return LANGUAGE_CODES[locale()] } }, /*!*************************************!*\ !*** ./js/localization/currency.js ***! \*************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, numberLocalization = __webpack_require__( /*! ./number */ 32); numberLocalization.inject({ _formatNumberCore: function(value, format, formatConfig) { if ("currency" === format) { formatConfig.precision = formatConfig.precision || 0; return this.getCurrencySymbol().symbol + this.format(value, extend({}, formatConfig, { type: "fixedpoint" })) } return this.callBase.apply(this, arguments) }, getCurrencySymbol: function() { return { symbol: "$" } }, getOpenXmlCurrencyFormat: function() { return "$#,##0{0}_);\\($#,##0{0}\\)" } }) }, /*!*********************************************!*\ !*** ./js/client_exporter/image_creator.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var clipPaths, imageDeferreds, patterns, filters, $ = __webpack_require__( /*! ../core/renderer */ 9), Color = __webpack_require__( /*! ../color */ 38), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, camelize = __webpack_require__( /*! ../core/utils/inflector */ 39).camelize, when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when, _math = Math, PI = _math.PI, _min = _math.min, _abs = _math.abs, _sqrt = _math.sqrt, _pow = _math.pow, _atan2 = _math.atan2, _cos = _math.cos, _sin = _math.sin, _each = $.each, _extend = extend, _number = Number, IMAGE_QUALITY = 1, TEXT_DECORATION_LINE_WIDTH_COEFF = .05, DEFAULT_MARGIN_SIZE = { x: 30, y: 20 }, DEFAULT_FONT_SIZE = "10px", DEFAULT_FONT_FAMILY = "sans-serif", DEFAULT_TEXT_COLOR = "#000"; function createCanvas(width, height, withoutMargins) { var canvas = $("<canvas>")[0]; canvas.width = width + (withoutMargins ? 0 : 2 * DEFAULT_MARGIN_SIZE.x); canvas.height = height + (withoutMargins ? 0 : 2 * DEFAULT_MARGIN_SIZE.y); return canvas } function getStringFromCanvas(canvas, mimeType) { var dataURL = canvas.toDataURL(mimeType, IMAGE_QUALITY), imageData = atob(dataURL.substring(("data:" + mimeType + ";base64,").length)); return imageData } function arcTo(x1, y1, x2, y2, radius, largeArcFlag, clockwise, context) { var opSide, adjSide, centerX, centerY, startAngle, endAngle, cBx = (x1 + x2) / 2, cBy = (y1 + y2) / 2, aB = _atan2(y1 - y2, x1 - x2), k = largeArcFlag ? 1 : -1; aB += 90 * (PI / 180) * (clockwise ? 1 : -1); opSide = _sqrt(_pow(x2 - x1, 2) + _pow(y2 - y1, 2)) / 2; adjSide = _sqrt(_abs(_pow(radius, 2) - _pow(opSide, 2))); centerX = cBx + k * (adjSide * _cos(aB)); centerY = cBy + k * (adjSide * _sin(aB)); startAngle = _atan2(y1 - centerY, x1 - centerX); endAngle = _atan2(y2 - centerY, x2 - centerX); context.arc(centerX, centerY, radius, startAngle, endAngle, !clockwise) } function getElementOptions(element) { var coords, attr = parseAttributes(element.attributes || {}), style = element.style || {}, options = _extend({}, attr, { text: element.textContent.replace(/\s+/g, " "), textAlign: "middle" === attr["text-anchor"] ? "center" : attr["text-anchor"] }), transform = attr.transform; if (transform) { coords = transform.match(/translate\(-*\d+([.]\d+)*(,*\s*-*\d+([.]\d+)*)*/); if (coords) { coords = coords[0].match(/-*\d+([.]\d+)*/g); options.translateX = _number(coords[0]); options.translateY = coords[1] ? _number(coords[1]) : 0 } coords = transform.match(/rotate\(-*\d+([.]\d+)*(,*\s*-*\d+([.]\d+)*,*\s*-*\d+([.]\d+)*)*/); if (coords) { coords = coords[0].match(/-*\d+([.]\d+)*/g); options.rotationAngle = _number(coords[0]); options.rotationX = coords[1] && _number(coords[1]); options.rotationY = coords[2] && _number(coords[2]) } } parseStyles(style, options); return options } function drawRect(context, options) { var x = options.x, y = options.y, width = options.width, height = options.height, cornerRadius = options.rx; if (!cornerRadius) { context.rect(options.x, options.y, options.width, options.height) } else { cornerRadius = _min(cornerRadius, width / 2, height / 2); context.save(); context.translate(x, y); context.moveTo(width / 2, 0); context.arcTo(width, 0, width, height, cornerRadius); context.arcTo(width, height, 0, height, cornerRadius); context.arcTo(0, height, 0, 0, cornerRadius); context.arcTo(0, 0, cornerRadius, 0, cornerRadius); context.lineTo(width / 2, 0); context.restore() } } function drawImage(context, options) { var d = $.Deferred(), image = new Image; image.onload = function() { context.save(); context.globalAlpha = options.globalAlpha; transformElement(context, options); clipElement(context, options); context.drawImage(image, options.x, options.y, options.width, options.height); context.restore(); d.resolve() }; image.onerror = function() { d.resolve() }; imageDeferreds.push(d); image.setAttribute("crossOrigin", "anonymous"); image.src = options["xlink:href"] } function drawPath(context, dAttr) { var param1, param2, dArray = dAttr.split(" "), i = 0; do { param1 = _number(dArray[i + 1]); param2 = _number(dArray[i + 2]); switch (dArray[i]) { case "M": context.moveTo(param1, param2); i += 3; break; case "L": context.lineTo(param1, param2); i += 3; break; case "C": context.bezierCurveTo(param1, param2, _number(dArray[i + 3]), _number(dArray[i + 4]), _number(dArray[i + 5]), _number(dArray[i + 6])); i += 7; break; case "A": arcTo(_number(dArray[i - 2]), _number(dArray[i - 1]), _number(dArray[i + 6]), _number(dArray[i + 7]), param1, _number(dArray[i + 4]), _number(dArray[i + 5]), context); i += 8; break; case "Z": context.closePath(); i += 1 } } while (i < dArray.length) } function parseStyles(style, options) { _each(style, function(_, field) { if ("" !== style[field]) { options[camelize(field)] = style[field] } }); options.textDecoration = options.textDecoration || options.textDecorationLine; options.globalAlpha = options.opacity || options.globalAlpha } function parseUrl(urlString) { var matches = urlString && urlString.match(/url\(.*\#(.*?)["']?\)/i); return matches && matches[1] } function setFontStyle(context, options) { var fontParams = []; options.fontSize = options.fontSize || DEFAULT_FONT_SIZE; options.fontFamily || DEFAULT_FONT_FAMILY; options.fill = options.fill || DEFAULT_TEXT_COLOR; options.fontStyle && fontParams.push(options.fontStyle); options.fontWeight && fontParams.push(options.fontWeight); fontParams.push(options.fontSize); fontParams.push(options.fontFamily); context.font = fontParams.join(" "); context.textAlign = options.textAlign; context.fillStyle = options.fill; context.globalAlpha = options.globalAlpha } function drawText(context, options) { setFontStyle(context, options); options.text && context.fillText(options.text, options.x || 0, options.y || 0); strokeElement(context, options, true); drawTextDecoration(context, options) } function drawTextDecoration(context, options) { if (!options.textDecoration || "none" === options.textDecoration) { return } var x = options.x, textWidth = context.measureText(options.text).width, textHeight = parseInt(options.fontSize, 10), lineHeight = textHeight * TEXT_DECORATION_LINE_WIDTH_COEFF < 1 ? 1 : textHeight * TEXT_DECORATION_LINE_WIDTH_COEFF, y = options.y; switch (options.textDecoration) { case "line-through": y -= textHeight / 3 + lineHeight / 2; break; case "overline": y -= textHeight - lineHeight; break; case "underline": y += lineHeight } context.rect(x, y, textWidth, lineHeight); fillElement(context, options); strokeElement(context, options) } function createClipPath(element) { clipPaths[element.attributes.id.textContent] = element.childNodes[0] } function createPattern(element) { patterns[element.attributes.id.textContent] = element } function aggregateOpacity(options) { options.strokeOpacity = void 0 !== options["stroke-opacity"] ? options["stroke-opacity"] : 1; options.fillOpacity = void 0 !== options["fill-opacity"] ? options["fill-opacity"] : 1; if (void 0 !== options.opacity) { options.strokeOpacity *= options.opacity; options.fillOpacity *= options.opacity } } function hasTspan(element) { var nodes = element.childNodes; for (var i = 0; i < nodes.length; i++) { if ("tspan" === nodes[i].tagName) { return true } } return false } function drawTextElement(childNodes, context, options) { var line, lines = [], offset = 0; for (var i = 0; i < childNodes.length; i++) { var element = childNodes[i]; if (void 0 === element.tagName) { drawElement(element, context, options) } else { if ("tspan" === element.tagName || "text" === element.tagName) { var elementOptions = getElementOptions(element), mergedOptions = _extend({}, options, elementOptions); if ("tspan" === element.tagName && hasTspan(element)) { drawTextElement(element.childNodes, context, mergedOptions); return } mergedOptions.textAlign = "start"; if (!line || void 0 !== elementOptions.x) { line = { elements: [], options: [], widths: [], offsets: [] }; lines.push(line) } if (void 0 !== elementOptions.dy) { offset += Number(elementOptions.dy) } line.elements.push(element); line.options.push(mergedOptions); line.offsets.push(offset); setFontStyle(context, mergedOptions); line.widths.push(context.measureText(mergedOptions.text).width) } } } lines.forEach(function(line) { var commonWidth = line.widths.reduce(function(commonWidth, width) { return commonWidth + width }, 0), xDiff = 0, currentOffset = 0; if ("center" === options.textAlign) { xDiff = commonWidth / 2 } if ("end" === options.textAlign) { xDiff = commonWidth } line.options.forEach(function(o, index) { var width = line.widths[index]; o.x = o.x - xDiff + currentOffset; o.y += line.offsets[index]; currentOffset += width }); line.elements.forEach(function(element, index) { drawTextElement(element.childNodes, context, line.options[index]) }) }) } function drawElement(element, context, parentOptions) { var tagName = element.tagName, isText = "text" === tagName || "tspan" === tagName || void 0 === tagName, isImage = "image" === tagName, options = _extend({}, parentOptions, getElementOptions(element)); if ("hidden" === options.visibility) { return } context.save(); !isImage && transformElement(context, options); clipElement(context, options); aggregateOpacity(options); context.beginPath(); switch (element.tagName) { case void 0: drawText(context, options); break; case "text": case "tspan": drawTextElement(element.childNodes, context, options); break; case "image": drawImage(context, options); break; case "path": drawPath(context, options.d); break; case "rect": drawRect(context, options); context.closePath(); break; case "circle": context.arc(options.cx, options.cy, options.r, 0, 2 * PI, 1) } applyFilter(context, options); if (!isText) { fillElement(context, options); strokeElement(context, options) } context.restore() } function applyFilter(context, options) { var filterOptions, id = parseUrl(options.filter); if (id) { filterOptions = filters && filters[id]; if (!filterOptions) { filterOptions = { offsetX: 0, offsetY: 0, blur: 0, color: "#000" } } context.shadowOffsetX = filterOptions.offsetX; context.shadowOffsetY = filterOptions.offsetY; context.shadowColor = filterOptions.color; context.shadowBlur = filterOptions.blur } } function transformElement(context, options) { context.translate(options.translateX || 0, options.translateY || 0); delete options.translateX; delete options.translateY; if (options.rotationAngle) { context.translate(options.rotationX || 0, options.rotationY || 0); context.rotate(options.rotationAngle * PI / 180); context.translate(-(options.rotationX || 0), -(options.rotationY || 0)); delete options.rotationAngle; delete options.rotationX; delete options.rotationY } } function clipElement(context, options) { if (options["clip-path"]) { drawElement(clipPaths[parseUrl(options["clip-path"])], context, {}); context.clip(); delete options["clip-path"] } } function hex2rgba(hexColor, alpha) { var color = new Color(hexColor); return "rgba(" + color.r + "," + color.g + "," + color.b + "," + alpha + ")" } function createFilter(element) { var color, opacity, filterOptions = {}; _each(element.childNodes, function(_, node) { var attr = node.attributes; if (!attr.result) { return } switch (attr.result.value) { case "gaussianBlurResult": if (attr.stdDeviation) { filterOptions.blur = _number(attr.stdDeviation.value) } break; case "offsetResult": filterOptions.offsetX = _number(attr.dx.value); filterOptions.offsetY = _number(attr.dy.value); break; case "floodResult": color = attr["flood-color"] ? attr["flood-color"].value : "#000"; opacity = attr["flood-opacity"] ? attr["flood-opacity"].value : 1; filterOptions.color = hex2rgba(color, opacity) } }); filters[element.id] = filterOptions } function drawCanvasElements(elements, context, parentOptions) { var options; _each(elements, function(_, element) { switch (element.tagName && element.tagName.toLowerCase()) { case "g": options = _extend({}, parentOptions, getElementOptions(element)); context.save(); transformElement(context, options); clipElement(context, options); drawCanvasElements(element.childNodes, context, options); context.restore(); break; case "defs": clipPaths = {}; patterns = {}; filters = {}; drawCanvasElements(element.childNodes, context); break; case "clippath": createClipPath(element); break; case "pattern": createPattern(element); break; case "filter": createFilter(element); break; default: drawElement(element, context, parentOptions) } }) } function setLineDash(context, options) { var matches = options["stroke-dasharray"] && options["stroke-dasharray"].match(/(\d+)/g); if (matches && matches.length && context.setLineDash) { matches = $.map(matches, function(item) { return _number(item) }); context.setLineDash(matches) } } function strokeElement(context, options, isText) { var stroke = options.stroke; if (stroke && "none" !== stroke && 0 !== options["stroke-width"]) { setLineDash(context, options); context.lineJoin = options["stroke-linejoin"]; context.lineWidth = options["stroke-width"]; context.globalAlpha = options.strokeOpacity; context.strokeStyle = stroke; isText ? context.strokeText(options.text, options.x, options.y) : context.stroke() } } function getPattern(context, fill) { var pattern = patterns[parseUrl(fill)], options = getElementOptions(pattern), patternCanvas = createCanvas(options.width, options.height, true), patternContext = patternCanvas.getContext("2d"); drawCanvasElements(pattern.childNodes, patternContext, options); return context.createPattern(patternCanvas, "repeat") } function fillElement(context, options) { var fill = options.fill; if (fill && "none" !== fill) { context.fillStyle = fill.search(/url/) === -1 ? fill : getPattern(context, fill); context.globalAlpha = options.fillOpacity; context.fill() } } var parseAttributes = function(attributes) { var attr, newAttributes = {}; $.each(attributes, function(index, item) { attr = item.textContent; if (isFinite(attr)) { attr = _number(attr) } newAttributes[item.name.toLowerCase()] = attr }); return newAttributes }; function drawBackground(context, width, height, backgroundColor) { context.fillStyle = backgroundColor || "#ffffff"; context.fillRect(-DEFAULT_MARGIN_SIZE.x, -DEFAULT_MARGIN_SIZE.y, width + 2 * DEFAULT_MARGIN_SIZE.x, height + 2 * DEFAULT_MARGIN_SIZE.y) } function getCanvasFromSvg(markup, width, height, backgroundColor) { var canvas = createCanvas(width, height), context = canvas.getContext("2d"), parser = new DOMParser, elem = parser.parseFromString(markup, "image/svg+xml"), svgElem = elem.childNodes[0]; context.translate(DEFAULT_MARGIN_SIZE.x, DEFAULT_MARGIN_SIZE.y); imageDeferreds = []; document.body.appendChild(canvas); if (svgElem.attributes.direction) { canvas.dir = svgElem.attributes.direction.textContent } drawBackground(context, width, height, backgroundColor); drawCanvasElements(svgElem.childNodes, context, {}); document.body.removeChild(canvas); return canvas } function resolveString(string, canvas, mimeType) { when.apply($, imageDeferreds).done(function() { var resultString = getStringFromCanvas(canvas, mimeType); string.resolve(resultString) }) } exports.imageCreator = { getImageData: function(markup, options) { var mimeType = "image/" + options.format, string = $.Deferred(), width = options.width, height = options.height, backgroundColor = options.backgroundColor; if (commonUtils.isFunction(options.__parseAttributesFn)) { parseAttributes = options.__parseAttributesFn } resolveString(string, getCanvasFromSvg(markup, width, height, backgroundColor), mimeType); return string }, getData: function(markup, options) { var that = this, imageData = exports.imageCreator.getImageData(markup, options), mimeType = "image/" + options.format, data = $.Deferred(); when(imageData).done(function(binaryData) { imageData = commonUtils.isFunction(window.Blob) ? that._getBlob(binaryData, mimeType) : that._getBase64(binaryData); data.resolve(imageData) }); return data }, _getBlob: function(binaryData, mimeType) { var i, dataArray = new Uint8Array(binaryData.length); for (i = 0; i < binaryData.length; i++) { dataArray[i] = binaryData.charCodeAt(i) } return new Blob([dataArray.buffer], { type: mimeType }) }, _getBase64: function(binaryData) { return window.btoa(binaryData) } }; exports.getData = function(data, options, callback) { exports.imageCreator.getData(data, options).done(callback) } }, /*!*********************!*\ !*** ./js/color.js ***! \*********************/ function(module, exports) { var standardColorNames = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd", blue: "0000ff", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "00ffff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dodgerblue: "1e90ff", feldspar: "d19275", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgrey: "d3d3d3", lightgreen: "90ee90", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslateblue: "8470ff", lightslategray: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "00ff00", limegreen: "32cd32", linen: "faf0e6", magenta: "ff00ff", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370d8", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "d87093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "ff0000", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", violetred: "d02090", wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5", yellow: "ffff00", yellowgreen: "9acd32" }; var standardColorTypes = [{ re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, process: function(colorString) { return [parseInt(colorString[1], 10), parseInt(colorString[2], 10), parseInt(colorString[3], 10)] } }, { re: /^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d*\.*\d+)\)$/, process: function(colorString) { return [parseInt(colorString[1], 10), parseInt(colorString[2], 10), parseInt(colorString[3], 10), parseFloat(colorString[4])] } }, { re: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/, process: function(colorString) { return [parseInt(colorString[1], 16), parseInt(colorString[2], 16), parseInt(colorString[3], 16)] } }, { re: /^#([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})$/, process: function(colorString) { return [parseInt(colorString[1] + colorString[1], 16), parseInt(colorString[2] + colorString[2], 16), parseInt(colorString[3] + colorString[3], 16)] } }, { re: /^hsv\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, process: function(colorString) { var h = parseInt(colorString[1], 10), s = parseInt(colorString[2], 10), v = parseInt(colorString[3], 10), rgb = hsvToRgb(h, s, v); return [rgb[0], rgb[1], rgb[2], 1, [h, s, v]] } }, { re: /^hsl\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, process: function(colorString) { var h = parseInt(colorString[1], 10), s = parseInt(colorString[2], 10), l = parseInt(colorString[3], 10), rgb = hslToRgb(h, s, l); return [rgb[0], rgb[1], rgb[2], 1, null, [h, s, l]] } }]; function Color(value) { this.baseColor = value; var color; if (value) { color = String(value).toLowerCase().replace(/ /g, ""); color = standardColorNames[color] ? "#" + standardColorNames[color] : color; color = parseColor(color) } if (!color) { this.colorIsInvalid = true } color = color || {}; this.r = normalize(color[0]); this.g = normalize(color[1]); this.b = normalize(color[2]); this.a = normalize(color[3], 1, 1); if (color[4]) { this.hsv = { h: color[4][0], s: color[4][1], v: color[4][2] } } else { this.hsv = toHsvFromRgb(this.r, this.g, this.b) } if (color[5]) { this.hsl = { h: color[5][0], s: color[5][1], l: color[5][2] } } else { this.hsl = toHslFromRgb(this.r, this.g, this.b) } } function parseColor(color) { if ("transparent" === color) { return [0, 0, 0, 0] } var str, i = 0, ii = standardColorTypes.length; for (; i < ii; ++i) { str = standardColorTypes[i].re.exec(color); if (str) { return standardColorTypes[i].process(str) } } return null } function normalize(colorComponent, def, max) { def = def || 0; max = max || 255; return colorComponent < 0 || isNaN(colorComponent) ? def : colorComponent > max ? max : colorComponent } function toHexFromRgb(r, g, b) { return "#" + (16777216 | r << 16 | g << 8 | b).toString(16).slice(1) } function toHsvFromRgb(r, g, b) { var H, S, V, max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min; V = max; S = 0 === max ? 0 : 1 - min / max; if (max === min) { H = 0 } else { switch (max) { case r: H = 60 * ((g - b) / delta); if (g < b) { H += 360 } break; case g: H = 60 * ((b - r) / delta) + 120; break; case b: H = 60 * ((r - g) / delta) + 240 } } S *= 100; V *= 100 / 255; return { h: Math.round(H), s: Math.round(S), v: Math.round(V) } } function hsvToRgb(h, s, v) { var vDec, vInc, vMin, index, a, r, g, b; index = Math.floor(h % 360 / 60); vMin = (100 - s) * v / 100; a = (v - vMin) * (h % 60 / 60); vInc = vMin + a; vDec = v - a; switch (index) { case 0: r = v; g = vInc; b = vMin; break; case 1: r = vDec; g = v; b = vMin; break; case 2: r = vMin; g = v; b = vInc; break; case 3: r = vMin; g = vDec; b = v; break; case 4: r = vInc; g = vMin; b = v; break; case 5: r = v; g = vMin; b = vDec } return [Math.round(2.55 * r), Math.round(2.55 * g), Math.round(2.55 * b)] } function calculateHue(r, g, b, delta) { var max = Math.max(r, g, b); switch (max) { case r: return (g - b) / delta + (g < b ? 6 : 0); case g: return (b - r) / delta + 2; case b: return (r - g) / delta + 4 } } function toHslFromRgb(r, g, b) { r = convertTo01Bounds(r, 255); g = convertTo01Bounds(g, 255); b = convertTo01Bounds(b, 255); var h, s, max = Math.max(r, g, b), min = Math.min(r, g, b), maxMinSum = max + min, l = maxMinSum / 2; if (max === min) { h = s = 0 } else { var delta = max - min; if (l > .5) { s = delta / (2 - maxMinSum) } else { s = delta / maxMinSum } h = calculateHue(r, g, b, delta); h /= 6 } return { h: _round(360 * h), s: _round(100 * s), l: _round(100 * l) } } function makeColorTint(colorPart, h) { var colorTint = h; if ("r" === colorPart) { colorTint = h + 1 / 3 } if ("b" === colorPart) { colorTint = h - 1 / 3 } return colorTint } function modifyColorTint(colorTint) { if (colorTint < 0) { colorTint += 1 } if (colorTint > 1) { colorTint -= 1 } return colorTint } function hueToRgb(p, q, colorTint) { colorTint = modifyColorTint(colorTint); if (colorTint < 1 / 6) { return p + 6 * (q - p) * colorTint } if (colorTint < .5) { return q } if (colorTint < 2 / 3) { return p + (q - p) * (2 / 3 - colorTint) * 6 } return p } function hslToRgb(h, s, l) { var r, g, b; h = convertTo01Bounds(h, 360); s = convertTo01Bounds(s, 100); l = convertTo01Bounds(l, 100); if (0 === s) { r = g = b = l } else { var q = l < .5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q; r = hueToRgb(p, q, makeColorTint("r", h)); g = hueToRgb(p, q, makeColorTint("g", h)); b = hueToRgb(p, q, makeColorTint("b", h)) } return [_round(255 * r), _round(255 * g), _round(255 * b)] } function convertTo01Bounds(n, max) { n = Math.min(max, Math.max(0, parseFloat(n))); if (Math.abs(n - max) < 1e-6) { return 1 } return n % max / parseFloat(max) } function isIntegerBetweenMinAndMax(number, min, max) { min = min || 0; max = max || 255; if (number % 1 !== 0 || number < min || number > max || "number" !== typeof number || isNaN(number)) { return false } return true } var _round = Math.round; Color.prototype = { constructor: Color, highlight: function(step) { step = step || 10; return this.alter(step).toHex() }, darken: function(step) { step = step || 10; return this.alter(-step).toHex() }, alter: function(step) { var result = new Color; result.r = normalize(this.r + step); result.g = normalize(this.g + step); result.b = normalize(this.b + step); return result }, blend: function(blendColor, opacity) { var other = blendColor instanceof Color ? blendColor : new Color(blendColor), result = new Color; result.r = normalize(_round(this.r * (1 - opacity) + other.r * opacity)); result.g = normalize(_round(this.g * (1 - opacity) + other.g * opacity)); result.b = normalize(_round(this.b * (1 - opacity) + other.b * opacity)); return result }, toHex: function() { return toHexFromRgb(this.r, this.g, this.b) }, getPureColor: function() { var rgb = hsvToRgb(this.hsv.h, 100, 100); return new Color("rgb(" + rgb.join(",") + ")") }, isValidHex: function(hex) { return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex) }, isValidRGB: function(r, g, b) { if (!isIntegerBetweenMinAndMax(r) || !isIntegerBetweenMinAndMax(g) || !isIntegerBetweenMinAndMax(b)) { return false } return true }, isValidAlpha: function(a) { if (isNaN(a) || a < 0 || a > 1 || "number" !== typeof a) { return false } return true }, colorIsInvalid: false }; module.exports = Color }, /*!************************************!*\ !*** ./js/core/utils/inflector.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var _normalize = function(text) { if (void 0 === text || null === text) { return "" } return String(text) }; var _upperCaseFirst = function(text) { return _normalize(text).charAt(0).toUpperCase() + text.substr(1) }; var _chop = function(text) { return _normalize(text).replace(/([a-z\d])([A-Z])/g, "$1 $2").split(/[\s_-]+/) }; var dasherize = function(text) { return $.map(_chop(text), function(p) { return p.toLowerCase() }).join("-") }; var underscore = function(text) { return dasherize(text).replace(/-/g, "_") }; var camelize = function(text, upperFirst) { return $.map(_chop(text), function(p, i) { p = p.toLowerCase(); if (upperFirst || i > 0) { p = _upperCaseFirst(p) } return p }).join("") }; var humanize = function(text) { return _upperCaseFirst(dasherize(text).replace(/-/g, " ")) }; var titleize = function(text) { return $.map(_chop(text), function(p) { return _upperCaseFirst(p.toLowerCase()) }).join(" ") }; var captionize = function(name) { var i, char, captionList = [], isPrevCharNewWord = false, isNewWord = false; for (i = 0; i < name.length; i++) { char = name.charAt(i); isNewWord = char === char.toUpperCase() || char in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; if ("_" === char || "." === char) { char = " "; isNewWord = true } else { if (0 === i) { char = char.toUpperCase(); isNewWord = true } else { if (!isPrevCharNewWord && isNewWord) { if (captionList.length > 0) { captionList.push(" ") } } } } captionList.push(char); isPrevCharNewWord = isNewWord } return captionList.join("") }; exports.dasherize = dasherize; exports.camelize = camelize; exports.humanize = humanize; exports.titleize = titleize; exports.underscore = underscore; exports.captionize = captionize }, /*!*******************************************!*\ !*** ./js/client_exporter/pdf_creator.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), VERSION = __webpack_require__( /*! ../core/version */ 19), imageCreator = __webpack_require__( /*! ./image_creator */ 37).imageCreator, isFunction = __webpack_require__( /*! ../core/utils/common */ 14).isFunction, extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when, mainPageTemplate = "%PDF-1.3\r\n2 0 obj\r\n<</ProcSet[/PDF/ImageB/ImageC/ImageI]/XObject<</I0 5 0 R>>>>\r\nendobj\r\n4 0 obj\r\n<</Type/Pages/Kids[1 0 R]/Count 1>>\r\nendobj\r\n7 0 obj\r\n<</OpenAction[1 0 R /FitH null]/Type/Catalog/Pages 4 0 R/PageLayout/OneColumn>>\r\nendobj\r\n1 0 obj\r\n<</Type/Page/Resources 2 0 R/MediaBox[0 0 _width_ _height_]/Contents 3 0 R/Parent 4 0 R>>\r\nendobj\r\n", contentTemplate = "3 0 obj\r\n<</Length 52>>stream\r\n0.20 w\n0 G\nq _width_ 0 0 _height_ 0.00 0.00 cm /I0 Do Q\r\nendstream\r\nendobj\r\n", infoTemplate = "6 0 obj\r\n<</CreationDate _date_/Producer(DevExtreme _version_)>>\r\nendobj\r\n", imageStartTemplate = "5 0 obj\r\n<</Type/XObject/Subtype/Image/Width _width_/Height _height_/ColorSpace/DeviceRGB/BitsPerComponent 8/Filter/DCTDecode/Length _length_>>stream\r\n", imageEndTemplate = "\r\nendstream\r\nendobj\r\n", trailerTemplate = "trailer\r\n<<\r\n/Size 8\r\n/Root 7 0 R\r\n/Info 6 0 R\r\n>>\r\nstartxref\r\n_length_\r\n%%EOF", xrefTemplate = "xref\r\n0 8\r\n0000000000 65535 f\r\n0000000241 00000 n\r\n0000000010 00000 n\r\n_main_ 00000 n\r\n0000000089 00000 n\r\n_image_ 00000 n\r\n_info_ 00000 n\r\n0000000143 00000 n\r\n", DEFAULT_MARGIN_X = 60, DEFAULT_MARGIN_Y = 40; var pad = function(str, len) { return str.length < len ? pad("0" + str, len) : str }; var composePdfString = function(imageString, options, curDate) { var width = options.width + DEFAULT_MARGIN_X, height = options.height + DEFAULT_MARGIN_Y, widthPt = (.75 * width).toFixed(2), heightPt = (.75 * height).toFixed(2); var mainPage = mainPageTemplate.replace("_width_", widthPt).replace("_height_", heightPt), content = contentTemplate.replace("_width_", widthPt).replace("_height_", heightPt), info = infoTemplate.replace("_date_", curDate).replace("_version_", VERSION), image = imageStartTemplate.replace("_width_", width).replace("_height_", height).replace("_length_", imageString.length) + imageString + imageEndTemplate, xref = getXref(mainPage.length, content.length, info.length); var mainContent = mainPage + content + info + image, trailer = trailerTemplate.replace("_length_", mainContent.length); return mainContent + xref + trailer }; var getXref = function(mainPageLength, contentLength, infoLength) { return xrefTemplate.replace("_main_", pad(mainPageLength + "", 10)).replace("_info_", pad(mainPageLength + contentLength + "", 10)).replace("_image_", pad(mainPageLength + contentLength + infoLength + "", 10)) }; var getCurDate = function() { return new Date }; var getBlob = function(binaryData) { var i = 0, dataArray = new Uint8Array(binaryData.length); for (; i < binaryData.length; i++) { dataArray[i] = binaryData.charCodeAt(i) } return new Blob([dataArray.buffer], { type: "application/pdf" }) }; var getBase64 = function(binaryData) { return window.btoa(binaryData) }; exports.getData = function(data, options, callback) { var imageData = imageCreator.getImageData(data, extend({}, options, { format: "jpeg" })), blob = $.Deferred(); blob.done(callback); when(imageData).done(function(imageString) { var binaryData = composePdfString(imageString, options, getCurDate()), pdfData = isFunction(window.Blob) ? getBlob(binaryData) : getBase64(binaryData); blob.resolve(pdfData) }) }; exports.__tests = { set_composePdfString: function(func) { exports.__tests.composePdfString = composePdfString; composePdfString = func }, restore_composePdfString: function(func) { if (exports.__tests.composePdfString) { composePdfString = exports.__tests.composePdfString; exports.__tests.composePdfString = null } }, set_getCurDate: function(func) { exports.__tests.getCurDate = getCurDate; getCurDate = func }, restore_getCurDate: function(func) { if (exports.__tests.getCurDate) { getCurDate = exports.__tests.getCurDate; exports.__tests.getCurDate = null } }, set_getBlob: function(func) { exports.__tests.getBlob = getBlob; getBlob = func }, restore_getBlob: function(func) { if (exports.__tests.getBlob) { getBlob = exports.__tests.getBlob; exports.__tests.getBlob = null } }, set_getBase64: function(func) { exports.__tests.getBase64 = getBase64; getBase64 = func }, restore_getBase64: function(func) { if (exports.__tests.getBase64) { getBase64 = exports.__tests.getBase64; exports.__tests.getBase64 = null } } } }, /*!*******************************************!*\ !*** ./js/client_exporter/svg_creator.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), getSvgMarkup = __webpack_require__( /*! ../core/utils/svg */ 42).getSvgMarkup, when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when; exports.svgCreator = { _markup: "", _imageArray: {}, _imageDeferreds: [], _getBinaryFile: function(src, callback) { var xhr = new XMLHttpRequest; xhr.onreadystatechange = function() { if (xhr.readyState === xhr.DONE) { if (200 === xhr.status && xhr.response) { callback(xhr.response) } else { callback(false) } } }; xhr.open("GET", src, true); xhr.responseType = "arraybuffer"; xhr.send() }, _loadImages: function() { var that = this; $.each(that._imageArray, function(src) { var deferred = new $.Deferred; that._imageDeferreds.push(deferred); that._getBinaryFile(src, function(response) { if (!response) { delete that._imageArray[src]; deferred.resolve(); return } var i, binary = "", bytes = new Uint8Array(response), length = bytes.byteLength; for (i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]) } that._imageArray[src] = "data:image/png;base64," + btoa(binary); deferred.resolve() }) }) }, _parseImages: function(element) { var href, that = this; if ("image" === element.tagName) { href = $(element).attr("xlink:href"); if (!that._imageArray[href]) { that._imageArray[href] = "" } } $.each(element.childNodes, function(_, element) { that._parseImages(element) }) }, _prepareImages: function(svgElem) { this._parseImages(svgElem); this._loadImages(); return when.apply($, this._imageDeferreds) }, getData: function(data, options) { var markup, that = this, xmlVersion = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>', blob = $.Deferred(), parser = new DOMParser, elem = parser.parseFromString(data, "image/svg+xml"), svgElem = elem.childNodes[0], $svgObject = $(svgElem); $svgObject.css("background-color", options.backgroundColor); markup = xmlVersion + getSvgMarkup($svgObject.get(0)); that._prepareImages(svgElem).done(function() { $.each(that._imageArray, function(href, dataURI) { markup = markup.split(href).join(dataURI) }); blob.resolve(commonUtils.isFunction(window.Blob) ? that._getBlob(markup) : that._getBase64(markup)) }); return blob }, _getBlob: function(markup) { return new Blob([markup], { type: "image/svg+xml" }) }, _getBase64: function(markup) { return window.btoa(markup) } }; exports.getData = function(data, options, callback) { exports.svgCreator.getData(data, options).done(callback) } }, /*!******************************!*\ !*** ./js/core/utils/svg.js ***! \******************************/ function(module, exports) { function getMarkup(element) { var temp = document.createElement("div"); temp.appendChild(element.cloneNode(true)); return temp.innerHTML } function fixIENamespaces(markup) { var first = true; markup = markup.replace(/xmlns="[\s\S]*?"/gi, function(match) { if (!first) { return "" } first = false; return match }); return markup.replace(/xmlns:NS1="[\s\S]*?"/gi, "").replace(/NS1:xmlns:xlink="([\s\S]*?)"/gi, 'xmlns:xlink="$1"') } function decodeHtmlEntities(markup) { return markup.replace(/"/gi, """).replace(/&/gi, "&").replace(/'/gi, "'").replace(/</gi, "<").replace(/>/gi, ">").replace(/ /gi, " ").replace(/­/gi, "­") } exports.getSvgMarkup = function(element) { return fixIENamespaces(decodeHtmlEntities(getMarkup(element))) } }, /*!**********************************!*\ !*** ./js/core/dom_component.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), extend = __webpack_require__( /*! ./utils/extend */ 11).extend, config = __webpack_require__( /*! ./config */ 15), errors = __webpack_require__( /*! ./errors */ 7), windowResizeCallbacks = __webpack_require__( /*! ./utils/window */ 44).resizeCallbacks, commonUtils = __webpack_require__( /*! ./utils/common */ 14), inArray = __webpack_require__( /*! ./utils/array */ 26).inArray, publicComponentUtils = __webpack_require__( /*! ./utils/public_component */ 45), Component = __webpack_require__( /*! ./component */ 48), abstract = Component.abstract; var RTL_DIRECTION_CLASS = "dx-rtl", VISIBILITY_CHANGE_CLASS = "dx-visibility-change-handler", VISIBILITY_CHANGE_EVENTNAMESPACE = "VisibilityChange"; var DOMComponent = Component.inherit({ _getDefaultOptions: function() { return extend(this.callBase(), { width: void 0, height: void 0, rtlEnabled: config().rtlEnabled, elementAttr: {}, disabled: false, integrationOptions: {} }) }, ctor: function(element, options) { this._$element = $(element); publicComponentUtils.attachInstanceToElement(this._$element, this, this._dispose); this.callBase(options) }, _visibilityChanged: abstract, _dimensionChanged: abstract, _init: function() { this.callBase(); this._attachWindowResizeCallback() }, _setOptionsByDevice: function(instanceCustomRules) { this.callBase([].concat(this.constructor._classCustomRules || [], instanceCustomRules || [])) }, _isInitialOptionValue: function(name) { var isCustomOption = this.constructor._classCustomRules && this._convertRulesToOptions(this.constructor._classCustomRules).hasOwnProperty(name); return !isCustomOption && this.callBase(name) }, _attachWindowResizeCallback: function() { if (this._isDimensionChangeSupported()) { var windowResizeCallBack = this._windowResizeCallBack = this._dimensionChanged.bind(this); windowResizeCallbacks.add(windowResizeCallBack) } }, _isDimensionChangeSupported: function() { return this._dimensionChanged !== abstract }, _render: function() { this._renderElementAttributes(); this._toggleRTLDirection(this.option("rtlEnabled")); this._renderVisibilityChange(); this._renderDimensions() }, _renderElementAttributes: function() { var attributes = extend({}, this.option("elementAttr")), classNames = attributes.class; delete attributes.class; this.element().attr(attributes).addClass(classNames) }, _renderVisibilityChange: function() { if (this._isDimensionChangeSupported()) { this._attachDimensionChangeHandlers() } if (!this._isVisibilityChangeSupported()) { return } this.element().addClass(VISIBILITY_CHANGE_CLASS); this._attachVisibilityChangeHandlers() }, _renderDimensions: function() { var width = this.option("width"), height = this.option("height"), $element = this.element(); $element.outerWidth(width); $element.outerHeight(height) }, _attachDimensionChangeHandlers: function() { var that = this; var resizeEventName = "dxresize." + this.NAME + VISIBILITY_CHANGE_EVENTNAMESPACE; that.element().off(resizeEventName).on(resizeEventName, function() { that._dimensionChanged() }) }, _attachVisibilityChangeHandlers: function() { var that = this; var hidingEventName = "dxhiding." + this.NAME + VISIBILITY_CHANGE_EVENTNAMESPACE; var shownEventName = "dxshown." + this.NAME + VISIBILITY_CHANGE_EVENTNAMESPACE; that._isHidden = !that._isVisible(); that.element().off(hidingEventName).on(hidingEventName, function() { that._checkVisibilityChanged("hiding") }).off(shownEventName).on(shownEventName, function() { that._checkVisibilityChanged("shown") }) }, _isVisible: function() { return this.element().is(":visible") }, _checkVisibilityChanged: function(event) { if ("hiding" === event && this._isVisible() && !this._isHidden) { this._visibilityChanged(false); this._isHidden = true } else { if ("shown" === event && this._isVisible() && this._isHidden) { this._isHidden = false; this._visibilityChanged(true) } } }, _isVisibilityChangeSupported: function() { return this._visibilityChanged !== abstract }, _clean: commonUtils.noop, _modelByElement: function() { var modelByElement = this.option("modelByElement") || commonUtils.noop; return modelByElement(this.element()) }, _invalidate: function() { if (!this._updateLockCount) { throw errors.Error("E0007") } this._requireRefresh = true }, _refresh: function() { this._clean(); this._render() }, _dispose: function() { this.callBase(); this._clean(); this._detachWindowResizeCallback() }, _detachWindowResizeCallback: function() { if (this._isDimensionChangeSupported()) { windowResizeCallbacks.remove(this._windowResizeCallBack) } }, _toggleRTLDirection: function(rtl) { this.element().toggleClass(RTL_DIRECTION_CLASS, rtl) }, _createComponent: function(element, component, config) { var that = this; config = config || {}; var synchronizableOptions = commonUtils.grep(["rtlEnabled", "disabled"], function(value) { return !(value in config) }); var nestedComponentOptions = that.option("nestedComponentOptions") || commonUtils.noop; that._extendConfig(config, extend({ integrationOptions: this.option("integrationOptions"), rtlEnabled: this.option("rtlEnabled"), disabled: this.option("disabled") }, nestedComponentOptions(this))); var instance; if (commonUtils.isString(component)) { var $element = $(element)[component](config); instance = $element[component]("instance") } else { if (element) { instance = component.getInstance(element); if (instance) { instance.option(config) } else { instance = new component(element, config) } } } if (instance) { var optionChangedHandler = function(args) { if (inArray(args.name, synchronizableOptions) >= 0) { instance.option(args.name, args.value) } }; that.on("optionChanged", optionChangedHandler); instance.on("disposing", function() { that.off("optionChanged", optionChangedHandler) }) } return instance }, _extendConfig: function(config, extendConfig) { $.each(extendConfig, function(key, value) { config[key] = config.hasOwnProperty(key) ? config[key] : value }) }, _defaultActionConfig: function() { return extend(this.callBase(), { context: this._modelByElement(this.element()) }) }, _defaultActionArgs: function() { var element = this.element(), model = this._modelByElement(this.element()); return extend(this.callBase(), { element: element, model: model }) }, _optionChanged: function(args) { switch (args.name) { case "width": case "height": this._renderDimensions(); break; case "rtlEnabled": case "elementAttr": this._invalidate(); break; case "disabled": case "integrationOptions": break; default: this.callBase(args) } }, endUpdate: function() { var requireRender = !this._initializing && !this._initialized; this.callBase.apply(this, arguments); if (!this._updateLockCount) { if (requireRender) { this._render() } else { if (this._requireRefresh) { this._requireRefresh = false; this._refresh() } } } }, element: function() { return this._$element } }); DOMComponent.getInstance = function($element) { return publicComponentUtils.getInstanceByElement($($element), this) }; DOMComponent.defaultOptions = function(rule) { this._classCustomRules = this._classCustomRules || []; this._classCustomRules.push(rule) }; module.exports = DOMComponent }, /*!*********************************!*\ !*** ./js/core/utils/window.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var resizeCallbacks = function() { var prevSize, callbacks = $.Callbacks(), jqWindow = $(window), resizeEventHandlerAttached = false, originalCallbacksAdd = callbacks.add, originalCallbacksRemove = callbacks.remove; var formatSize = function() { return { width: jqWindow.width(), height: jqWindow.height() } }; var handleResize = function() { var now = formatSize(); if (now.width === prevSize.width && now.height === prevSize.height) { return } var changedDimension; if (now.width === prevSize.width) { changedDimension = "height" } if (now.height === prevSize.height) { changedDimension = "width" } prevSize = now; setTimeout(function() { callbacks.fire(changedDimension) }) }; prevSize = formatSize(); callbacks.add = function() { var result = originalCallbacksAdd.apply(callbacks, arguments); if (!resizeEventHandlerAttached && callbacks.has()) { jqWindow.on("resize", handleResize); resizeEventHandlerAttached = true } return result }; callbacks.remove = function() { var result = originalCallbacksRemove.apply(callbacks, arguments); if (!callbacks.has() && resizeEventHandlerAttached) { jqWindow.off("resize", handleResize); resizeEventHandlerAttached = false } return result }; return callbacks }(); var defaultScreenFactorFunc = function(width) { if (width < 768) { return "xs" } else { if (width < 992) { return "sm" } else { if (width < 1200) { return "md" } else { return "lg" } } } }; var getCurrentScreenFactor = function(screenFactorCallback) { var screenFactorFunc = screenFactorCallback || defaultScreenFactorFunc; return screenFactorFunc($(window).width()) }; exports.resizeCallbacks = resizeCallbacks; exports.defaultScreenFactorFunc = defaultScreenFactorFunc; exports.getCurrentScreenFactor = getCurrentScreenFactor }, /*!*******************************************!*\ !*** ./js/core/utils/public_component.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), WeakMap = __webpack_require__( /*! ../polyfills/weak_map */ 46), commonUtils = __webpack_require__( /*! ./common */ 14), removeEvent = __webpack_require__( /*! ../remove_event */ 47); var COMPONENT_NAMES_DATA_KEY = "dxComponents", ANONYMOUS_COMPONENT_DATA_KEY = "dxPrivateComponent"; var componentNames = new WeakMap, nextAnonymousComponent = 0; var getName = exports.name = function(componentClass, newName) { if (commonUtils.isDefined(newName)) { componentNames.set(componentClass, newName); return } if (!componentNames.has(componentClass)) { var generatedName = ANONYMOUS_COMPONENT_DATA_KEY + nextAnonymousComponent++; componentNames.set(componentClass, generatedName); return generatedName } return componentNames.get(componentClass) }; exports.attachInstanceToElement = function($element, componentInstance, disposeFn) { var data = $.data($element.get(0)), name = getName(componentInstance.constructor); data[name] = componentInstance; if (disposeFn) { $element.one(removeEvent, function() { disposeFn.call(componentInstance) }) } if (!data[COMPONENT_NAMES_DATA_KEY]) { data[COMPONENT_NAMES_DATA_KEY] = [] } data[COMPONENT_NAMES_DATA_KEY].push(name) }; exports.getInstanceByElement = function($element, componentClass) { var name = getName(componentClass); return $.data($element.get(0), name) } }, /*!***************************************!*\ !*** ./js/core/polyfills/weak_map.js ***! \***************************************/ function(module, exports, __webpack_require__) { var inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, WeakMap = window.WeakMap; if (!WeakMap) { WeakMap = function() { var keys = [], values = []; this.set = function(key, value) { var index = inArray(key, keys); if (index === -1) { keys.push(key); values.push(value) } else { values[index] = value } }; this.get = function(key) { var index = inArray(key, keys); if (index === -1) { return } return values[index] }; this.has = function(key) { var index = inArray(key, keys); if (index === -1) { return false } return true } } } module.exports = WeakMap }, /*!*********************************!*\ !*** ./js/core/remove_event.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), jQuery = __webpack_require__( /*! jquery */ 10), cleanData = jQuery.cleanData, specialEvents = $.event.special; var eventName = "dxremove", eventPropName = "dxRemoveEvent"; jQuery.cleanData = function(elements) { elements = [].slice.call(elements); for (var i = 0; i < elements.length; i++) { var $element = $(elements[i]); if ($element.prop(eventPropName)) { $element.removeProp(eventPropName); $element.triggerHandler(eventName) } } return cleanData(elements) }; specialEvents[eventName] = { noBubble: true, setup: function() { $(this).prop(eventPropName, true) } }; module.exports = eventName }, /*!******************************!*\ !*** ./js/core/component.js ***! \******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Config = __webpack_require__( /*! ./config */ 15), extend = __webpack_require__( /*! ./utils/extend */ 11).extend, Class = __webpack_require__( /*! ./class */ 25), Action = __webpack_require__( /*! ./action */ 49), errors = __webpack_require__( /*! ./errors */ 7), coreDataUtils = __webpack_require__( /*! ./utils/data */ 50), commonUtils = __webpack_require__( /*! ./utils/common */ 14), typeUtils = __webpack_require__( /*! ./utils/type */ 12), EventsMixin = __webpack_require__( /*! ./events_mixin */ 51), publicComponentUtils = __webpack_require__( /*! ./utils/public_component */ 45), devices = __webpack_require__( /*! ./devices */ 53), isFunction = commonUtils.isFunction, noop = commonUtils.noop; var cachedGetters = {}; var cachedSetters = {}; var Component = Class.inherit({ _setDeprecatedOptions: function() { this._deprecatedOptions = {} }, _getDeprecatedOptions: function() { return this._deprecatedOptions }, _getOptionAliasesByName: function(optionName) { return $.map(this._deprecatedOptions, function(deprecate, aliasName) { return optionName === deprecate.alias ? aliasName : void 0 }) }, _getDefaultOptions: function() { return { onInitialized: null, onOptionChanged: null, onDisposing: null, defaultOptionsRules: null } }, _setDefaultOptions: function() { this._options = this._getDefaultOptions() }, _defaultOptionsRules: function() { return [] }, _setOptionsByDevice: function(customRules) { var rules = this._defaultOptionsRules(); if (Array.isArray(customRules)) { rules = rules.concat(customRules) } var rulesOptions = this._convertRulesToOptions(rules); extend(true, this._options, rulesOptions); for (var fieldName in this._optionsByReference) { if (rulesOptions.hasOwnProperty(fieldName)) { this._options[fieldName] = rulesOptions[fieldName] } } }, _convertRulesToOptions: function(rules) { var options = {}; var currentDevice = devices.current(); var deviceMatch = function(device, filter) { filter = $.makeArray(filter); return 1 === filter.length && typeUtils.isEmptyObject(filter[0]) || commonUtils.findBestMatches(device, filter).length > 0 }; for (var i = 0; i < rules.length; i++) { var match, rule = rules[i], deviceFilter = rule.device || {}; if (isFunction(deviceFilter)) { match = deviceFilter(currentDevice) } else { match = deviceMatch(currentDevice, deviceFilter) } if (match) { extend(options, rule.options) } } return options }, _isInitialOptionValue: function(name) { var optionValue = this.option(name), initialOptionValue = this.initialOption(name), isInitialOption = isFunction(optionValue) && isFunction(initialOptionValue) ? optionValue.toString() === initialOptionValue.toString() : commonUtils.equalByValue(optionValue, initialOptionValue); return isInitialOption }, _setOptionsByReference: function() { this._optionsByReference = {} }, _getOptionsByReference: function() { return this._optionsByReference }, ctor: function(options) { this.NAME = publicComponentUtils.name(this.constructor); options = options || {}; if (options.eventsStrategy) { this.setEventsStrategy(options.eventsStrategy) } this._options = {}; this._updateLockCount = 0; this._optionChangedCallbacks = options._optionChangedCallbacks || $.Callbacks(); this._disposingCallbacks = options._disposingCallbacks || $.Callbacks(); this.beginUpdate(); try { this._suppressDeprecatedWarnings(); this._setOptionsByReference(); this._setDeprecatedOptions(); this._setDefaultOptions(); if (options && options.onInitializing) { options.onInitializing.apply(this, [options]) } this._setOptionsByDevice(options.defaultOptionsRules); this._resumeDeprecatedWarnings(); this._initOptions(options) } finally { this.endUpdate() } }, _initOptions: function(options) { this.option(options) }, _optionValuesEqual: function(name, oldValue, newValue) { oldValue = coreDataUtils.toComparable(oldValue, true); newValue = coreDataUtils.toComparable(newValue, true); if (oldValue && newValue && oldValue.jquery && newValue.jquery) { return newValue.is(oldValue) } var oldValueIsNaN = oldValue !== oldValue, newValueIsNaN = newValue !== newValue; if (oldValueIsNaN && newValueIsNaN) { return true } if (null === oldValue || "object" !== typeof oldValue) { return oldValue === newValue } return false }, _init: function() { this._createOptionChangedAction(); this.on("disposing", function(args) { this._disposingCallbacks.fireWith(this, [args]) }.bind(this)) }, _createOptionChangedAction: function() { this._optionChangedAction = this._createActionByOption("onOptionChanged", { excludeValidators: ["disabled", "readOnly", "designMode"] }) }, _createDisposingAction: function() { this._disposingAction = this._createActionByOption("onDisposing", { excludeValidators: ["disabled", "readOnly", "designMode"] }) }, _optionChanged: function(args) { switch (args.name) { case "onDisposing": case "onInitialized": break; case "onOptionChanged": this._createOptionChangedAction(); break; case "defaultOptionsRules": } }, _dispose: function() { this._optionChangedCallbacks.empty(); this._createDisposingAction(); this._disposingAction(); this._disposeEvents(); this._disposed = true }, instance: function() { return this }, beginUpdate: function() { this._updateLockCount++ }, endUpdate: function() { this._updateLockCount = Math.max(this._updateLockCount - 1, 0); if (!this._updateLockCount) { if (!this._initializing && !this._initialized) { this._initializing = true; try { this._init() } finally { this._initializing = false; this._updateLockCount++; this._createActionByOption("onInitialized", { excludeValidators: ["disabled", "readOnly", "designMode"] })(); this._updateLockCount--; this._initialized = true } } } }, _logWarningIfDeprecated: function(option) { var info = this._deprecatedOptions[option]; if (info && !this._deprecatedOptionsSuppressed) { this._logDeprecatedWarning(option, info) } }, _logDeprecatedWarningCount: 0, _logDeprecatedWarning: function(option, info) { var message = info.message || "Use the '" + info.alias + "' option instead"; errors.log("W0001", this.NAME, option, info.since, message); ++this._logDeprecatedWarningCount }, _suppressDeprecatedWarnings: function() { this._deprecatedOptionsSuppressed = true }, _resumeDeprecatedWarnings: function() { this._deprecatedOptionsSuppressed = false }, _optionChanging: noop, _notifyOptionChanged: function(option, value, previousValue) { var that = this; if (this._initialized) { var optionNames = [option].concat(that._getOptionAliasesByName(option)); for (var i = 0; i < optionNames.length; i++) { var name = optionNames[i], args = { name: name.split(/[.\[]/)[0], fullName: name, value: value, previousValue: previousValue }; that._optionChangedCallbacks.fireWith(that, [extend(that._defaultActionArgs(), args)]); that._optionChangedAction(extend({}, args)); if (!that._disposed) { that._optionChanged(args) } } } }, initialOption: function(optionName) { var currentOptions, currentInitialized = this._initialized; if (!this._initialOptions) { currentOptions = this._options; this._options = {}; this._initialized = false; this._setDefaultOptions(); this._setOptionsByDevice(currentOptions.defaultOptionsRules); this._initialOptions = this._options; this._options = currentOptions; this._initialized = currentInitialized } return this._initialOptions[optionName] }, _defaultActionConfig: function() { return { context: this, component: this } }, _defaultActionArgs: function() { return { component: this } }, _createAction: function(actionSource, config) { var action, that = this; return function(e) { if (!arguments.length) { e = {} } if (e instanceof $.Event) { throw Error("Action must be executed with jQuery.Event like action({ jQueryEvent: event })") } if (!typeUtils.isPlainObject(e)) { e = { actionValue: e } } action = action || new Action(actionSource, extend(config, that._defaultActionConfig())); return action.execute.call(action, extend(e, that._defaultActionArgs())) } }, _createActionByOption: function(optionName, config) { var action, eventName, actionFunc, that = this; var result = function() { if (!eventName) { config = config || {}; if ("string" !== typeof optionName) { throw errors.Error("E0008") } if (0 === optionName.indexOf("on")) { eventName = that._getEventName(optionName) } if (0 !== optionName.indexOf("on")) { throw Error("The '" + optionName + "' option name should start with 'on' prefix") } actionFunc = that.option(optionName) } if (!action && !actionFunc && !config.beforeExecute && !config.afterExecute && !that.hasEvent(eventName)) { return } if (!action) { var beforeExecute = config.beforeExecute; config.beforeExecute = function(args) { that.fireEvent(eventName, args.args); beforeExecute && beforeExecute.apply(that, arguments) }; that._suppressDeprecatedWarnings(); action = that._createAction(actionFunc, config); that._resumeDeprecatedWarnings() } if (Config().wrapActionsBeforeExecute) { var beforeActionExecute = that.option("beforeActionExecute") || noop; action = beforeActionExecute(that, action, config) || action } return action.apply(that, arguments) }; if (!Config().wrapActionsBeforeExecute) { var onActionCreated = that.option("onActionCreated") || noop; result = onActionCreated(that, result, config) || result } return result }, _getEventName: function(actionName) { return actionName.charAt(2).toLowerCase() + actionName.substr(3) }, hasActionSubscription: function(actionName) { return !!this.option(actionName) || this.hasEvent(this._getEventName(actionName)) }, isOptionDeprecated: function(name) { var deprecatedOptions = this._getDeprecatedOptions(); return deprecatedOptions.hasOwnProperty(name) }, option: function() { var normalizeOptionName = function(that, name) { var deprecate; if (name) { if (!that._cachedDeprecateNames) { that._cachedDeprecateNames = []; for (var optionName in that._deprecatedOptions) { that._cachedDeprecateNames.push(optionName) } } for (var i = 0; i < that._cachedDeprecateNames.length; i++) { if (that._cachedDeprecateNames[i] === name) { deprecate = that._deprecatedOptions[name]; break } } if (deprecate) { that._logWarningIfDeprecated(name); var alias = deprecate.alias; if (alias) { name = alias } } } return name }; var getPreviousName = function(fullName) { var splitNames = fullName.split("."); splitNames.pop(); return splitNames.join(".") }; var getFieldName = function(fullName) { var splitNames = fullName.split("."); return splitNames[splitNames.length - 1] }; var getOptionValue = function(options, name, unwrapObservables) { var getter = cachedGetters[name]; if (!getter) { getter = cachedGetters[name] = coreDataUtils.compileGetter(name) } return getter(options, { functionsAsIs: true, unwrapObservables: unwrapObservables }) }; var clearOptionsField = function(options, name) { delete options[name]; var previousFieldName = getPreviousName(name), fieldName = getFieldName(name), fieldObject = previousFieldName ? getOptionValue(options, previousFieldName, false) : options; if (fieldObject) { delete fieldObject[fieldName] } }; var setOptionsField = function(options, fullName, value) { var fieldObject, fieldName = ""; do { if (fieldName) { fieldName = "." + fieldName } fieldName = getFieldName(fullName) + fieldName; fullName = getPreviousName(fullName); fieldObject = fullName ? getOptionValue(options, fullName, false) : options } while (!fieldObject); fieldObject[fieldName] = value }; var normalizeOptionValue = function(that, options, name, value) { if (name) { var alias = normalizeOptionName(that, name); if (alias && alias !== name) { setOptionsField(options, alias, value); clearOptionsField(options, name) } } }; var prepareOption = function(that, options, name, value) { if (typeUtils.isPlainObject(value)) { for (var valueName in value) { prepareOption(that, options, name + "." + valueName, value[valueName]) } } normalizeOptionValue(that, options, name, value) }; var setOptionValue = function(that, name, value) { if (!cachedSetters[name]) { cachedSetters[name] = coreDataUtils.compileSetter(name) } var path = name.split(/[.\[]/); cachedSetters[name](that._options, value, { functionsAsIs: true, merge: !that._getOptionsByReference()[name], unwrapObservables: path.length > 1 && !!that._getOptionsByReference()[path[0]] }) }; var setOption = function(that, name, value) { var previousValue = getOptionValue(that._options, name, false); if (that._optionValuesEqual(name, previousValue, value)) { return } if (that._initialized) { that._optionChanging(name, previousValue, value) } setOptionValue(that, name, value); that._notifyOptionChanged(name, value, previousValue) }; return function(options, value) { var that = this, name = options; if (arguments.length < 2 && "object" !== commonUtils.type(name)) { name = normalizeOptionName(that, name); return getOptionValue(that._options, name) } if ("string" === typeof name) { options = {}; options[name] = value } that.beginUpdate(); try { var optionName; for (optionName in options) { prepareOption(that, options, optionName, options[optionName]) } for (optionName in options) { setOption(that, optionName, options[optionName]) } } finally { that.endUpdate() } } }() }).include(EventsMixin); module.exports = Component }, /*!***************************!*\ !*** ./js/core/action.js ***! \***************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), config = __webpack_require__( /*! ./config */ 15), commonUtils = __webpack_require__( /*! ./utils/common */ 14), typeUtils = __webpack_require__( /*! ./utils/type */ 12), Class = __webpack_require__( /*! ./class */ 25); var Action = Class.inherit({ ctor: function(action, config) { config = config || {}; this._action = action; this._context = config.context || window; this._beforeExecute = config.beforeExecute; this._afterExecute = config.afterExecute; this._component = config.component; this._validatingTargetName = config.validatingTargetName; var excludeValidators = this._excludeValidators = {}; if (config.excludeValidators) { for (var i = 0; i < config.excludeValidators.length; i++) { excludeValidators[config.excludeValidators[i]] = true } } }, execute: function() { var e = { action: this._action, args: Array.prototype.slice.call(arguments), context: this._context, component: this._component, validatingTargetName: this._validatingTargetName, cancel: false, handled: false }; var beforeExecute = this._beforeExecute, afterExecute = this._afterExecute; if (!this._validateAction(e)) { return } beforeExecute && beforeExecute.call(this._context, e); if (e.cancel) { return } var result = this._executeAction(e); var argsBag = e.args[0]; if (argsBag && argsBag.cancel) { return } afterExecute && afterExecute.call(this._context, e); return result }, _validateAction: function(e) { var excludeValidators = this._excludeValidators, executors = Action.executors; for (var name in executors) { if (!excludeValidators[name]) { var executor = executors[name]; if (executor.validate) { executor.validate(e) } if (e.cancel) { return false } } } return true }, _executeAction: function(e) { var result, executors = Action.executors; for (var name in executors) { var executor = executors[name]; if (executor.execute) { executor.execute(e) } if (e.handled) { result = e.result; break } } return result } }); Action.executors = {}; Action.registerExecutor = function(name, executor) { if (typeUtils.isPlainObject(name)) { $.each(name, Action.registerExecutor); return } Action.executors[name] = executor }; Action.unregisterExecutor = function() { var args = $.makeArray(arguments); $.each(args, function() { delete Action.executors[this] }) }; Action.registerExecutor({ undefined: { execute: function(e) { if (!e.action) { e.result = void 0; e.handled = true } } }, func: { execute: function(e) { if (commonUtils.isFunction(e.action)) { e.result = e.action.call(e.context, e.args[0]); e.handled = true } } } }); var createValidatorByTargetElement = function(condition) { return function(e) { if (!e.args.length) { return } var args = e.args[0], element = args[e.validatingTargetName] || args.element; if (element && condition(element)) { e.cancel = true } } }; Action.registerExecutor({ designMode: { validate: function(e) { if (config().designMode) { e.cancel = true } } }, disabled: { validate: createValidatorByTargetElement(function($target) { return $target.is(".dx-state-disabled, .dx-state-disabled *") }) }, readOnly: { validate: createValidatorByTargetElement(function($target) { return $target.is(".dx-state-readonly, .dx-state-readonly *") }) } }); module.exports = Action }, /*!*******************************!*\ !*** ./js/core/utils/data.js ***! \*******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), errors = __webpack_require__( /*! ../errors */ 7), Class = __webpack_require__( /*! ../class */ 25), objectUtils = __webpack_require__( /*! ./object */ 27), commonUtils = __webpack_require__( /*! ./common */ 14), typeUtils = __webpack_require__( /*! ./type */ 12), variableWrapper = __webpack_require__( /*! ./variable_wrapper */ 28), unwrapVariable = variableWrapper.unwrap, isWrapped = variableWrapper.isWrapped, assign = variableWrapper.assign; var bracketsToDots = function(expr) { return expr.replace(/\[/g, ".").replace(/\]/g, "") }; var readPropValue = function(obj, propName) { if ("this" === propName) { return obj } return obj[propName] }; var assignPropValue = function(obj, propName, value, options) { if ("this" === propName) { throw new errors.Error("E4016") } var propValue = obj[propName]; if (options.unwrapObservables && isWrapped(propValue)) { assign(propValue, value) } else { obj[propName] = value } }; var prepareOptions = function(options) { options = options || {}; options.unwrapObservables = void 0 !== options.unwrapObservables ? options.unwrapObservables : true; return options }; var unwrap = function(value, options) { return options.unwrapObservables ? unwrapVariable(value) : value }; var compileGetter = function(expr) { if (arguments.length > 1) { expr = $.makeArray(arguments) } if (!expr || "this" === expr) { return function(obj) { return obj } } if ("string" === typeof expr) { expr = bracketsToDots(expr); var path = expr.split("."); return function(obj, options) { options = prepareOptions(options); var functionAsIs = options.functionsAsIs, current = unwrap(obj, options); for (var i = 0; i < path.length; i++) { if (!current) { break } var next = unwrap(current[path[i]], options); if (!functionAsIs && commonUtils.isFunction(next)) { next = next.call(current) } current = next } return current } } if (Array.isArray(expr)) { return combineGetters(expr) } if (commonUtils.isFunction(expr)) { return expr } }; var combineGetters = function(getters) { var compiledGetters = {}; for (var i = 0, l = getters.length; i < l; i++) { var getter = getters[i]; compiledGetters[getter] = compileGetter(getter) } return function(obj, options) { var result; $.each(compiledGetters, function(name) { var current, path, last, i, value = this(obj, options); if (void 0 === value) { return } current = result || (result = {}); path = name.split("."); last = path.length - 1; for (i = 0; i < last; i++) { current = current[path[i]] = {} } current[path[i]] = value }); return result } }; var compileSetter = function(expr) { expr = expr || "this"; expr = bracketsToDots(expr); var pos = expr.lastIndexOf("."), targetGetter = compileGetter(expr.substr(0, pos)), targetPropName = expr.substr(1 + pos); return function(obj, value, options) { options = prepareOptions(options); var target = targetGetter(obj, { functionsAsIs: options.functionsAsIs, unwrapObservables: options.unwrapObservables }), prevTargetValue = readPropValue(target, targetPropName); if (!options.functionsAsIs && commonUtils.isFunction(prevTargetValue) && !isWrapped(prevTargetValue)) { target[targetPropName](value) } else { prevTargetValue = unwrap(prevTargetValue, options); if (options.merge && typeUtils.isPlainObject(value) && (void 0 === prevTargetValue || typeUtils.isPlainObject(prevTargetValue)) && !(value instanceof $.Event)) { if (!prevTargetValue) { assignPropValue(target, targetPropName, {}, options) } target = unwrap(readPropValue(target, targetPropName), options); objectUtils.deepExtendArraySafe(target, value, false, true) } else { assignPropValue(target, targetPropName, value, options) } } } }; var toComparable = function(value, caseSensitive) { if (value instanceof Date) { return value.getTime() } if (value && value instanceof Class && value.valueOf) { return value.valueOf() } if (!caseSensitive && "string" === typeof value) { return value.toLowerCase() } return value }; exports.compileGetter = compileGetter; exports.compileSetter = compileSetter; exports.toComparable = toComparable }, /*!*********************************!*\ !*** ./js/core/events_mixin.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), DefaultEventsStrategy = __webpack_require__( /*! ./events_strategy */ 52), isPlainObject = __webpack_require__( /*! ./utils/type */ 12).isPlainObject; module.exports = { ctor: function() { this._events = {}; this.setEventsStrategy(new DefaultEventsStrategy(this)) }, setEventsStrategy: function(strategy) { this._eventsStrategy = strategy }, hasEvent: function(eventName) { return this._eventsStrategy.hasEvent(eventName) }, fireEvent: function(eventName, eventArgs) { this._eventsStrategy.fireEvent(eventName, eventArgs); return this }, on: function(eventName, eventHandler) { if (isPlainObject(eventName)) { $.each(eventName, function(e, h) { this.on(e, h) }.bind(this)) } else { this._eventsStrategy.on(eventName, eventHandler) } return this }, off: function(eventName, eventHandler) { this._eventsStrategy.off(eventName, eventHandler); return this }, _disposeEvents: function() { this._eventsStrategy.dispose() } } }, /*!************************************!*\ !*** ./js/core/events_strategy.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), isFunction = __webpack_require__( /*! ./utils/common */ 14).isFunction, Class = __webpack_require__( /*! ./class */ 25); module.exports = Class.inherit({ ctor: function(owner) { this._events = {}; this._owner = owner }, hasEvent: function(eventName) { var callbacks = this._events[eventName]; if (callbacks) { return callbacks.has() } return false }, fireEvent: function(eventName, eventArgs) { var callbacks = this._events[eventName]; if (callbacks) { callbacks.fireWith(this._owner, eventArgs) } }, on: function(eventName, eventHandler) { var addFn, callbacks = this._events[eventName]; if (!callbacks) { callbacks = $.Callbacks(); this._events[eventName] = callbacks } addFn = callbacks.originalAdd || callbacks.add; addFn.call(callbacks, eventHandler) }, off: function(eventName, eventHandler) { var callbacks = this._events[eventName]; if (callbacks) { if (isFunction(eventHandler)) { callbacks.remove(eventHandler) } else { callbacks.empty() } } }, dispose: function() { $.each(this._events, function() { this.empty() }) } }) }, /*!****************************!*\ !*** ./js/core/devices.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), extend = __webpack_require__( /*! ./utils/extend */ 11).extend, isPlainObject = __webpack_require__( /*! ./utils/type */ 12).isPlainObject, Class = __webpack_require__( /*! ./class */ 25), errors = __webpack_require__( /*! ./errors */ 7), resizeCallbacks = __webpack_require__( /*! ./utils/window */ 44).resizeCallbacks, EventsMixin = __webpack_require__( /*! ./events_mixin */ 51), SessionStorage = __webpack_require__( /*! ./utils/storage */ 54).sessionStorage, viewPort = __webpack_require__( /*! ./utils/view_port */ 55), Config = __webpack_require__( /*! ./config */ 15); var KNOWN_UA_TABLE = { iPhone: "iPhone", iPhone5: "iPhone", iPhone6: "iPhone", iPhone6plus: "iPhone", iPad: "iPad", iPadMini: "iPad Mini", androidPhone: "Android Mobile", androidTablet: "Android", win8: "MSAppHost", win8Phone: "Windows Phone 8.0", msSurface: "Windows ARM Tablet PC", desktop: "desktop", win10Phone: "Windows Phone 10.0", win10: "MSAppHost/3.0" }; var DEFAULT_DEVICE = { deviceType: "desktop", platform: "generic", version: [], phone: false, tablet: false, android: false, ios: false, win: false, generic: true, grade: "A", mac: false }; var uaParsers = { win: function(userAgent) { var isPhone = /windows phone/i.test(userAgent) || userAgent.match(/WPDesktop/), isTablet = !isPhone && /Windows(.*)arm(.*)Tablet PC/i.test(userAgent), isDesktop = !isPhone && !isTablet && /msapphost/i.test(userAgent); if (!(isPhone || isTablet || isDesktop)) { return } var matches = userAgent.match(/windows phone (\d+).(\d+)/i) || userAgent.match(/windows nt (\d+).(\d+)/i), version = []; if (matches) { version.push(parseInt(matches[1], 10), parseInt(matches[2], 10)) } else { matches = userAgent.match(/msapphost(\/(\d+).(\d+))?/i); matches && version.push(3 === parseInt(matches[2], 10) ? 10 : 8) } return { deviceType: isPhone ? "phone" : isTablet ? "tablet" : "desktop", platform: "win", version: version, grade: "A" } }, ios: function(userAgent) { if (!/ip(hone|od|ad)/i.test(userAgent)) { return } var isPhone = /ip(hone|od)/i.test(userAgent), matches = userAgent.match(/os (\d+)_(\d+)_?(\d+)?/i), version = matches ? [parseInt(matches[1], 10), parseInt(matches[2], 10), parseInt(matches[3] || 0, 10)] : [], isIPhone4 = 480 === window.screen.height, grade = isIPhone4 ? "B" : "A"; return { deviceType: isPhone ? "phone" : "tablet", platform: "ios", version: version, grade: grade } }, android: function(userAgent) { if (!/android|htc_|silk/i.test(userAgent)) { return } var isPhone = /mobile/i.test(userAgent), matches = userAgent.match(/android (\d+)\.(\d+)\.?(\d+)?/i), version = matches ? [parseInt(matches[1], 10), parseInt(matches[2], 10), parseInt(matches[3] || 0, 10)] : [], worseThan4_4 = version.length > 1 && (version[0] < 4 || 4 === version[0] && version[1] < 4), grade = worseThan4_4 ? "B" : "A"; return { deviceType: isPhone ? "phone" : "tablet", platform: "android", version: version, grade: grade } } }; var Devices = Class.inherit({ ctor: function(options) { this._window = options && options.window || window; this._realDevice = this._getDevice(); this._currentDevice = void 0; this._currentOrientation = void 0; this.changed = $.Callbacks(); this._recalculateOrientation(); resizeCallbacks.add(this._recalculateOrientation.bind(this)) }, current: function(deviceOrName) { if (deviceOrName) { this._currentDevice = this._getDevice(deviceOrName); this._forced = true; this.changed.fire(); if ("win" === this._currentDevice.platform && 8 === this._currentDevice.version[0]) { errors.log("W0010", "the 'win8' theme", "16.1", "Use the 'win10' theme instead.") } return } if (!this._currentDevice) { deviceOrName = void 0; try { deviceOrName = this._getDeviceOrNameFromWindowScope() } catch (e) { deviceOrName = this._getDeviceNameFromSessionStorage() } finally { if (!deviceOrName) { deviceOrName = this._getDeviceNameFromSessionStorage() } if (deviceOrName) { this._forced = true } } this._currentDevice = this._getDevice(deviceOrName) } return this._currentDevice }, real: function() { var forceDevice = arguments[0]; if (isPlainObject(forceDevice)) { extend(this._realDevice, forceDevice); return } return extend({}, this._realDevice) }, orientation: function() { return this._currentOrientation }, isForced: function() { return this._forced }, isRippleEmulator: function() { return !!this._window.tinyHippos }, _getCssClasses: function(device) { var result = []; var realDevice = this._realDevice; device = device || this.current(); if (device.deviceType) { result.push("dx-device-" + device.deviceType); if ("desktop" !== device.deviceType) { result.push("dx-device-mobile") } } result.push("dx-device-" + realDevice.platform); if (realDevice.version && realDevice.version.length) { result.push("dx-device-" + realDevice.platform + "-" + realDevice.version[0]) } if (devices.isSimulator()) { result.push("dx-simulator") } if (Config().rtlEnabled) { result.push("dx-rtl") } return result }, attachCssClasses: function(element, device) { this._deviceClasses = this._getCssClasses(device).join(" "); $(element).addClass(this._deviceClasses) }, detachCssClasses: function(element) { $(element).removeClass(this._deviceClasses) }, isSimulator: function() { try { return this._isSimulator || this._window.top !== this._window.self && this._window.top["dx-force-device"] || this.isRippleEmulator() } catch (e) { return false } }, forceSimulator: function() { this._isSimulator = true }, _getDevice: function(deviceName) { if ("genericPhone" === deviceName) { deviceName = { deviceType: "phone", platform: "generic", generic: true } } if (isPlainObject(deviceName)) { return this._fromConfig(deviceName) } else { var ua; if (deviceName) { ua = KNOWN_UA_TABLE[deviceName]; if (!ua) { throw errors.Error("E0005") } } else { ua = navigator.userAgent } return this._fromUA(ua) } }, _getDeviceOrNameFromWindowScope: function() { var result; if (this._window.top["dx-force-device-object"] || this._window.top["dx-force-device"]) { result = this._window.top["dx-force-device-object"] || this._window.top["dx-force-device"] } return result }, _getDeviceNameFromSessionStorage: function() { var sessionStorage = SessionStorage(); if (!sessionStorage) { return } var deviceOrName = sessionStorage.getItem("dx-force-device"); try { return JSON.parse(deviceOrName) } catch (ex) { return deviceOrName } }, _fromConfig: function(config) { var result = extend({}, DEFAULT_DEVICE, this._currentDevice, config), shortcuts = { phone: "phone" === result.deviceType, tablet: "tablet" === result.deviceType, android: "android" === result.platform, ios: "ios" === result.platform, win: "win" === result.platform, generic: "generic" === result.platform }; return extend(result, shortcuts) }, _fromUA: function(ua) { var config; $.each(uaParsers, function(platform, parser) { config = parser(ua); return !config }); if (config) { return this._fromConfig(config) } var isMac = /(mac os)/.test(ua.toLowerCase()), deviceWithOS = DEFAULT_DEVICE; deviceWithOS.mac = isMac; return deviceWithOS }, _changeOrientation: function() { var $window = $(this._window), orientation = $window.height() > $window.width() ? "portrait" : "landscape"; if (this._currentOrientation === orientation) { return } this._currentOrientation = orientation; this.fireEvent("orientationChanged", [{ orientation: orientation }]) }, _recalculateOrientation: function() { var windowWidth = $(this._window).width(); if (this._currentWidth === windowWidth) { return } this._currentWidth = windowWidth; this._changeOrientation() } }).include(EventsMixin); var devices = new Devices; viewPort.changeCallback.add(function(viewPort, prevViewport) { devices.detachCssClasses(prevViewport); devices.attachCssClasses(viewPort) }); if (!devices.isForced() && "win" === devices.current().platform) { devices.current({ version: [10] }) } module.exports = devices }, /*!**********************************!*\ !*** ./js/core/utils/storage.js ***! \**********************************/ function(module, exports) { var getSessionStorage = function() { var sessionStorage; try { sessionStorage = window.sessionStorage } catch (e) {} return sessionStorage }; exports.sessionStorage = getSessionStorage }, /*!************************************!*\ !*** ./js/core/utils/view_port.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ready = __webpack_require__( /*! ./dom */ 56).ready, changeCallback = $.Callbacks(), $originalViewPort = $(); var value = function() { var $current; return function(element) { if (!arguments.length) { return $current } var $element = $(element); $originalViewPort = $element; var isNewViewportFound = !!$element.length; var prevViewPort = value(); $current = isNewViewportFound ? $element : $("body"); changeCallback.fire(isNewViewportFound ? value() : $(), prevViewPort) } }(); ready(function() { value(".dx-viewport") }); exports.value = value; exports.changeCallback = changeCallback; exports.originalViewPort = function() { return $originalViewPort } }, /*!******************************!*\ !*** ./js/core/utils/dom.js ***! \******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), errors = __webpack_require__( /*! ../errors */ 7), inArray = __webpack_require__( /*! ./array */ 26).inArray, commonUtils = __webpack_require__( /*! ./common */ 14); var resetActiveElement = function() { var activeElement = document.activeElement; if (activeElement && activeElement !== document.body && activeElement.blur) { activeElement.blur() } }; var clearSelection = function() { var selection = window.getSelection(); if (!selection) { return } if ("Caret" === selection.type) { return } if (selection.empty) { selection.empty() } else { if (selection.removeAllRanges) { try { selection.removeAllRanges() } catch (e) {} } } }; var closestCommonParent = function(startTarget, endTarget) { var $startTarget = $(startTarget), $endTarget = $(endTarget); if ($startTarget[0] === $endTarget[0]) { return $startTarget[0] } var $startParents = $startTarget.parents(), $endParents = $endTarget.parents(), startingParent = Math.min($startParents.length, $endParents.length); for (var i = -startingParent; i < 0; i++) { if ($startParents.get(i) === $endParents.get(i)) { return $startParents.get(i) } } }; var triggerVisibilityChangeEvent = function(eventName) { var VISIBILITY_CHANGE_SELECTOR = ".dx-visibility-change-handler"; return function(element) { var $element = $(element || "body"); var changeHandlers = $element.filter(VISIBILITY_CHANGE_SELECTOR).add($element.find(VISIBILITY_CHANGE_SELECTOR)); for (var i = 0; i < changeHandlers.length; i++) { $(changeHandlers[i]).triggerHandler(eventName) } } }; var uniqueId = function() { var counter = 0; return function(prefix) { return (prefix || "") + counter++ } }(); var dataOptionsAttributeName = "data-options"; var getElementOptions = function(element) { var result, optionsString = $(element).attr(dataOptionsAttributeName); if ("{" !== $.trim(optionsString).charAt(0)) { optionsString = "{" + optionsString + "}" } try { result = new Function("return " + optionsString)() } catch (ex) { throw errors.Error("E3018", ex, optionsString) } return result }; var createComponents = function(elements, componentTypes) { var result = [], selector = "[" + dataOptionsAttributeName + "]"; var $items = elements.find(selector).add(elements.filter(selector)); $items.each(function(index, element) { var $element = $(element), options = getElementOptions(element); for (var componentName in options) { if (!componentTypes || inArray(componentName, componentTypes) > -1) { if ($element[componentName]) { $element[componentName](options[componentName]); result.push($element[componentName]("instance")) } } } }); return result }; var createMarkupFromString = function(str) { if (!window.WinJS) { return $(str) } var tempElement = $("<div />"); window.WinJS.Utilities.setInnerHTMLUnsafe(tempElement.get(0), str); return tempElement.contents() }; var normalizeTemplateElement = function(element) { var $element = commonUtils.isDefined(element) && (element.nodeType || element.jquery) ? $(element) : $("<div>").html(element).contents(); if (1 === $element.length) { if ($element.is("script")) { $element = normalizeTemplateElement($element.html()) } else { if ($element.is("table")) { $element = $element.children("tbody").contents() } } } return $element }; var toggleAttr = function($target, attr, value) { value ? $target.attr(attr, value) : $target.removeAttr(attr) }; var clipboardText = function(event, text) { var clipboard = event.originalEvent && event.originalEvent.clipboardData || window.clipboardData; if (1 === arguments.length) { return clipboard && clipboard.getData("Text") } clipboard && clipboard.setData("Text", text) }; exports.ready = function(callback) { if ("complete" === document.readyState || "loading" !== document.readyState && !document.documentElement.doScroll) { callback(); return } var loadedCallback = function() { callback(); document.removeEventListener("DOMContentLoaded", loadedCallback) }; document.addEventListener("DOMContentLoaded", loadedCallback) }; exports.resetActiveElement = resetActiveElement; exports.createMarkupFromString = createMarkupFromString; exports.triggerShownEvent = triggerVisibilityChangeEvent("dxshown"); exports.triggerHidingEvent = triggerVisibilityChangeEvent("dxhiding"); exports.triggerResizeEvent = triggerVisibilityChangeEvent("dxresize"); exports.getElementOptions = getElementOptions; exports.createComponents = createComponents; exports.normalizeTemplateElement = normalizeTemplateElement; exports.clearSelection = clearSelection; exports.uniqueId = uniqueId; exports.closestCommonParent = closestCommonParent; exports.clipboardText = clipboardText; exports.toggleAttr = toggleAttr }, /*!******************************************!*\ !*** ./js/core/component_registrator.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), jQuery = __webpack_require__( /*! jquery */ 10), errors = __webpack_require__( /*! ./errors */ 7), MemorizedCallbacks = __webpack_require__( /*! ./memorized_callbacks */ 58), publicComponentUtils = __webpack_require__( /*! ./utils/public_component */ 45); var callbacks = new MemorizedCallbacks; var registerComponent = function(name, namespace, componentClass) { if (!componentClass) { componentClass = namespace } else { namespace[name] = componentClass } publicComponentUtils.name(componentClass, name); callbacks.fire(name, componentClass) }; registerComponent.callbacks = callbacks; var registerJQueryComponent = function(name, componentClass) { $.fn[name] = jQuery.fn[name] = function(options) { var result, isMemberInvoke = "string" === typeof options; if (isMemberInvoke) { var memberName = options, memberArgs = $.makeArray(arguments).slice(1); this.each(function() { var instance = componentClass.getInstance(this); if (!instance) { throw errors.Error("E0009", name) } var member = instance[memberName], memberValue = member.apply(instance, memberArgs); if (void 0 === result) { result = memberValue } }) } else { this.each(function() { var instance = componentClass.getInstance(this); if (instance) { instance.option(options) } else { new componentClass(this, options) } }); result = this } return result } }; callbacks.add(registerJQueryComponent); module.exports = registerComponent }, /*!****************************************!*\ !*** ./js/core/memorized_callbacks.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9); var MemorizedCallbacks = function() { var memory = []; var callbacks = $.Callbacks(); this.add = function(fn) { $.each(memory, function(_, item) { fn.apply(fn, item) }); callbacks.add(fn) }; this.remove = function(fn) { callbacks.remove(fn) }; this.fire = function() { memory.push(arguments); callbacks.fire.apply(callbacks, arguments) } }; module.exports = MemorizedCallbacks }, /*!*******************************!*\ !*** ./js/animation/frame.js ***! \*******************************/ function(module, exports) { var FRAME_ANIMATION_STEP_TIME = 1e3 / 60, request = function(callback) { return this.setTimeout(callback, FRAME_ANIMATION_STEP_TIME) }, cancel = function(requestID) { this.clearTimeout(requestID) }, nativeRequest = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame, nativeCancel = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame; if (nativeRequest && nativeCancel) { request = nativeRequest; cancel = nativeCancel } if (nativeRequest && !nativeCancel) { var canceledRequests = {}; request = function(callback) { var requestId = nativeRequest.call(window, function() { try { if (requestId in canceledRequests) { return } callback.apply(this, arguments) } finally { delete canceledRequests[requestId] } }); return requestId }; cancel = function(requestId) { canceledRequests[requestId] = true } } exports.requestAnimationFrame = request.bind(window); exports.cancelAnimationFrame = cancel.bind(window) }, /*!****************************************************************!*\ !*** ./js/mobile/init_mobile_viewport/init_mobile_viewport.js ***! \****************************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, resizeCallbacks = __webpack_require__( /*! ../../core/utils/window */ 44).resizeCallbacks, support = __webpack_require__( /*! ../../core/utils/support */ 61), devices = __webpack_require__( /*! ../../core/devices */ 53); var initMobileViewport = function(options) { options = extend({}, options); var realDevice = devices.real(); var allowZoom = options.allowZoom; var allowPan = options.allowPan; var allowSelection = "allowSelection" in options ? options.allowSelection : "generic" === realDevice.platform; var metaSelector = "meta[name=viewport]"; if (!$(metaSelector).length) { $("<meta />").attr("name", "viewport").appendTo("head") } var metaVerbs = ["width=device-width"], msTouchVerbs = []; if (allowZoom) { msTouchVerbs.push("pinch-zoom") } else { metaVerbs.push("initial-scale=1.0", "maximum-scale=1.0, user-scalable=no") } if (allowPan) { msTouchVerbs.push("pan-x", "pan-y") } if (!allowPan && !allowZoom) { $("html, body").css({ "-ms-content-zooming": "none", "-ms-user-select": "none", overflow: "hidden" }) } else { $("html").css("-ms-overflow-style", "-ms-autohiding-scrollbar") } if (!allowSelection && support.supportProp("user-select")) { $(".dx-viewport").css(support.styleProp("user-select"), "none") } $(metaSelector).attr("content", metaVerbs.join()); $("html").css("-ms-touch-action", msTouchVerbs.join(" ") || "none"); realDevice = devices.real(); if (support.touch && !("win" === realDevice.platform && 10 === realDevice.version[0])) { $(document).off(".dxInitMobileViewport").on("dxpointermove.dxInitMobileViewport", function(e) { var count = e.pointers.length, isTouchEvent = "touch" === e.pointerType, zoomDisabled = !allowZoom && count > 1, panDisabled = !allowPan && 1 === count && !e.isScrollingEvent; if (isTouchEvent && (zoomDisabled || panDisabled)) { e.preventDefault() } }) } if (realDevice.ios) { var isPhoneGap = "file:" === document.location.protocol; if (!isPhoneGap) { resizeCallbacks.add(function() { var windowWidth = $(window).width(); $("body").width(windowWidth) }) } } if (realDevice.android) { resizeCallbacks.add(function() { setTimeout(function() { document.activeElement.scrollIntoViewIfNeeded() }) }) } }; exports.initMobileViewport = initMobileViewport }, /*!**********************************!*\ !*** ./js/core/utils/support.js ***! \**********************************/ function(module, exports, __webpack_require__) { var inflector = __webpack_require__( /*! ./inflector */ 39), inArray = __webpack_require__( /*! ./array */ 26).inArray, devices = __webpack_require__( /*! ../devices */ 53); var camelize = inflector.camelize; var jsPrefixes = ["", "Webkit", "Moz", "O", "Ms"], cssPrefixes = { "": "", Webkit: "-webkit-", Moz: "-moz-", O: "-o-", ms: "-ms-" }, styles = document.createElement("dx").style; var transitionEndEventNames = { webkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd", msTransition: "MsTransitionEnd", transition: "transitionend" }; var forEachPrefixes = function(prop, callBack) { prop = camelize(prop, true); var result; for (var i = 0, cssPrefixesCount = jsPrefixes.length; i < cssPrefixesCount; i++) { var jsPrefix = jsPrefixes[i]; var prefixedProp = jsPrefix + prop; var lowerPrefixedProp = camelize(prefixedProp); result = callBack(lowerPrefixedProp, jsPrefix); if (void 0 === result) { result = callBack(prefixedProp, jsPrefix) } if (void 0 !== result) { break } } return result }; var styleProp = function(prop) { return forEachPrefixes(prop, function(specific) { if (specific in styles) { return specific } }) }; var stylePropPrefix = function(prop) { return forEachPrefixes(prop, function(specific, jsPrefix) { if (specific in styles) { return cssPrefixes[jsPrefix] } }) }; var supportProp = function(prop) { return !!styleProp(prop) }; var isNativeScrollingSupported = function() { var realDevice = devices.real(), realPlatform = realDevice.platform, realVersion = realDevice.version, isObsoleteAndroid = realVersion && realVersion[0] < 4 && "android" === realPlatform, isNativeScrollDevice = !isObsoleteAndroid && inArray(realPlatform, ["ios", "android", "win"]) > -1 || realDevice.mac; return isNativeScrollDevice }; var inputType = function(type) { if ("text" === type) { return true } var input = document.createElement("input"); try { input.setAttribute("type", type); input.value = "wrongValue"; return !input.value } catch (e) { return false } }; var touchEvents = "ontouchstart" in window && !("callPhantom" in window), pointerEvents = !!window.navigator.pointerEnabled || !!window.navigator.msPointerEnabled, touchPointersPresent = !!window.navigator.maxTouchPoints || !!window.navigator.msMaxTouchPoints; exports.touchEvents = touchEvents; exports.pointerEvents = pointerEvents; exports.touch = touchEvents || pointerEvents && touchPointersPresent; exports.transition = supportProp("transition"); exports.transitionEndEventName = transitionEndEventNames[styleProp("transition")]; exports.animation = supportProp("animation"); exports.nativeScrolling = isNativeScrollingSupported(); exports.styleProp = styleProp; exports.stylePropPrefix = stylePropPrefix; exports.supportProp = supportProp; exports.hasKo = !!window.ko; exports.inputType = inputType }, /*!********************************!*\ !*** ./js/core/utils/queue.js ***! \********************************/ function(module, exports, __webpack_require__) { var errors = __webpack_require__( /*! ../errors */ 7), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; function createQueue(discardPendingTasks) { var _tasks = [], _busy = false; function exec() { while (_tasks.length) { _busy = true; var task = _tasks.shift(), result = task(); if (void 0 === result) { continue } if (result.then) { when(result).always(exec); return } throw errors.Error("E0015") } _busy = false } function add(task, removeTaskCallback) { if (!discardPendingTasks) { _tasks.push(task) } else { if (_tasks[0] && removeTaskCallback) { removeTaskCallback(_tasks[0]) } _tasks = [task] } if (!_busy) { exec() } } function busy() { return _busy } return { add: add, busy: busy } } exports.create = createQueue; exports.enqueue = createQueue().add }, /*!*******************************!*\ !*** ./js/core/utils/date.js ***! \*******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ./common */ 14), camelize = __webpack_require__( /*! ./inflector */ 39).camelize, isObject = commonUtils.isObject, isString = commonUtils.isString, isDate = commonUtils.isDate, isDefined = commonUtils.isDefined; var dateUnitIntervals = ["millisecond", "second", "minute", "hour", "day", "week", "month", "quarter", "year"]; var toMilliseconds = function(value) { switch (value) { case "millisecond": return 1; case "second": return 1e3 * toMilliseconds("millisecond"); case "minute": return 60 * toMilliseconds("second"); case "hour": return 60 * toMilliseconds("minute"); case "day": return 24 * toMilliseconds("hour"); case "week": return 7 * toMilliseconds("day"); case "month": return 30 * toMilliseconds("day"); case "quarter": return 3 * toMilliseconds("month"); case "year": return 365 * toMilliseconds("day"); default: return 0 } }; var getDatesInterval = function(startDate, endDate, intervalUnit) { var delta = endDate.getTime() - startDate.getTime(), millisecondCount = toMilliseconds(intervalUnit) || 1; return Math.floor(delta / millisecondCount) }; var getNextDateUnit = function(unit, withWeeks) { var interval = getDateUnitInterval(unit); switch (interval) { case "millisecond": return "second"; case "second": return "minute"; case "minute": return "hour"; case "hour": return "day"; case "day": return withWeeks ? "week" : "month"; case "week": return "month"; case "month": return "quarter"; case "quarter": return "year"; case "year": return "year"; default: return 0 } }; var convertMillisecondsToDateUnits = function(value) { var i, dateUnitCount, dateUnitInterval, dateUnitIntervals = ["millisecond", "second", "minute", "hour", "day", "month", "year"], result = {}; for (i = dateUnitIntervals.length - 1; i >= 0; i--) { dateUnitInterval = dateUnitIntervals[i]; dateUnitCount = Math.floor(value / toMilliseconds(dateUnitInterval)); if (dateUnitCount > 0) { result[dateUnitInterval + "s"] = dateUnitCount; value -= convertDateUnitToMilliseconds(dateUnitInterval, dateUnitCount) } } return result }; var dateToMilliseconds = function(tickInterval) { var milliseconds = 0; if (isObject(tickInterval)) { $.each(tickInterval, function(key, value) { milliseconds += convertDateUnitToMilliseconds(key.substr(0, key.length - 1), value) }) } if (isString(tickInterval)) { milliseconds = convertDateUnitToMilliseconds(tickInterval, 1) } return milliseconds }; var convertDateUnitToMilliseconds = function(dateUnit, count) { return toMilliseconds(dateUnit) * count }; var getDateUnitInterval = function(tickInterval) { var i, maxInterval = -1; if (isString(tickInterval)) { return tickInterval } if (isObject(tickInterval)) { $.each(tickInterval, function(key, value) { for (i = 0; i < dateUnitIntervals.length; i++) { if (value && (key === dateUnitIntervals[i] + "s" || key === dateUnitIntervals[i]) && maxInterval < i) { maxInterval = i } } }); return dateUnitIntervals[maxInterval] } return "" }; var tickIntervalToFormatMap = { millisecond: "millisecond", second: "longtime", minute: "shorttime", hour: "shorttime", day: "day", week: "day", month: "month", quarter: "quarter", year: "year" }; function getDateFormatByTickInterval(tickInterval) { return tickIntervalToFormatMap[getDateUnitInterval(tickInterval)] || "" } var getQuarter = function(month) { return Math.floor(month / 3) }; var getFirstQuarterMonth = function(month) { return 3 * getQuarter(month) }; var correctDateWithUnitBeginning = function(date, dateInterval, withCorrection) { date = new Date(date.getTime()); var firstQuarterMonth, oldDate = new Date(date.getTime()), dateUnitInterval = getDateUnitInterval(dateInterval); switch (dateUnitInterval) { case "second": date.setMilliseconds(0); break; case "minute": date.setSeconds(0, 0); break; case "hour": date.setMinutes(0, 0, 0); break; case "year": date.setMonth(0); case "month": date.setDate(1); case "day": date.setHours(0, 0, 0, 0); break; case "week": date.setDate(date.getDate() - date.getDay()); date.setHours(0, 0, 0, 0); break; case "quarter": firstQuarterMonth = getFirstQuarterMonth(date.getMonth()); if (date.getMonth() !== firstQuarterMonth) { date.setMonth(firstQuarterMonth) } date.setDate(1); date.setHours(0, 0, 0, 0) } if (withCorrection && "hour" !== dateUnitInterval && "minute" !== dateUnitInterval && "second" !== dateUnitInterval) { fixTimezoneGap(oldDate, date) } return date }; var trimTime = function(date) { return dateUtils.correctDateWithUnitBeginning(date, "day") }; var getDatesDifferences = function(date1, date2) { var differences, counter = 0; differences = { year: date1.getFullYear() !== date2.getFullYear(), month: date1.getMonth() !== date2.getMonth(), day: date1.getDate() !== date2.getDate(), hour: date1.getHours() !== date2.getHours(), minute: date1.getMinutes() !== date2.getMinutes(), second: date1.getSeconds() !== date2.getSeconds(), millisecond: date1.getMilliseconds() !== date2.getMilliseconds() }; $.each(differences, function(key, value) { if (value) { counter++ } }); differences.count = counter; return differences }; function addDateInterval(value, interval, dir) { var result = new Date(value.getTime()), intervalObject = isString(interval) ? getDateIntervalByString(interval.toLowerCase()) : interval; if (intervalObject.years) { result.setFullYear(result.getFullYear() + intervalObject.years * dir) } if (intervalObject.quarters) { result.setMonth(result.getMonth() + 3 * intervalObject.quarters * dir) } if (intervalObject.months) { result.setMonth(result.getMonth() + intervalObject.months * dir) } if (intervalObject.weeks) { result.setDate(result.getDate() + 7 * intervalObject.weeks * dir) } if (intervalObject.days) { result.setDate(result.getDate() + intervalObject.days * dir) } if (intervalObject.hours) { result.setHours(result.getHours() + intervalObject.hours * dir) } if (intervalObject.minutes) { result.setMinutes(result.getMinutes() + intervalObject.minutes * dir) } if (intervalObject.seconds) { result.setSeconds(result.getSeconds() + intervalObject.seconds * dir) } if (intervalObject.milliseconds) { result.setMilliseconds(value.getMilliseconds() + intervalObject.milliseconds * dir) } return result } var addInterval = function(value, interval, isNegative) { var dir = isNegative ? -1 : 1; return isDate(value) ? addDateInterval(value, interval, dir) : value + interval * dir }; var getSequenceByInterval = function(min, max, interval) { var cur, intervals = []; intervals.push(isDate(min) ? new Date(min.getTime()) : min); cur = min; while (cur < max) { cur = addInterval(cur, interval); intervals.push(cur) } return intervals }; var getViewFirstCellDate = function(viewType, date) { if ("month" === viewType) { return new Date(date.getFullYear(), date.getMonth(), 1) } if ("year" === viewType) { return new Date(date.getFullYear(), 0, date.getDate()) } if ("decade" === viewType) { return new Date(getFirstYearInDecade(date), date.getMonth(), date.getDate()) } if ("century" === viewType) { return new Date(getFirstDecadeInCentury(date), date.getMonth(), date.getDate()) } }; var getViewLastCellDate = function(viewType, date) { if ("month" === viewType) { return new Date(date.getFullYear(), date.getMonth(), getLastMonthDay(date)) } if ("year" === viewType) { return new Date(date.getFullYear(), 11, date.getDate()) } if ("decade" === viewType) { return new Date(getFirstYearInDecade(date) + 9, date.getMonth(), date.getDate()) } if ("century" === viewType) { return new Date(getFirstDecadeInCentury(date) + 90, date.getMonth(), date.getDate()) } }; var getViewMinBoundaryDate = function(viewType, date) { var resultDate = new Date(date.getFullYear(), date.getMonth(), 1); if ("month" === viewType) { return resultDate } resultDate.setMonth(0); if ("year" === viewType) { return resultDate } if ("decade" === viewType) { resultDate.setFullYear(getFirstYearInDecade(date)) } if ("century" === viewType) { resultDate.setFullYear(getFirstDecadeInCentury(date)) } return resultDate }; var getViewMaxBoundaryDate = function(viewType, date) { var resultDate = new Date(date.getFullYear(), date.getMonth(), getLastMonthDay(date)); if ("month" === viewType) { return resultDate } resultDate.setMonth(11); resultDate.setDate(getLastMonthDay(resultDate)); if ("year" === viewType) { return resultDate } if ("decade" === viewType) { resultDate.setFullYear(getFirstYearInDecade(date) + 9) } if ("century" === viewType) { resultDate.setFullYear(getFirstDecadeInCentury(date) + 99) } return resultDate }; var getLastMonthDay = function(date) { var resultDate = new Date(date.getFullYear(), date.getMonth() + 1, 0); return resultDate.getDate() }; var sameView = function(view, date1, date2) { return dateUtils[camelize("same " + view)](date1, date2) }; var getViewUp = function(typeView) { switch (typeView) { case "month": return "year"; case "year": return "decade"; case "decade": return "century" } }; var getViewDown = function(typeView) { switch (typeView) { case "century": return "decade"; case "decade": return "year"; case "year": return "month" } }; var getDifferenceInMonth = function(typeView) { var difference = 1; if ("year" === typeView) { difference = 12 } if ("decade" === typeView) { difference = 120 } if ("century" === typeView) { difference = 1200 } return difference }; var getDifferenceInMonthForCells = function(typeView) { var difference = 1; if ("decade" === typeView) { difference = 12 } if ("century" === typeView) { difference = 120 } return difference }; var getDateIntervalByString = function(intervalString) { var result = {}; switch (intervalString) { case "year": result.years = 1; break; case "month": result.months = 1; break; case "quarter": result.months = 3; break; case "week": result.days = 7; break; case "day": result.days = 1; break; case "hour": result.hours = 1; break; case "minute": result.minutes = 1; break; case "second": result.seconds = 1; break; case "millisecond": result.milliseconds = 1 } return result }; var sameDate = function(date1, date2) { return sameMonthAndYear(date1, date2) && date1.getDate() === date2.getDate() }; var sameMonthAndYear = function(date1, date2) { return sameYear(date1, date2) && date1.getMonth() === date2.getMonth() }; var sameYear = function(date1, date2) { return date1 && date2 && date1.getFullYear() === date2.getFullYear() }; var sameDecade = function(date1, date2) { if (!isDefined(date1) || !isDefined(date2)) { return } var startDecadeDate1 = date1.getFullYear() - date1.getFullYear() % 10, startDecadeDate2 = date2.getFullYear() - date2.getFullYear() % 10; return date1 && date2 && startDecadeDate1 === startDecadeDate2 }; var sameCentury = function(date1, date2) { if (!isDefined(date1) || !isDefined(date2)) { return } var startCenturyDate1 = date1.getFullYear() - date1.getFullYear() % 100, startCenturyDate2 = date2.getFullYear() - date2.getFullYear() % 100; return date1 && date2 && startCenturyDate1 === startCenturyDate2 }; var getFirstDecadeInCentury = function(date) { return date && date.getFullYear() - date.getFullYear() % 100 }; var getFirstYearInDecade = function(date) { return date && date.getFullYear() - date.getFullYear() % 10 }; var getShortDateFormat = function() { return "yyyy/MM/dd" }; var getFirstMonthDate = function(date) { if (!isDefined(date)) { return } var newDate = new Date(date.getFullYear(), date.getMonth(), 1); return newDate }; var getLastMonthDate = function(date) { if (!isDefined(date)) { return } var newDate = new Date(date.getFullYear(), date.getMonth() + 1, 0); return newDate }; var getFirstWeekDate = function(date, firstDayOfWeek) { var delta = (date.getDay() - firstDayOfWeek + 7) % 7; var result = new Date(date); result.setDate(date.getDate() - delta); return result }; var normalizeDateByWeek = function(date, currentDate) { var differenceInDays = dateUtils.getDatesInterval(date, currentDate, "day"), resultDate = new Date(date); if (differenceInDays >= 6) { resultDate = new Date(resultDate.setDate(resultDate.getDate() + 7)) } return resultDate }; var dateInRange = function(date, min, max, format) { if ("date" === format) { min = min && dateUtils.correctDateWithUnitBeginning(min, "day"); max = max && dateUtils.correctDateWithUnitBeginning(max, "day"); date = date && dateUtils.correctDateWithUnitBeginning(date, "day") } return normalizeDate(date, min, max) === date }; var normalizeDate = function(date, min, max) { var normalizedDate = date; if (!isDefined(date)) { return date } if (isDefined(min) && date < min) { normalizedDate = min } if (isDefined(max) && date > max) { normalizedDate = max } return normalizedDate }; var fixTimezoneGap = function(oldDate, newDate) { if (!isDefined(oldDate)) { return } var sign, trial, diff = newDate.getHours() - oldDate.getHours(); if (0 === diff) { return } sign = 1 === diff || diff === -23 ? -1 : 1; trial = new Date(newDate.getTime() + 36e5 * sign); if (sign > 0 || trial.getDate() === newDate.getDate()) { newDate.setTime(trial.getTime()) } }; var roundToHour = function(date) { date.setHours(date.getHours() + 1); date.setMinutes(0); return date }; var getTimezonesDifference = function(min, max) { return 60 * (max.getTimezoneOffset() - min.getTimezoneOffset()) * 1e3 }; var makeDate = function(date) { return new Date(date) }; var dateUtils = { dateUnitIntervals: dateUnitIntervals, convertMillisecondsToDateUnits: convertMillisecondsToDateUnits, dateToMilliseconds: dateToMilliseconds, getNextDateUnit: getNextDateUnit, convertDateUnitToMilliseconds: convertDateUnitToMilliseconds, getDateUnitInterval: getDateUnitInterval, getDateFormatByTickInterval: getDateFormatByTickInterval, getDatesDifferences: getDatesDifferences, correctDateWithUnitBeginning: correctDateWithUnitBeginning, trimTime: trimTime, addDateInterval: addDateInterval, addInterval: addInterval, getSequenceByInterval: getSequenceByInterval, getDateIntervalByString: getDateIntervalByString, sameDate: sameDate, sameMonthAndYear: sameMonthAndYear, sameMonth: sameMonthAndYear, sameYear: sameYear, sameDecade: sameDecade, sameCentury: sameCentury, sameView: sameView, getDifferenceInMonth: getDifferenceInMonth, getDifferenceInMonthForCells: getDifferenceInMonthForCells, getFirstYearInDecade: getFirstYearInDecade, getFirstDecadeInCentury: getFirstDecadeInCentury, getShortDateFormat: getShortDateFormat, getViewFirstCellDate: getViewFirstCellDate, getViewLastCellDate: getViewLastCellDate, getViewDown: getViewDown, getViewUp: getViewUp, getLastMonthDay: getLastMonthDay, getLastMonthDate: getLastMonthDate, getFirstMonthDate: getFirstMonthDate, getFirstWeekDate: getFirstWeekDate, normalizeDateByWeek: normalizeDateByWeek, getQuarter: getQuarter, getFirstQuarterMonth: getFirstQuarterMonth, dateInRange: dateInRange, roundToHour: roundToHour, normalizeDate: normalizeDate, getViewMinBoundaryDate: getViewMinBoundaryDate, getViewMaxBoundaryDate: getViewMaxBoundaryDate, fixTimezoneGap: fixTimezoneGap, getTimezonesDifference: getTimezonesDifference, makeDate: makeDate, getDatesInterval: getDatesInterval }; module.exports = dateUtils }, /*!***************************************************!*\ !*** ./js/mobile/process_hardware_back_button.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), hardwareBack = $.Callbacks(); module.exports = function() { hardwareBack.fire() }; module.exports.processCallback = hardwareBack }, /*!***************************************!*\ !*** ./js/mobile/hide_top_overlay.js ***! \***************************************/ function(module, exports, __webpack_require__) { var inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray; var hideCallback = function() { var callbacks = []; return { add: function(callback) { var indexOfCallback = inArray(callback, callbacks); if (indexOfCallback === -1) { callbacks.push(callback) } }, remove: function(callback) { var indexOfCallback = inArray(callback, callbacks); if (indexOfCallback !== -1) { callbacks.splice(indexOfCallback, 1) } }, fire: function() { var callback = callbacks.pop(), result = !!callback; if (result) { callback() } return result }, hasCallback: function() { return callbacks.length > 0 }, reset: function() { callbacks = [] } } }(); module.exports = function() { return hideCallback.fire() }; module.exports.hideCallback = hideCallback }, /*!*****************************!*\ !*** ./js/format_helper.js ***! \*****************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ./core/utils/common */ 14), typeUtils = __webpack_require__( /*! ./core/utils/type */ 12), dateUtils = __webpack_require__( /*! ./core/utils/date */ 63), numberLocalization = __webpack_require__( /*! ./localization/number */ 32), dateLocalization = __webpack_require__( /*! ./localization/date */ 33), dependencyInjector = __webpack_require__( /*! ./core/utils/dependency_injector */ 29), logger = __webpack_require__( /*! ./core/utils/console */ 13).logger; __webpack_require__( /*! ./localization/currency */ 36); module.exports = dependencyInjector({ format: function(value, format, precision) { var formatIsValid = commonUtils.isString(format) && "" !== format || typeUtils.isPlainObject(format) || commonUtils.isFunction(format), valueIsValid = commonUtils.isNumeric(value) || commonUtils.isDate(value); if (!formatIsValid || !valueIsValid) { return commonUtils.isDefined(value) ? value.toString() : "" } if (commonUtils.isFunction(format)) { return format(value) } if (void 0 !== precision) { logger.warn("Option 'precision' is deprecated. Use field 'precision' of a format object instead.") } if (commonUtils.isString(format)) { format = { type: format, precision: precision } } if (commonUtils.isNumeric(value)) { return numberLocalization.format(value, format) } if (commonUtils.isDate(value)) { return dateLocalization.format(value, format) } }, getTimeFormat: function(showSecond) { return showSecond ? "longtime" : "shorttime" }, _normalizeFormat: function(format) { if (!Array.isArray(format)) { return format } if (1 === format.length) { return format[0] } return function(date) { return format.map(function(formatPart) { return dateLocalization.format(date, formatPart) }).join(" ") } }, getDateFormatByDifferences: function(dateDifferences) { var resultFormat = []; if (dateDifferences.millisecond) { resultFormat.push("millisecond") } if (dateDifferences.hour || dateDifferences.minute || dateDifferences.second) { resultFormat.unshift(this.getTimeFormat(dateDifferences.second)) } if (dateDifferences.year && dateDifferences.month && dateDifferences.day) { resultFormat.unshift("shortdate"); return this._normalizeFormat(resultFormat) } if (dateDifferences.year && dateDifferences.month) { return "monthandyear" } if (dateDifferences.year && dateDifferences.quarter) { return "quarterandyear" } if (dateDifferences.year) { return "year" } if (dateDifferences.quarter) { return "quarter" } if (dateDifferences.month && dateDifferences.day) { resultFormat.unshift("monthandday"); return this._normalizeFormat(resultFormat) } if (dateDifferences.month) { return "month" } if (dateDifferences.day) { var dayFormatter = function(date) { return dateLocalization.format(date, "dayofweek") + ", " + dateLocalization.format(date, "day") }; resultFormat.unshift(dayFormatter); return this._normalizeFormat(resultFormat) } return this._normalizeFormat(resultFormat) }, getDateFormatByTicks: function(ticks) { var resultFormat, maxDiff, currentDiff, i; if (ticks.length > 1) { maxDiff = dateUtils.getDatesDifferences(ticks[0], ticks[1]); for (i = 1; i < ticks.length - 1; i++) { currentDiff = dateUtils.getDatesDifferences(ticks[i], ticks[i + 1]); if (maxDiff.count < currentDiff.count) { maxDiff = currentDiff } } } else { maxDiff = { year: true, month: true, day: true, hour: ticks[0].getHours() > 0, minute: ticks[0].getMinutes() > 0, second: ticks[0].getSeconds() > 0, millisecond: ticks[0].getMilliseconds() > 0 } } resultFormat = this.getDateFormatByDifferences(maxDiff); return resultFormat }, getDateFormatByTickInterval: function(startValue, endValue, tickInterval) { var resultFormat, dateDifferences, dateUnitInterval, dateDifferencesConverter = { week: "day" }, correctDateDifferences = function(dateDifferences, tickInterval, value) { switch (tickInterval) { case "year": case "quarter": dateDifferences.month = value; case "month": dateDifferences.day = value; case "week": case "day": dateDifferences.hour = value; case "hour": dateDifferences.minute = value; case "minute": dateDifferences.second = value; case "second": dateDifferences.millisecond = value } }, correctDifferencesByMaxDate = function(differences, minDate, maxDate) { if (!maxDate.getMilliseconds() && maxDate.getSeconds()) { if (maxDate.getSeconds() - minDate.getSeconds() === 1) { differences.millisecond = true; differences.second = false } } else { if (!maxDate.getSeconds() && maxDate.getMinutes()) { if (maxDate.getMinutes() - minDate.getMinutes() === 1) { differences.second = true; differences.minute = false } } else { if (!maxDate.getMinutes() && maxDate.getHours()) { if (maxDate.getHours() - minDate.getHours() === 1) { differences.minute = true; differences.hour = false } } else { if (!maxDate.getHours() && maxDate.getDate() > 1) { if (maxDate.getDate() - minDate.getDate() === 1) { differences.hour = true; differences.day = false } } else { if (1 === maxDate.getDate() && maxDate.getMonth()) { if (maxDate.getMonth() - minDate.getMonth() === 1) { differences.day = true; differences.month = false } } else { if (!maxDate.getMonth() && maxDate.getFullYear()) { if (maxDate.getFullYear() - minDate.getFullYear() === 1) { differences.month = true; differences.year = false } } } } } } } }; tickInterval = commonUtils.isString(tickInterval) ? tickInterval.toLowerCase() : tickInterval; dateDifferences = dateUtils.getDatesDifferences(startValue, endValue); if (startValue !== endValue) { correctDifferencesByMaxDate(dateDifferences, startValue > endValue ? endValue : startValue, startValue > endValue ? startValue : endValue) } dateUnitInterval = dateUtils.getDateUnitInterval(dateDifferences); correctDateDifferences(dateDifferences, dateUnitInterval, true); dateUnitInterval = dateUtils.getDateUnitInterval(tickInterval || "second"); correctDateDifferences(dateDifferences, dateUnitInterval, false); dateDifferences[dateDifferencesConverter[dateUnitInterval] || dateUnitInterval] = true; resultFormat = this.getDateFormatByDifferences(dateDifferences); return resultFormat } }) }, /*!*****************************************!*\ !*** ./js/animation/presets/presets.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Component = __webpack_require__( /*! ../../core/component */ 48), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, devices = __webpack_require__( /*! ../../core/devices */ 53), fx = __webpack_require__( /*! ../fx */ 68); var directionPostfixes = { forward: " dx-forward", backward: " dx-backward", none: " dx-no-direction", undefined: " dx-no-direction" }; var optionPrefix = "preset_"; var AnimationPresetCollection = Component.inherit({ ctor: function() { this.callBase.apply(this, arguments); this._registeredPresets = []; this.resetToDefaults() }, _getDefaultOptions: function() { return extend(this.callBase(), { defaultAnimationDuration: 400, defaultAnimationDelay: 0, defaultStaggerAnimationDuration: 300, defaultStaggerAnimationDelay: 40, defaultStaggerAnimationStartDelay: 500 }) }, _defaultOptionsRules: function() { return this.callBase().concat([{ device: function(device) { return device.phone }, options: { defaultStaggerAnimationDuration: 350, defaultStaggerAnimationDelay: 50, defaultStaggerAnimationStartDelay: 0 } }, { device: function() { return devices.current().android || devices.real.android }, options: { defaultAnimationDelay: 100 } }]) }, _getPresetOptionName: function(animationName) { return optionPrefix + animationName }, _createAndroidSlideAnimationConfig: function(throughOpacity, widthMultiplier) { var that = this; var createBaseConfig = function(configModifier) { return { type: "slide", delay: void 0 === configModifier.delay ? that.option("defaultAnimationDelay") : configModifier.delay, duration: void 0 === configModifier.duration ? that.option("defaultAnimationDuration") : configModifier.duration } }; return { enter: function($element, configModifier) { var width = $element.parent().width() * widthMultiplier, direction = configModifier.direction, config = createBaseConfig(configModifier); config.to = { left: 0, opacity: 1 }; if ("forward" === direction) { config.from = { left: width, opacity: throughOpacity } } else { if ("backward" === direction) { config.from = { left: -width, opacity: throughOpacity } } else { config.from = { left: 0, opacity: 0 } } } return fx.createAnimation($element, config) }, leave: function($element, configModifier) { var width = $element.parent().width() * widthMultiplier, direction = configModifier.direction, config = createBaseConfig(configModifier); config.from = { left: 0, opacity: 1 }; if ("forward" === direction) { config.to = { left: -width, opacity: throughOpacity } } else { if ("backward" === direction) { config.to = { left: width, opacity: throughOpacity } } else { config.to = { left: 0, opacity: 0 } } } return fx.createAnimation($element, config) } } }, _createOpenDoorConfig: function() { var that = this; var createBaseConfig = function(configModifier) { return { type: "css", extraCssClasses: "dx-opendoor-animation", delay: void 0 === configModifier.delay ? that.option("defaultAnimationDelay") : configModifier.delay, duration: void 0 === configModifier.duration ? that.option("defaultAnimationDuration") : configModifier.duration } }; return { enter: function($element, configModifier) { var direction = configModifier.direction, config = createBaseConfig(configModifier); config.delay = "none" === direction ? config.delay : config.duration; config.from = "dx-enter dx-opendoor-animation" + directionPostfixes[direction]; config.to = "dx-enter-active"; return fx.createAnimation($element, config) }, leave: function($element, configModifier) { var direction = configModifier.direction, config = createBaseConfig(configModifier); config.from = "dx-leave dx-opendoor-animation" + directionPostfixes[direction]; config.to = "dx-leave-active"; return fx.createAnimation($element, config) } } }, _createWinPopConfig: function() { var that = this, baseConfig = { type: "css", extraCssClasses: "dx-win-pop-animation", duration: that.option("defaultAnimationDuration") }; return { enter: function($element, configModifier) { var config = baseConfig, direction = configModifier.direction; config.delay = "none" === direction ? that.option("defaultAnimationDelay") : that.option("defaultAnimationDuration") / 2; config.from = "dx-enter dx-win-pop-animation" + directionPostfixes[direction]; config.to = "dx-enter-active"; return fx.createAnimation($element, config) }, leave: function($element, configModifier) { var config = baseConfig, direction = configModifier.direction; config.delay = that.option("defaultAnimationDelay"); config.from = "dx-leave dx-win-pop-animation" + directionPostfixes[direction]; config.to = "dx-leave-active"; return fx.createAnimation($element, config) } } }, resetToDefaults: function() { this.clear(); this.registerDefaultPresets(); this.applyChanges() }, clear: function(name) { var that = this, newRegisteredPresets = []; $.each(this._registeredPresets, function(index, preset) { if (!name || name === preset.name) { that.option(that._getPresetOptionName(preset.name), void 0) } else { newRegisteredPresets.push(preset) } }); this._registeredPresets = newRegisteredPresets; this.applyChanges() }, registerPreset: function(name, config) { this._registeredPresets.push({ name: name, config: config }) }, applyChanges: function() { var that = this; var customRules = []; $.each(this._registeredPresets, function(index, preset) { var rule = { device: preset.config.device, options: {} }; rule.options[that._getPresetOptionName(preset.name)] = preset.config.animation; customRules.push(rule) }); this._setOptionsByDevice(customRules) }, getPreset: function(name) { var result = name; while ("string" === typeof result) { result = this.option(this._getPresetOptionName(result)) } return result }, registerDefaultPresets: function() { this.registerPreset("pop", { animation: { extraCssClasses: "dx-android-pop-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("openDoor", { animation: this._createOpenDoorConfig() }); this.registerPreset("win-pop", { animation: this._createWinPopConfig() }); this.registerPreset("fade", { animation: { extraCssClasses: "dx-fade-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("slide", { device: function() { return devices.current().android || devices.real.android }, animation: this._createAndroidSlideAnimationConfig(1, 1) }); this.registerPreset("slide", { device: function() { return !devices.current().android && !devices.real.android }, animation: { extraCssClasses: "dx-slide-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("ios7-slide", { animation: { extraCssClasses: "dx-ios7-slide-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("overflow", { animation: { extraCssClasses: "dx-overflow-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("ios7-toolbar", { device: function() { return !devices.current().android && !devices.real.android }, animation: { extraCssClasses: "dx-ios7-toolbar-animation", delay: this.option("defaultAnimationDelay"), duration: this.option("defaultAnimationDuration") } }); this.registerPreset("ios7-toolbar", { device: function() { return devices.current().android || devices.real.android }, animation: this._createAndroidSlideAnimationConfig(0, .4) }); this.registerPreset("stagger-fade", { animation: { extraCssClasses: "dx-fade-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-slide", { animation: { extraCssClasses: "dx-slide-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-fade-slide", { animation: { extraCssClasses: "dx-fade-slide-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-drop", { animation: { extraCssClasses: "dx-drop-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-fade-drop", { animation: { extraCssClasses: "dx-fade-drop-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-fade-rise", { animation: { extraCssClasses: "dx-fade-rise-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-3d-drop", { animation: { extraCssClasses: "dx-3d-drop-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }); this.registerPreset("stagger-fade-zoom", { animation: { extraCssClasses: "dx-fade-zoom-animation", staggerDelay: this.option("defaultStaggerAnimationDelay"), duration: this.option("defaultStaggerAnimationDuration"), delay: this.option("defaultStaggerAnimationStartDelay") } }) } }); exports.PresetCollection = AnimationPresetCollection; var animationPresets = new AnimationPresetCollection; exports.presets = animationPresets }, /*!****************************!*\ !*** ./js/animation/fx.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ../core/errors */ 7), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), translator = __webpack_require__( /*! ./translator */ 69), animationFrame = __webpack_require__( /*! ./frame */ 59), support = __webpack_require__( /*! ../core/utils/support */ 61), positionUtils = __webpack_require__( /*! ./position */ 70), removeEvent = __webpack_require__( /*! ../core/remove_event */ 47), eventUtils = __webpack_require__( /*! ../events/utils */ 71), when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when, transitionEndEventName = support.transitionEndEventName + ".dxFX", removeEventName = eventUtils.addNamespace(removeEvent, "dxFX"), isFunction = commonUtils.isFunction, isPlainObject = typeUtils.isPlainObject, noop = commonUtils.noop; var CSS_TRANSITION_EASING_REGEX = /cubic-bezier\((\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\)/, RELATIVE_VALUE_REGEX = /^([+-])=(.*)/i, ANIM_DATA_KEY = "dxAnimData", ANIM_QUEUE_KEY = "dxAnimQueue", TRANSFORM_PROP = "transform"; var TransitionAnimationStrategy = { initAnimation: function($element, config) { $element.css({ transitionProperty: "none" }); if ("string" === typeof config.from) { $element.addClass(config.from) } else { setProps($element, config.from) } var that = this, deferred = $.Deferred(), cleanupWhen = config.cleanupWhen; config.transitionAnimation = { deferred: deferred, finish: function() { that._finishTransition($element); if (cleanupWhen) { when(deferred, cleanupWhen).always(function() { that._cleanup($element, config) }) } else { that._cleanup($element, config) } deferred.resolveWith($element, [config, $element]) } }; this._completeAnimationCallback($element, config).done(function() { config.transitionAnimation.finish() }).fail(function() { deferred.rejectWith($element, [config, $element]) }); if (!config.duration) { config.transitionAnimation.finish() } $element.css("transform") }, animate: function($element, config) { this._startAnimation($element, config); return config.transitionAnimation.deferred.promise() }, _completeAnimationCallback: function($element, config) { var simulatedEndEventTimer, waitForJSCompleteTimer, that = this, startTime = $.now() + config.delay, deferred = $.Deferred(), transitionEndFired = $.Deferred(), simulatedTransitionEndFired = $.Deferred(); config.transitionAnimation.cleanup = function() { clearTimeout(simulatedEndEventTimer); clearTimeout(waitForJSCompleteTimer); $element.off(transitionEndEventName); $element.off(removeEventName) }; $element.one(transitionEndEventName, function() { if ($.now() - startTime >= config.duration) { transitionEndFired.reject() } }).off(removeEventName).on(removeEventName, function() { that.stop($element, config); deferred.reject() }); waitForJSCompleteTimer = setTimeout(function() { simulatedEndEventTimer = setTimeout(function() { simulatedTransitionEndFired.reject() }, config.duration + config.delay + fx._simulatedTransitionEndDelay); when(transitionEndFired, simulatedTransitionEndFired).fail(function() { deferred.resolve() }.bind(this)) }); return deferred.promise() }, _startAnimation: function($element, config) { $element.css({ transitionProperty: "all", transitionDelay: config.delay + "ms", transitionDuration: config.duration + "ms", transitionTimingFunction: config.easing }); if ("string" === typeof config.to) { $element[0].className += " " + config.to } else { if (config.to) { setProps($element, config.to) } } }, _finishTransition: function($element) { $element.css("transition", "none") }, _cleanup: function($element, config) { config.transitionAnimation.cleanup(); if ("string" === typeof config.from) { $element.removeClass(config.from); $element.removeClass(config.to) } }, stop: function($element, config, jumpToEnd) { if (!config) { return } if (jumpToEnd) { config.transitionAnimation.finish() } else { if (isPlainObject(config.to)) { $.each(config.to, function(key) { $element.css(key, $element.css(key)) }) } this._finishTransition($element); this._cleanup($element, config) } } }; var FrameAnimationStrategy = { initAnimation: function($element, config) { setProps($element, config.from) }, animate: function($element, config) { var deferred = $.Deferred(), that = this; if (!config) { return deferred.reject().promise() } $.each(config.to, function(prop) { if (void 0 === config.from[prop]) { config.from[prop] = that._normalizeValue($element.css(prop)) } }); if (config.to[TRANSFORM_PROP]) { config.from[TRANSFORM_PROP] = that._parseTransform(config.from[TRANSFORM_PROP]); config.to[TRANSFORM_PROP] = that._parseTransform(config.to[TRANSFORM_PROP]) } config.frameAnimation = { to: config.to, from: config.from, currentValue: config.from, easing: convertTransitionTimingFuncToJQueryEasing(config.easing), duration: config.duration, startTime: (new Date).valueOf(), finish: function() { this.currentValue = this.to; this.draw(); animationFrame.cancelAnimationFrame(config.frameAnimation.animationFrameId); deferred.resolve() }, draw: function() { if (config.draw) { config.draw(this.currentValue); return } var currentValue = extend({}, this.currentValue); if (currentValue[TRANSFORM_PROP]) { currentValue[TRANSFORM_PROP] = $.map(currentValue[TRANSFORM_PROP], function(value, prop) { if ("translate" === prop) { return translator.getTranslateCss(value) } else { if ("scale" === prop) { return "scale(" + value + ")" } else { if ("rotate" === prop.substr(0, prop.length - 1)) { return prop + "(" + value + "deg)" } } } }).join(" ") } $element.css(currentValue) } }; if (config.delay) { config.frameAnimation.startTime += config.delay; config.frameAnimation.delayTimeout = setTimeout(function() { that._startAnimation($element, config) }, config.delay) } else { that._startAnimation($element, config) } return deferred.promise() }, _startAnimation: function($element, config) { $element.off(removeEventName).on(removeEventName, function() { if (config.frameAnimation) { animationFrame.cancelAnimationFrame(config.frameAnimation.animationFrameId) } }); this._animationStep($element, config) }, _parseTransform: function(transformString) { var result = {}; $.each(transformString.match(/(\w|\d)+\([^\)]*\)\s*/g), function(i, part) { var translateData = translator.parseTranslate(part), scaleData = part.match(/scale\((.+?)\)/), rotateData = part.match(/(rotate.)\((.+)deg\)/); if (translateData) { result.translate = translateData } if (scaleData && scaleData[1]) { result.scale = parseFloat(scaleData[1]) } if (rotateData && rotateData[1]) { result[rotateData[1]] = parseFloat(rotateData[2]) } }); return result }, stop: function($element, config, jumpToEnd) { var frameAnimation = config && config.frameAnimation; if (!frameAnimation) { return } animationFrame.cancelAnimationFrame(frameAnimation.animationFrameId); clearTimeout(frameAnimation.delayTimeout); if (jumpToEnd) { frameAnimation.finish() } delete config.frameAnimation }, _animationStep: function($element, config) { var frameAnimation = config && config.frameAnimation; if (!frameAnimation) { return } var now = (new Date).valueOf(); if (now >= frameAnimation.startTime + frameAnimation.duration) { frameAnimation.finish(); return } frameAnimation.currentValue = this._calcStepValue(frameAnimation, now - frameAnimation.startTime); frameAnimation.draw(); var that = this; frameAnimation.animationFrameId = animationFrame.requestAnimationFrame(function() { that._animationStep($element, config) }) }, _calcStepValue: function(frameAnimation, currentDuration) { var calcValueRecursively = function(from, to) { var result = Array.isArray(to) ? [] : {}; var calcEasedValue = function(propName) { var x = currentDuration / frameAnimation.duration, t = currentDuration, b = 1 * from[propName], c = to[propName] - from[propName], d = frameAnimation.duration; return $.easing[frameAnimation.easing](x, t, b, c, d) }; $.each(to, function(propName, endPropValue) { if ("string" === typeof endPropValue && false === parseFloat(endPropValue, 10)) { return true } result[propName] = "object" === typeof endPropValue ? calcValueRecursively(from[propName], endPropValue) : calcEasedValue(propName) }); return result }; return calcValueRecursively(frameAnimation.from, frameAnimation.to) }, _normalizeValue: function(value) { var numericValue = parseFloat(value, 10); if (false === numericValue) { return value } return numericValue } }; var FallbackToNoAnimationStrategy = { initAnimation: function() {}, animate: function() { return $.Deferred().resolve().promise() }, stop: noop, isSynchronous: true }; var animationStrategies = { transition: support.transition ? TransitionAnimationStrategy : FrameAnimationStrategy, frame: FrameAnimationStrategy, noAnimation: FallbackToNoAnimationStrategy }; var getAnimationStrategy = function(config) { config = config || {}; var strategy = config.strategy || "transition"; if ("css" === config.type && !support.transition) { strategy = "noAnimation" } return animationStrategies[strategy] }; var TransitionTimingFuncMap = { linear: "cubic-bezier(0, 0, 1, 1)", ease: "cubic-bezier(0.25, 0.1, 0.25, 1)", "ease-in": "cubic-bezier(0.42, 0, 1, 1)", "ease-out": "cubic-bezier(0, 0, 0.58, 1)", "ease-in-out": "cubic-bezier(0.42, 0, 0.58, 1)" }; var convertTransitionTimingFuncToJQueryEasing = function(cssTransitionEasing) { cssTransitionEasing = TransitionTimingFuncMap[cssTransitionEasing] || cssTransitionEasing; var coeffs = cssTransitionEasing.match(CSS_TRANSITION_EASING_REGEX); if (!coeffs) { return "linear" } coeffs = coeffs.slice(1, 5); $.each(coeffs, function(index, value) { coeffs[index] = parseFloat(value) }); var easingName = "cubicbezier_" + coeffs.join("_").replace(/\./g, "p"); if (!isFunction($.easing[easingName])) { var polynomBezier = function(x1, y1, x2, y2) { var Cx = 3 * x1, Bx = 3 * (x2 - x1) - Cx, Ax = 1 - Cx - Bx, Cy = 3 * y1, By = 3 * (y2 - y1) - Cy, Ay = 1 - Cy - By; var bezierX = function(t) { return t * (Cx + t * (Bx + t * Ax)) }; var bezierY = function(t) { return t * (Cy + t * (By + t * Ay)) }; var findXFor = function(t) { var z, x = t, i = 0; while (i < 14) { z = bezierX(x) - t; if (Math.abs(z) < .001) { break } x -= z / derivativeX(x); i++ } return x }; var derivativeX = function(t) { return Cx + t * (2 * Bx + 3 * t * Ax) }; return function(t) { return bezierY(findXFor(t)) } }; $.easing[easingName] = function(x, t, b, c, d) { return c * polynomBezier(coeffs[0], coeffs[1], coeffs[2], coeffs[3])(t / d) + b } } return easingName }; var baseConfigValidator = function(config, animationType, validate, typeMessage) { $.each(["from", "to"], function() { if (!validate(config[this])) { throw errors.Error("E0010", animationType, this, typeMessage) } }) }; var isObjectConfigValidator = function(config, animationType) { return baseConfigValidator(config, animationType, function(target) { return isPlainObject(target) }, "a plain object") }; var isStringConfigValidator = function(config, animationType) { return baseConfigValidator(config, animationType, function(target) { return "string" === typeof target }, "a string") }; var CustomAnimationConfigurator = { setup: function() {} }; var CssAnimationConfigurator = { validateConfig: function(config) { isStringConfigValidator(config, "css") }, setup: function() {} }; var positionAliases = { top: { my: "bottom center", at: "top center" }, bottom: { my: "top center", at: "bottom center" }, right: { my: "left center", at: "right center" }, left: { my: "right center", at: "left center" } }; var SlideAnimationConfigurator = { validateConfig: function(config) { isObjectConfigValidator(config, "slide") }, setup: function($element, config) { var location = translator.locate($element); if ("slide" !== config.type) { var positioningConfig = "slideIn" === config.type ? config.from : config.to; positioningConfig.position = extend({ of: window }, positionAliases[config.direction]); setupPosition($element, positioningConfig) } this._setUpConfig(location, config.from); this._setUpConfig(location, config.to); translator.clearCache($element) }, _setUpConfig: function(location, config) { config.left = "left" in config ? config.left : "+=0"; config.top = "top" in config ? config.top : "+=0"; this._initNewPosition(location, config) }, _initNewPosition: function(location, config) { var position = { left: config.left, top: config.top }; delete config.left; delete config.top; var relativeValue = this._getRelativeValue(position.left); if (void 0 !== relativeValue) { position.left = relativeValue + location.left } else { config.left = 0 } relativeValue = this._getRelativeValue(position.top); if (void 0 !== relativeValue) { position.top = relativeValue + location.top } else { config.top = 0 } config[TRANSFORM_PROP] = translator.getTranslateCss({ x: position.left, y: position.top }) }, _getRelativeValue: function(value) { var relativeValue; if ("string" === typeof value && (relativeValue = RELATIVE_VALUE_REGEX.exec(value))) { return parseInt(relativeValue[1] + "1") * relativeValue[2] } } }; var FadeAnimationConfigurator = { setup: function($element, config) { var toOpacity, from = config.from, fromOpacity = isPlainObject(from) ? config.skipElementInitialStyles ? 0 : $element.css("opacity") : String(from); switch (config.type) { case "fadeIn": toOpacity = 1; break; case "fadeOut": toOpacity = 0; break; default: toOpacity = String(config.to) } config.from = { visibility: "visible", opacity: fromOpacity }; config.to = { opacity: toOpacity } } }; var PopAnimationConfigurator = { validateConfig: function(config) { isObjectConfigValidator(config, "pop") }, setup: function($element, config) { var from = config.from, to = config.to, fromOpacity = "opacity" in from ? from.opacity : $element.css("opacity"), toOpacity = "opacity" in to ? to.opacity : 1, fromScale = "scale" in from ? from.scale : 0, toScale = "scale" in to ? to.scale : 1; config.from = { opacity: fromOpacity }; var translate = translator.getTranslate($element); config.from[TRANSFORM_PROP] = this._getCssTransform(translate, fromScale); config.to = { opacity: toOpacity }; config.to[TRANSFORM_PROP] = this._getCssTransform(translate, toScale) }, _getCssTransform: function(translate, scale) { return translator.getTranslateCss(translate) + "scale(" + scale + ")" } }; var animationConfigurators = { custom: CustomAnimationConfigurator, slide: SlideAnimationConfigurator, slideIn: SlideAnimationConfigurator, slideOut: SlideAnimationConfigurator, fade: FadeAnimationConfigurator, fadeIn: FadeAnimationConfigurator, fadeOut: FadeAnimationConfigurator, pop: PopAnimationConfigurator, css: CssAnimationConfigurator }; var getAnimationConfigurator = function(config) { var result = animationConfigurators[config.type]; if (!result) { throw errors.Error("E0011", config.type) } return result }; var defaultJSConfig = { type: "custom", from: {}, to: {}, duration: 400, start: noop, complete: noop, easing: "ease", delay: 0 }, defaultCssConfig = { duration: 400, easing: "ease", delay: 0 }; var setupAnimationOnElement = function() { var animation = this, $element = animation.element, config = animation.config; setupPosition($element, config.from); setupPosition($element, config.to); animation.configurator.setup($element, config); $element.data(ANIM_DATA_KEY, animation); if (fx.off) { config.duration = 0; config.delay = 0 } animation.strategy.initAnimation($element, config); if (config.start) { config.start.apply(this, [$element, config]) } }; var onElementAnimationComplete = function(animation) { var $element = animation.element, config = animation.config; $element.removeData(ANIM_DATA_KEY); if (config.complete) { config.complete.apply(this, [$element, config]) } animation.deferred.resolveWith(this, [$element, config]) }; var startAnimationOnElement = function() { var animation = this, $element = animation.element, config = animation.config; animation.isStarted = true; return animation.strategy.animate($element, config).done(function() { onElementAnimationComplete(animation) }).fail(function() { animation.deferred.rejectWith(this, [$element, config]) }) }; var stopAnimationOnElement = function(jumpToEnd) { var animation = this, $element = animation.element, config = animation.config; clearTimeout(animation.startTimeout); if (!animation.isStarted) { animation.start() } animation.strategy.stop($element, config, jumpToEnd) }; var scopedRemoveEvent = eventUtils.addNamespace(removeEvent, "dxFXStartAnimation"); var subscribeToRemoveEvent = function(animation) { animation.element.off(scopedRemoveEvent).on(scopedRemoveEvent, function() { fx.stop(animation.element) }); animation.deferred.always(function() { animation.element.off(scopedRemoveEvent) }) }; var createAnimation = function(element, initialConfig) { var defaultConfig = "css" === initialConfig.type ? defaultCssConfig : defaultJSConfig, config = extend(true, {}, defaultConfig, initialConfig), configurator = getAnimationConfigurator(config), strategy = getAnimationStrategy(config), animation = { element: $(element), config: config, configurator: configurator, strategy: strategy, isSynchronous: strategy.isSynchronous, setup: setupAnimationOnElement, start: startAnimationOnElement, stop: stopAnimationOnElement, deferred: $.Deferred() }; if (isFunction(configurator.validateConfig)) { configurator.validateConfig(config) } subscribeToRemoveEvent(animation); return animation }; var animate = function(element, config) { var $element = $(element); if (!$element.length) { return $.Deferred().resolve().promise() } var animation = createAnimation($element, config); pushInAnimationQueue($element, animation); return animation.deferred.promise() }; var pushInAnimationQueue = function($element, animation) { var queueData = getAnimQueueData($element); writeAnimQueueData($element, queueData); queueData.push(animation); if (!isAnimating($element)) { shiftFromAnimationQueue($element, queueData) } }; var getAnimQueueData = function($element) { return $element.data(ANIM_QUEUE_KEY) || [] }; var writeAnimQueueData = function($element, queueData) { $element.data(ANIM_QUEUE_KEY, queueData) }; var destroyAnimQueueData = function($element) { $element.removeData(ANIM_QUEUE_KEY) }; var isAnimating = function($element) { return !!$element.data(ANIM_DATA_KEY) }; var shiftFromAnimationQueue = function($element, queueData) { queueData = getAnimQueueData($element); if (!queueData.length) { return } var animation = queueData.shift(); if (0 === queueData.length) { destroyAnimQueueData($element) } executeAnimation(animation).done(function() { if (!isAnimating($element)) { shiftFromAnimationQueue($element) } }) }; var executeAnimation = function(animation) { animation.setup(); if (fx.off || animation.isSynchronous) { animation.start() } else { animation.startTimeout = setTimeout(function() { animation.start() }) } return animation.deferred.promise() }; var setupPosition = function($element, config) { if (!config || !config.position) { return } var position = positionUtils.calculate($element, config.position), offset = $element.offset(), currentPosition = $element.position(); extend(config, { left: position.h.location - offset.left + currentPosition.left, top: position.v.location - offset.top + currentPosition.top }); delete config.position }; var setProps = function($element, props) { $.each(props, function(key, value) { try { $element.css(key, value) } catch (e) {} }) }; var stop = function(element, jumpToEnd) { var $element = $(element), queueData = getAnimQueueData($element); $.each(queueData, function(_, animation) { animation.config.delay = 0; animation.config.duration = 0; animation.isSynchronous = true }); if (!isAnimating($element)) { shiftFromAnimationQueue($element, queueData) } var animation = $element.data(ANIM_DATA_KEY); if (animation) { animation.stop(jumpToEnd) } $element.removeData(ANIM_DATA_KEY); destroyAnimQueueData($element) }; var fx = { off: false, animationTypes: animationConfigurators, animate: animate, createAnimation: createAnimation, isAnimating: isAnimating, stop: stop, _simulatedTransitionEndDelay: 100 }; fx.__internals = { convertTransitionTimingFuncToJQueryEasing: convertTransitionTimingFuncToJQueryEasing }; module.exports = fx }, /*!************************************!*\ !*** ./js/animation/translator.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), type = __webpack_require__( /*! ../core/utils/common */ 14).type; var TRANSLATOR_DATA_KEY = "dxTranslator", TRANSFORM_MATRIX_REGEX = /matrix(3d)?\((.+?)\)/, TRANSLATE_REGEX = /translate(?:3d)?\((.+?)\)/; var locate = function($element) { var translate = getTranslate($element); return { left: translate.x, top: translate.y } }; var move = function($element, position) { var translate, left = position.left, top = position.top; if (void 0 === left) { translate = getTranslate($element); translate.y = top || 0 } else { if (void 0 === top) { translate = getTranslate($element); translate.x = left || 0 } else { translate = { x: left || 0, y: top || 0, z: 0 }; cacheTranslate($element, translate) } } $element.css({ transform: getTranslateCss(translate) }); if (isPercentValue(left) || isPercentValue(top)) { clearCache($element) } }; var isPercentValue = function(value) { return "string" === type(value) && "%" === value[value.length - 1] }; var getTranslate = function($element) { var result = $element.length ? $.data($element.get(0), TRANSLATOR_DATA_KEY) : null; if (!result) { var transformValue = $element.css("transform") || getTranslateCss({ x: 0, y: 0 }), matrix = transformValue.match(TRANSFORM_MATRIX_REGEX), is3D = matrix && matrix[1]; if (matrix) { matrix = matrix[2].split(","); if ("3d" === is3D) { matrix = matrix.slice(12, 15) } else { matrix.push(0); matrix = matrix.slice(4, 7) } } else { matrix = [0, 0, 0] } result = { x: parseFloat(matrix[0]), y: parseFloat(matrix[1]), z: parseFloat(matrix[2]) }; cacheTranslate($element, result) } return result }; var cacheTranslate = function($element, translate) { if ($element.length) { $.data($element.get(0), TRANSLATOR_DATA_KEY, translate) } }; var clearCache = function($element) { if ($element.length) { $.removeData($element.get(0), TRANSLATOR_DATA_KEY) } }; var resetPosition = function($element) { $element.css({ left: 0, top: 0, transform: "none" }); clearCache($element) }; var parseTranslate = function(translateString) { var result = translateString.match(TRANSLATE_REGEX); if (!result || !result[1]) { return } result = result[1].split(","); result = { x: parseFloat(result[0]), y: parseFloat(result[1]), z: parseFloat(result[2]) }; return result }; var getTranslateCss = function(translate) { translate.x = translate.x || 0; translate.y = translate.y || 0; var xValueString = isPercentValue(translate.x) ? translate.x : translate.x + "px"; var yValueString = isPercentValue(translate.y) ? translate.y : translate.y + "px"; return "translate(" + xValueString + ", " + yValueString + ")" }; exports.move = move; exports.locate = locate; exports.clearCache = clearCache; exports.parseTranslate = parseTranslate; exports.getTranslate = getTranslate; exports.getTranslateCss = getTranslateCss; exports.resetPosition = resetPosition }, /*!**********************************!*\ !*** ./js/animation/position.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), stringUtils = __webpack_require__( /*! ../core/utils/string */ 18), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, translator = __webpack_require__( /*! ./translator */ 69), support = __webpack_require__( /*! ../core/utils/support */ 61); var horzRe = /left|right/, vertRe = /top|bottom/, collisionRe = /fit|flip|none/; var normalizeAlign = function(raw) { var result = { h: "center", v: "center" }; var pair = commonUtils.splitPair(raw); if (pair) { $.each(pair, function() { var w = String(this).toLowerCase(); if (horzRe.test(w)) { result.h = w } else { if (vertRe.test(w)) { result.v = w } } }) } return result }; var normalizeOffset = function(raw) { return stringUtils.pairToObject(raw) }; var normalizeCollision = function(raw) { var pair = commonUtils.splitPair(raw), h = String(pair && pair[0]).toLowerCase(), v = String(pair && pair[1]).toLowerCase(); if (!collisionRe.test(h)) { h = "none" } if (!collisionRe.test(v)) { v = h } return { h: h, v: v } }; var getAlignFactor = function(align) { switch (align) { case "center": return .5; case "right": case "bottom": return 1; default: return 0 } }; var inverseAlign = function(align) { switch (align) { case "left": return "right"; case "right": return "left"; case "top": return "bottom"; case "bottom": return "top"; default: return align } }; var calculateOversize = function(data, bounds) { var oversize = 0; if (data.myLocation < bounds.min) { oversize += bounds.min - data.myLocation } if (data.myLocation > bounds.max) { oversize += data.myLocation - bounds.max } return oversize }; var collisionSide = function(direction, data, bounds) { if (data.myLocation < bounds.min) { return "h" === direction ? "left" : "top" } if (data.myLocation > bounds.max) { return "h" === direction ? "right" : "bottom" } return "none" }; var initMyLocation = function(data) { data.myLocation = data.atLocation + getAlignFactor(data.atAlign) * data.atSize - getAlignFactor(data.myAlign) * data.mySize + data.offset }; var collisionResolvers = { fit: function(data, bounds) { var result = false; if (data.myLocation > bounds.max) { data.myLocation = bounds.max; result = true } if (data.myLocation < bounds.min) { data.myLocation = bounds.min; result = true } data.fit = result }, flip: function(data, bounds) { data.flip = false; if ("center" === data.myAlign && "center" === data.atAlign) { return } if (data.myLocation < bounds.min || data.myLocation > bounds.max) { var inverseData = extend({}, data, { myAlign: inverseAlign(data.myAlign), atAlign: inverseAlign(data.atAlign), offset: -data.offset }); initMyLocation(inverseData); inverseData.oversize = calculateOversize(inverseData, bounds); if (inverseData.myLocation >= bounds.min && inverseData.myLocation <= bounds.max || data.oversize > inverseData.oversize) { data.myLocation = inverseData.myLocation; data.oversize = inverseData.oversize; data.flip = true } } }, flipfit: function(data, bounds) { this.flip(data, bounds); this.fit(data, bounds) }, none: function(data) { data.oversize = 0 } }; var scrollbarWidth; var calculateScrollbarWidth = function() { var $scrollDiv = $("<div>").css({ width: 100, height: 100, overflow: "scroll", position: "absolute", top: -9999 }).appendTo($("body")), result = $scrollDiv.get(0).offsetWidth - $scrollDiv.get(0).clientWidth; $scrollDiv.remove(); scrollbarWidth = result }; var defaultPositionResult = { h: { location: 0, flip: false, fit: false, oversize: 0 }, v: { location: 0, flip: false, fit: false, oversize: 0 } }; var calculatePosition = function(what, options) { var $what = $(what), currentOffset = $what.offset(), result = extend(true, {}, defaultPositionResult, { h: { location: currentOffset.left }, v: { location: currentOffset.top } }); if (!options) { return result } var my = normalizeAlign(options.my), at = normalizeAlign(options.at), of = options.of || window, offset = normalizeOffset(options.offset), collision = normalizeCollision(options.collision), boundary = options.boundary, boundaryOffset = normalizeOffset(options.boundaryOffset); var h = { mySize: $what.outerWidth(), myAlign: my.h, atAlign: at.h, offset: offset.h, collision: collision.h, boundaryOffset: boundaryOffset.h }; var v = { mySize: $what.outerHeight(), myAlign: my.v, atAlign: at.v, offset: offset.v, collision: collision.v, boundaryOffset: boundaryOffset.v }; if ( of .preventDefault) { h.atLocation = of .pageX; v.atLocation = of .pageY; h.atSize = 0; v.atSize = 0 } else { of = $( of ); if (commonUtils.isWindow( of [0])) { h.atLocation = of .scrollLeft(); v.atLocation = of .scrollTop(); h.atSize = of [0].innerWidth > of [0].outerWidth ? of [0].innerWidth : of .width(); v.atSize = of [0].innerHeight > of [0].outerHeight ? of [0].innerHeight : of .height() } else { if (9 === of [0].nodeType) { h.atLocation = 0; v.atLocation = 0; h.atSize = of .width(); v.atSize = of .height() } else { var o = of .offset(); h.atLocation = o.left; v.atLocation = o.top; h.atSize = of .outerWidth(); v.atSize = of .outerHeight() } } } initMyLocation(h); initMyLocation(v); var bounds = function() { var win = $(window), windowWidth = win.width(), windowHeight = win.height(), left = win.scrollLeft(), top = win.scrollTop(), hScrollbar = document.width > document.documentElement.clientWidth, vScrollbar = document.height > document.documentElement.clientHeight, hZoomLevel = support.touch ? document.documentElement.clientWidth / (vScrollbar ? windowWidth - scrollbarWidth : windowWidth) : 1, vZoomLevel = support.touch ? document.documentElement.clientHeight / (hScrollbar ? windowHeight - scrollbarWidth : windowHeight) : 1; if (void 0 === scrollbarWidth) { calculateScrollbarWidth() } var boundaryWidth = windowWidth, boundaryHeight = windowHeight; if (boundary) { var $boundary = $(boundary), boundaryPosition = $boundary.offset(); left = boundaryPosition.left; top = boundaryPosition.top; boundaryWidth = $boundary.width(); boundaryHeight = $boundary.height() } return { h: { min: left + h.boundaryOffset, max: left + boundaryWidth / hZoomLevel - h.mySize - h.boundaryOffset }, v: { min: top + v.boundaryOffset, max: top + boundaryHeight / vZoomLevel - v.mySize - v.boundaryOffset } } }(); h.oversize = calculateOversize(h, bounds.h); v.oversize = calculateOversize(v, bounds.v); h.collisionSide = collisionSide("h", h, bounds.h); v.collisionSide = collisionSide("v", v, bounds.v); if (collisionResolvers[h.collision]) { collisionResolvers[h.collision](h, bounds.h) } if (collisionResolvers[v.collision]) { collisionResolvers[v.collision](v, bounds.v) } var preciser = function(number) { return options.precise ? number : Math.round(number) }; extend(true, result, { h: { location: preciser(h.myLocation), oversize: preciser(h.oversize), fit: h.fit, flip: h.flip, collisionSide: h.collisionSide }, v: { location: preciser(v.myLocation), oversize: preciser(v.oversize), fit: v.fit, flip: v.flip, collisionSide: v.collisionSide }, precise: options.precise }); return result }; var position = function(what, options) { var $what = $(what); if (!options) { return $what.offset() } translator.resetPosition($what); var offset = $what.offset(), targetPosition = options.h && options.v ? options : calculatePosition($what, options); var preciser = function(number) { return options.precise ? number : Math.round(number) }; translator.move($what, { left: targetPosition.h.location - preciser(offset.left), top: targetPosition.v.location - preciser(offset.top) }); return targetPosition }; var offset = function(element) { element = $(element).get(0); if (commonUtils.isWindow(element)) { return null } else { if (element instanceof $.Event) { return { top: element.pageY, left: element.pageX } } } return $(element).offset() }; if (!position.inverseAlign) { position.inverseAlign = inverseAlign } if (!position.normalizeAlign) { position.normalizeAlign = normalizeAlign } module.exports = { calculateScrollbarWidth: calculateScrollbarWidth, calculate: calculatePosition, setup: position, offset: offset } }, /*!****************************!*\ !*** ./js/events/utils.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ../core/errors */ 7), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, copyEvent = __webpack_require__( /*! ./core/hooks */ 72).copy; var eventSource = function() { var EVENT_SOURCES_REGEX = { dx: /^dx/i, mouse: /(mouse|wheel)/i, touch: /^touch/i, keyboard: /^key/i, pointer: /^(ms)?pointer/i }; return function(e) { var result = "other"; $.each(EVENT_SOURCES_REGEX, function(key) { if (this.test(e.type)) { result = key; return false } }); return result } }(); var isDxEvent = function(e) { return "dx" === eventSource(e) }; var isNativeMouseEvent = function(e) { return "mouse" === eventSource(e) }; var isNativeTouchEvent = function(e) { return "touch" === eventSource(e) }; var isPointerEvent = function(e) { return "pointer" === eventSource(e) }; var isMouseEvent = function(e) { return isNativeMouseEvent(e) || (isPointerEvent(e) || isDxEvent(e)) && "mouse" === e.pointerType }; var isTouchEvent = function(e) { return isNativeTouchEvent(e) || (isPointerEvent(e) || isDxEvent(e)) && "touch" === e.pointerType }; var isKeyboardEvent = function(e) { return "keyboard" === eventSource(e) }; var isFakeClickEvent = function(e) { return 0 === e.screenX && !e.offsetX && 0 === e.pageX }; var eventData = function(e) { return { x: e.pageX, y: e.pageY, time: e.timeStamp } }; var eventDelta = function(from, to) { return { x: to.x - from.x, y: to.y - from.y, time: to.time - from.time || 1 } }; var hasTouches = function(e) { if (isNativeTouchEvent(e)) { return (e.originalEvent.touches || []).length } if (isDxEvent(e)) { return (e.pointers || []).length } return 0 }; var needSkipEvent = function(e) { var $target = $(e.target), touchInInput = $target.is("input, textarea, select"); if ($target.is(".dx-skip-gesture-event *, .dx-skip-gesture-event")) { return true } if ("dxmousewheel" === e.type) { return $target.is("input[type='number'], textarea, select") && $target.is(":focus") } if (isMouseEvent(e)) { return touchInInput || e.which > 1 } if (isTouchEvent(e)) { return touchInInput && $target.is(":focus") } }; var createEvent = function(originalEvent, args) { var event = copyEvent(originalEvent); if (args) { extend(event, args) } return event }; var fireEvent = function(props) { var event = createEvent(props.originalEvent, props); $.event.trigger(event, null, props.delegateTarget || event.target); return event }; var addNamespace = function(eventNames, namespace) { if (!namespace) { throw errors.Error("E0017") } if ("string" === typeof eventNames) { if (eventNames.indexOf(" ") === -1) { return eventNames + "." + namespace } return addNamespace(eventNames.split(/\s+/g), namespace) } $.each(eventNames, function(index, eventName) { eventNames[index] = eventName + "." + namespace }); return eventNames.join(" ") }; module.exports = { eventSource: eventSource, isPointerEvent: isPointerEvent, isMouseEvent: isMouseEvent, isTouchEvent: isTouchEvent, isKeyboardEvent: isKeyboardEvent, isFakeClickEvent: isFakeClickEvent, hasTouches: hasTouches, eventData: eventData, eventDelta: eventDelta, needSkipEvent: needSkipEvent, createEvent: createEvent, fireEvent: fireEvent, addNamespace: addNamespace } }, /*!*********************************!*\ !*** ./js/events/core/hooks.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), compareVersion = __webpack_require__( /*! ../../core/utils/version */ 17).compare, isNumeric = __webpack_require__( /*! ../../core/utils/common */ 14).isNumeric, registerEvent = __webpack_require__( /*! ./event_registrator */ 73); var touchPropsToHook = ["pageX", "pageY", "screenX", "screenY", "clientX", "clientY"]; var touchPropHook = function(name, event) { if (event[name] || !event.touches) { return event[name] } var touches = event.touches.length ? event.touches : event.changedTouches; if (!touches.length) { return } return touches[0][name] }; if (compareVersion($.fn.jquery, [3]) < 0) { var POINTER_TYPE_MAP = { 2: "touch", 3: "pen", 4: "mouse" }; $.each(["MSPointerDown", "MSPointerMove", "MSPointerUp", "MSPointerCancel", "MSPointerOver", "MSPointerOut", "mouseenter", "mouseleave", "pointerdown", "pointermove", "pointerup", "pointercancel", "pointerover", "pointerout", "pointerenter", "pointerleave"], function() { $.event.fixHooks[this] = { filter: function(event, originalEvent) { var pointerType = originalEvent.pointerType; if (isNumeric(pointerType)) { event.pointerType = POINTER_TYPE_MAP[pointerType] } return event }, props: $.event.mouseHooks.props.concat(["pointerId", "pointerType", "originalTarget", "width", "height", "pressure", "result", "tiltX", "charCode", "tiltY", "detail", "isPrimary", "prevValue"]) } }); $.each(["touchstart", "touchmove", "touchend", "touchcancel"], function() { $.event.fixHooks[this] = { filter: function(event, originalEvent) { $.each(touchPropsToHook, function(_, name) { event[name] = touchPropHook(name, originalEvent) }); return event }, props: $.event.mouseHooks.props.concat(["touches", "changedTouches", "targetTouches", "detail", "result", "originalTarget", "charCode", "prevValue"]) } }); $.event.fixHooks.wheel = $.event.mouseHooks; var DX_EVENT_HOOKS = { props: $.event.mouseHooks.props.concat(["pointerType", "pointerId", "pointers"]) }; registerEvent.callbacks.add(function(name) { $.event.fixHooks[name] = DX_EVENT_HOOKS }); var fix = function(event) { var originalEvent = event.originalEvent; var fixHook = $.event.fixHooks[originalEvent.type] || $.event.mouseHooks; var props = fixHook.props ? $.event.props.concat(fixHook.props) : $.event.props, propIndex = props.length; while (propIndex--) { var prop = props[propIndex]; event[prop] = originalEvent[prop] } return fixHook.filter ? fixHook.filter(event, originalEvent) : event }; exports.copy = function(originalEvent) { return fix($.Event(originalEvent)) } } else { $.each(touchPropsToHook, function(_, name) { $.event.addProp(name, function(event) { return touchPropHook(name, event) }) }); exports.copy = function(originalEvent) { return $.Event(originalEvent, originalEvent) } } }, /*!*********************************************!*\ !*** ./js/events/core/event_registrator.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), MemorizedCallbacks = __webpack_require__( /*! ../../core/memorized_callbacks */ 58); var callbacks = new MemorizedCallbacks; var registerEvent = function(name, eventObject) { var strategy = {}; if ("noBubble" in eventObject) { strategy.noBubble = eventObject.noBubble } if ("bindType" in eventObject) { strategy.bindType = eventObject.bindType } if ("delegateType" in eventObject) { strategy.delegateType = eventObject.delegateType } $.each(["setup", "teardown", "add", "remove", "trigger", "handle", "_default", "dispose"], function(_, methodName) { if (!eventObject[methodName]) { return } strategy[methodName] = function() { var args = $.makeArray(arguments); args.unshift(this); return eventObject[methodName].apply(eventObject, args) } }); callbacks.fire(name, strategy) }; registerEvent.callbacks = callbacks; var registerJQueryEvent = function(name, eventObject) { $.event.special[name] = eventObject }; callbacks.add(registerJQueryEvent); module.exports = registerEvent }, /*!*****************************************************************!*\ !*** ./js/animation/transition_executor/transition_executor.js ***! \*****************************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), fx = __webpack_require__( /*! ../fx */ 68), animationPresetsModule = __webpack_require__( /*! ../presets/presets */ 67), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; var directionPostfixes = { forward: " dx-forward", backward: " dx-backward", none: " dx-no-direction", undefined: " dx-no-direction" }, DX_ANIMATING_CLASS = "dx-animating"; var TransitionExecutor = Class.inherit({ ctor: function() { this._accumulatedDelays = { enter: 0, leave: 0 }; this._animations = []; this.reset() }, _createAnimations: function($elements, initialConfig, configModifier, type) { var animationConfig, that = this, result = []; configModifier = configModifier || {}; animationConfig = this._prepareElementAnimationConfig(initialConfig, configModifier, type); if (animationConfig) { $elements.each(function() { var animation = that._createAnimation($(this), animationConfig, configModifier); if (animation) { animation.element.addClass(DX_ANIMATING_CLASS); animation.setup(); result.push(animation) } }) } return result }, _prepareElementAnimationConfig: function(config, configModifier, type) { var result; if ("string" === typeof config) { var presetName = config; config = animationPresetsModule.presets.getPreset(presetName) } if (!config) { result = void 0 } else { if (commonUtils.isFunction(config[type])) { result = config[type] } else { result = extend({ skipElementInitialStyles: true, cleanupWhen: this._completePromise }, config, configModifier); if (!result.type || "css" === result.type) { var cssClass = "dx-" + type, extraCssClasses = (result.extraCssClasses ? " " + result.extraCssClasses : "") + directionPostfixes[result.direction]; result.type = "css"; result.from = (result.from || cssClass) + extraCssClasses; result.to = result.to || cssClass + "-active" } result.staggerDelay = result.staggerDelay || 0; result.delay = result.delay || 0; if (result.staggerDelay) { result.delay += this._accumulatedDelays[type]; this._accumulatedDelays[type] += result.staggerDelay } } } return result }, _createAnimation: function($element, animationConfig, configModifier) { var result; if (typeUtils.isPlainObject(animationConfig)) { result = fx.createAnimation($element, animationConfig) } else { if (commonUtils.isFunction(animationConfig)) { result = animationConfig($element, configModifier) } } return result }, _startAnimations: function() { var animations = this._animations; for (var i = 0; i < animations.length; i++) { animations[i].start() } }, _stopAnimations: function(jumpToEnd) { var animations = this._animations; for (var i = 0; i < animations.length; i++) { animations[i].stop(jumpToEnd) } }, _clearAnimations: function() { var animations = this._animations; for (var i = 0; i < animations.length; i++) { animations[i].element.removeClass(DX_ANIMATING_CLASS) } this._animations.length = 0 }, reset: function() { this._accumulatedDelays.enter = 0; this._accumulatedDelays.leave = 0; this._clearAnimations(); this._completeDeferred = $.Deferred(); this._completePromise = this._completeDeferred.promise() }, enter: function($elements, animationConfig, configModifier) { var animations = this._createAnimations($elements, animationConfig, configModifier, "enter"); this._animations.push.apply(this._animations, animations) }, leave: function($elements, animationConfig, configModifier) { var animations = this._createAnimations($elements, animationConfig, configModifier, "leave"); this._animations.push.apply(this._animations, animations) }, start: function() { var result, that = this; if (!this._animations.length) { that.reset(); result = $.Deferred().resolve().promise() } else { var animationDeferreds = $.map(this._animations, function(animation) { var result = $.Deferred(); animation.deferred.always(function() { result.resolve() }); return result.promise() }); result = when.apply($, animationDeferreds).always(function() { that._completeDeferred.resolve(); that.reset() }); commonUtils.executeAsync(function() { that._startAnimations() }) } return result }, stop: function(jumpToEnd) { this._stopAnimations(jumpToEnd) } }); exports.TransitionExecutor = TransitionExecutor }, /*!****************************!*\ !*** ./js/events/click.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), devices = __webpack_require__( /*! ../core/devices */ 53), domUtils = __webpack_require__( /*! ../core/utils/dom */ 56), animationFrame = __webpack_require__( /*! ../animation/frame */ 59), eventUtils = __webpack_require__( /*! ./utils */ 71), pointerEvents = __webpack_require__( /*! ./pointer */ 76), Emitter = __webpack_require__( /*! ./core/emitter */ 83), registerEmitter = __webpack_require__( /*! ./core/emitter_registrator */ 84), compareVersions = __webpack_require__( /*! ../core/utils/version */ 17).compare; var CLICK_EVENT_NAME = "dxclick", TOUCH_BOUNDARY = 10, abs = Math.abs; var isInput = function(element) { return $(element).is("input, textarea, select, button ,:focus, :focus *") }; var misc = { requestAnimationFrame: animationFrame.requestAnimationFrame, cancelAnimationFrame: animationFrame.cancelAnimationFrame }; var ClickEmitter = Emitter.inherit({ ctor: function(element) { this.callBase(element); this._makeElementClickable($(element)) }, _makeElementClickable: function($element) { if (!$element.attr("onclick")) { $element.attr("onclick", "void(0)") } }, start: function(e) { this._blurPrevented = e.isDefaultPrevented(); this._startTarget = e.target; this._startEventData = eventUtils.eventData(e) }, end: function(e) { if (this._eventOutOfElement(e, this.getElement().get(0)) || e.type === pointerEvents.cancel) { this._cancel(e); return } if (!isInput(e.target) && !this._blurPrevented) { domUtils.resetActiveElement() } this._accept(e); this._clickAnimationFrame = misc.requestAnimationFrame(function() { this._fireClickEvent(e) }.bind(this)) }, _eventOutOfElement: function(e, element) { var target = e.target, targetChanged = !$.contains(element, target) && element !== target, gestureDelta = eventUtils.eventDelta(eventUtils.eventData(e), this._startEventData), boundsExceeded = abs(gestureDelta.x) > TOUCH_BOUNDARY || abs(gestureDelta.y) > TOUCH_BOUNDARY; return targetChanged || boundsExceeded }, _fireClickEvent: function(e) { this._fireEvent(CLICK_EVENT_NAME, e, { target: domUtils.closestCommonParent(this._startTarget, e.target) }) }, dispose: function() { misc.cancelAnimationFrame(this._clickAnimationFrame) } }); ! function() { var NATIVE_CLICK_CLASS = "dx-native-click"; var realDevice = devices.real(), useNativeClick = realDevice.generic || realDevice.ios && compareVersions(realDevice.version, [9, 3]) >= 0 || realDevice.android && compareVersions(realDevice.version, [5]) >= 0; var isNativeClickEvent = function(target) { return useNativeClick || $(target).closest("." + NATIVE_CLICK_CLASS).length }; var prevented = null, lastFiredEvent = null; var clickHandler = function(e) { var originalEvent = e.originalEvent, eventAlreadyFired = lastFiredEvent !== originalEvent, leftButton = !e.which || 1 === e.which; if (leftButton && !prevented && isNativeClickEvent(e.target) && eventAlreadyFired) { lastFiredEvent = originalEvent; eventUtils.fireEvent({ type: CLICK_EVENT_NAME, originalEvent: e }) } }; ClickEmitter = ClickEmitter.inherit({ _makeElementClickable: function($element) { if (!isNativeClickEvent($element)) { this.callBase($element) } $element.on("click", clickHandler) }, configure: function(data) { this.callBase(data); if (data.useNative) { this.getElement().addClass(NATIVE_CLICK_CLASS) } }, start: function(e) { prevented = null; if (!isNativeClickEvent(e.target)) { this.callBase(e) } }, end: function(e) { if (!isNativeClickEvent(e.target)) { this.callBase(e) } }, cancel: function() { prevented = true }, dispose: function() { this.callBase(); this.getElement().off("click", clickHandler) } }); exports.useNativeClick = useNativeClick }(); ! function() { var desktopDevice = devices.real().generic; if (!desktopDevice) { var startTarget = null, blurPrevented = false; var pointerDownHandler = function(e) { startTarget = e.target; blurPrevented = e.isDefaultPrevented() }; var clickHandler = function(e) { var $target = $(e.target); if (!blurPrevented && startTarget && !$target.is(startTarget) && !$(startTarget).is("label") && isInput($target)) { domUtils.resetActiveElement() } startTarget = null; blurPrevented = false }; var NATIVE_CLICK_FIXER_NAMESPACE = "NATIVE_CLICK_FIXER"; $(document).on(eventUtils.addNamespace(pointerEvents.down, NATIVE_CLICK_FIXER_NAMESPACE), pointerDownHandler).on(eventUtils.addNamespace("click", NATIVE_CLICK_FIXER_NAMESPACE), clickHandler) } }(); registerEmitter({ emitter: ClickEmitter, bubble: true, events: [CLICK_EVENT_NAME] }); exports.name = CLICK_EVENT_NAME; exports.misc = misc }, /*!******************************!*\ !*** ./js/events/pointer.js ***! \******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), support = __webpack_require__( /*! ../core/utils/support */ 61), devices = __webpack_require__( /*! ../core/devices */ 53), registerEvent = __webpack_require__( /*! ./core/event_registrator */ 73), TouchStrategy = __webpack_require__( /*! ./pointer/touch */ 77), MsPointerStrategy = __webpack_require__( /*! ./pointer/mspointer */ 79), MouseStrategy = __webpack_require__( /*! ./pointer/mouse */ 81), MouseAndTouchStrategy = __webpack_require__( /*! ./pointer/mouse_and_touch */ 82); var EventStrategy = function() { if (support.pointerEvents) { return MsPointerStrategy } var device = devices.real(); if (support.touch && !(device.tablet || device.phone)) { return MouseAndTouchStrategy } if (support.touch) { return TouchStrategy } return MouseStrategy }(); $.each(EventStrategy.map, function(pointerEvent, originalEvents) { registerEvent(pointerEvent, new EventStrategy(pointerEvent, originalEvents)) }); module.exports = { down: "dxpointerdown", up: "dxpointerup", move: "dxpointermove", cancel: "dxpointercancel", enter: "dxpointerenter", leave: "dxpointerleave", over: "dxpointerover", out: "dxpointerout" } }, /*!************************************!*\ !*** ./js/events/pointer/touch.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), devices = __webpack_require__( /*! ../../core/devices */ 53), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, BaseStrategy = __webpack_require__( /*! ./base */ 78); var eventMap = { dxpointerdown: "touchstart", dxpointermove: "touchmove", dxpointerup: "touchend", dxpointercancel: "touchcancel", dxpointerover: "", dxpointerout: "", dxpointerenter: "", dxpointerleave: "" }; var normalizeTouchEvent = function(e) { var pointers = []; $.each(e.touches, function(_, touch) { pointers.push(extend({ pointerId: touch.identifier }, touch)) }); return { pointers: pointers, pointerId: e.changedTouches[0].identifier } }; var skipTouchWithSameIdentifier = function(pointerEvent) { return "ios" === devices.real().platform && ("dxpointerdown" === pointerEvent || "dxpointerup" === pointerEvent) }; var TouchStrategy = BaseStrategy.inherit({ ctor: function() { this.callBase.apply(this, arguments); this._pointerId = 0 }, _handler: function(e) { if (skipTouchWithSameIdentifier(this._eventName)) { var touch = e.changedTouches[0]; if (this._pointerId === touch.identifier && 0 !== this._pointerId) { return } this._pointerId = touch.identifier } return this.callBase.apply(this, arguments) }, _fireEvent: function(args) { return this.callBase(extend(normalizeTouchEvent(args.originalEvent), args)) } }); TouchStrategy.map = eventMap; TouchStrategy.normalize = normalizeTouchEvent; module.exports = TouchStrategy }, /*!***********************************!*\ !*** ./js/events/pointer/base.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), browser = __webpack_require__( /*! ../../core/utils/browser */ 23), Class = __webpack_require__( /*! ../../core/class */ 25), eventUtils = __webpack_require__( /*! ../utils */ 71); var POINTER_EVENTS_NAMESPACE = "dxPointerEvents"; var BaseStrategy = Class.inherit({ ctor: function(eventName, originalEvents) { this._eventName = eventName; this._originalEvents = eventUtils.addNamespace(originalEvents, POINTER_EVENTS_NAMESPACE); this._handlerCount = 0; this.noBubble = this._isNoBubble() }, _isNoBubble: function() { var eventName = this._eventName; return "dxpointerenter" === eventName || "dxpointerleave" === eventName }, _handler: function(e) { var delegateTarget = this._getDelegateTarget(e); return this._fireEvent({ type: this._eventName, pointerType: e.pointerType || eventUtils.eventSource(e), originalEvent: e, delegateTarget: delegateTarget, timeStamp: browser.mozilla ? (new Date).getTime() : e.timeStamp }) }, _getDelegateTarget: function(e) { var delegateTarget; if (this.noBubble) { delegateTarget = e.delegateTarget } return delegateTarget }, _fireEvent: function(args) { return eventUtils.fireEvent(args) }, setup: function() { return true }, add: function(element, handleObj) { if (this._handlerCount <= 0 || this.noBubble) { this._selector = handleObj.selector; element = this.noBubble ? element : document; var that = this; $(element).on(this._originalEvents, this._selector, function(e) { that._handler(e) }) } if (!this.noBubble) { this._handlerCount++ } }, remove: function() { if (!this.noBubble) { this._handlerCount-- } }, teardown: function(element) { if (this._handlerCount && !this.noBubble) { return } element = this.noBubble ? element : document; if (this._originalEvents !== "." + POINTER_EVENTS_NAMESPACE) { $(element).off(this._originalEvents, this._selector) } }, dispose: function(element) { element = this.noBubble ? element : document; $(element).off(this._originalEvents) } }); module.exports = BaseStrategy }, /*!****************************************!*\ !*** ./js/events/pointer/mspointer.js ***! \****************************************/ function(module, exports, __webpack_require__) { var BaseStrategy = __webpack_require__( /*! ./base */ 78), Observer = __webpack_require__( /*! ./observer */ 80), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, onlyMSPointerSupport = !window.PointerEvent && window.MSPointerEvent; var eventMap = { dxpointerdown: onlyMSPointerSupport ? "MSPointerDown" : "pointerdown", dxpointermove: onlyMSPointerSupport ? "MSPointerMove" : "pointermove", dxpointerup: onlyMSPointerSupport ? "MSPointerUp" : "pointerup", dxpointercancel: onlyMSPointerSupport ? "MSPointerCancel" : "pointercancel", dxpointerover: onlyMSPointerSupport ? "MSPointerOver" : "pointerover", dxpointerout: onlyMSPointerSupport ? "MSPointerOut" : "pointerout", dxpointerenter: onlyMSPointerSupport ? "mouseenter" : "pointerenter", dxpointerleave: onlyMSPointerSupport ? "mouseleave" : "pointerleave" }; var observer; var activated = false; var activateStrategy = function() { if (activated) { return } observer = new Observer(eventMap, function(a, b) { return a.pointerId === b.pointerId }, function(e) { if (e.isPrimary) { observer.reset() } }); activated = true }; var MsPointerStrategy = BaseStrategy.inherit({ ctor: function() { this.callBase.apply(this, arguments); activateStrategy() }, _fireEvent: function(args) { return this.callBase(extend({ pointers: observer.pointers(), pointerId: args.originalEvent.pointerId }, args)) } }); MsPointerStrategy.map = eventMap; MsPointerStrategy.resetObserver = function() { observer.reset() }; module.exports = MsPointerStrategy }, /*!***************************************!*\ !*** ./js/events/pointer/observer.js ***! \***************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var addEventsListener = function(events, handler) { events.split(" ").forEach(function(event) { document.addEventListener(event, handler, true) }) }; var Observer = function(eventMap, pointerEquals, onPointerAdding) { onPointerAdding = onPointerAdding || function() {}; var pointers = []; var getPointerIndex = function(e) { var index = -1; $.each(pointers, function(i, pointer) { if (!pointerEquals(e, pointer)) { return true } index = i; return false }); return index }; var addPointer = function(e) { if (getPointerIndex(e) === -1) { onPointerAdding(e); pointers.push(e) } }; var removePointer = function(e) { var index = getPointerIndex(e); if (index > -1) { pointers.splice(index, 1) } }; var updatePointer = function(e) { pointers[getPointerIndex(e)] = e }; addEventsListener(eventMap.dxpointerdown, addPointer); addEventsListener(eventMap.dxpointermove, updatePointer); addEventsListener(eventMap.dxpointerup, removePointer); addEventsListener(eventMap.dxpointercancel, removePointer); this.pointers = function() { return pointers }; this.reset = function() { pointers = [] } }; module.exports = Observer }, /*!************************************!*\ !*** ./js/events/pointer/mouse.js ***! \************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, BaseStrategy = __webpack_require__( /*! ./base */ 78), Observer = __webpack_require__( /*! ./observer */ 80); var eventMap = { dxpointerdown: "mousedown", dxpointermove: "mousemove", dxpointerup: "mouseup", dxpointercancel: "", dxpointerover: "mouseover", dxpointerout: "mouseout", dxpointerenter: "mouseenter", dxpointerleave: "mouseleave" }; var normalizeMouseEvent = function(e) { e.pointerId = 1; return { pointers: observer.pointers(), pointerId: 1 } }; var observer; var activated = false; var activateStrategy = function() { if (activated) { return } observer = new Observer(eventMap, function() { return true }); activated = true }; var MouseStrategy = BaseStrategy.inherit({ ctor: function() { this.callBase.apply(this, arguments); activateStrategy() }, _fireEvent: function(args) { return this.callBase(extend(normalizeMouseEvent(args.originalEvent), args)) } }); MouseStrategy.map = eventMap; MouseStrategy.normalize = normalizeMouseEvent; MouseStrategy.activate = activateStrategy; MouseStrategy.resetObserver = function() { observer.reset() }; module.exports = MouseStrategy }, /*!**********************************************!*\ !*** ./js/events/pointer/mouse_and_touch.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, BaseStrategy = __webpack_require__( /*! ./base */ 78), MouseStrategy = __webpack_require__( /*! ./mouse */ 81), TouchStrategy = __webpack_require__( /*! ./touch */ 77), eventUtils = __webpack_require__( /*! ../utils */ 71); var eventMap = { dxpointerdown: "touchstart mousedown", dxpointermove: "touchmove mousemove", dxpointerup: "touchend mouseup", dxpointercancel: "touchcancel", dxpointerover: "mouseover", dxpointerout: "mouseout", dxpointerenter: "mouseenter", dxpointerleave: "mouseleave" }; var activated = false; var activateStrategy = function() { if (activated) { return } MouseStrategy.activate(); activated = true }; var MouseAndTouchStrategy = BaseStrategy.inherit({ EVENT_LOCK_TIMEOUT: 100, ctor: function() { this.callBase.apply(this, arguments); activateStrategy() }, _handler: function(e) { var isMouseEvent = eventUtils.isMouseEvent(e); if (!isMouseEvent) { this._skipNextEvents = true } if (isMouseEvent && this._mouseLocked) { return } if (isMouseEvent && this._skipNextEvents) { this._skipNextEvents = false; this._mouseLocked = true; clearTimeout(this._unlockMouseTimer); var that = this; this._unlockMouseTimer = setTimeout(function() { that._mouseLocked = false }, this.EVENT_LOCK_TIMEOUT); return } return this.callBase(e) }, _fireEvent: function(args) { var isMouseEvent = eventUtils.isMouseEvent(args.originalEvent), normalizer = isMouseEvent ? MouseStrategy.normalize : TouchStrategy.normalize; return this.callBase(extend(normalizer(args.originalEvent), args)) }, dispose: function() { this.callBase(); this._skipNextEvents = false; this._mouseLocked = false; clearTimeout(this._unlockMouseTimer) } }); MouseAndTouchStrategy.map = eventMap; MouseAndTouchStrategy.resetObserver = MouseStrategy.resetObserver; module.exports = MouseAndTouchStrategy }, /*!***********************************!*\ !*** ./js/events/core/emitter.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, eventUtils = __webpack_require__( /*! ../utils */ 71); var Emitter = Class.inherit({ ctor: function(element) { this._$element = $(element); this._cancelCallback = $.Callbacks(); this._acceptCallback = $.Callbacks() }, getElement: function() { return this._$element }, validate: function(e) { return "dxmousewheel" !== e.type }, validatePointers: function(e) { return 1 === eventUtils.hasTouches(e) }, allowInterruptionByMouseWheel: function() { return true }, configure: function(data) { extend(this, data) }, addCancelCallback: function(callback) { this._cancelCallback.add(callback) }, removeCancelCallback: function() { this._cancelCallback.empty() }, _cancel: function(e) { this._cancelCallback.fire(this, e) }, addAcceptCallback: function(callback) { this._acceptCallback.add(callback) }, removeAcceptCallback: function() { this._acceptCallback.empty() }, _accept: function(e) { this._acceptCallback.fire(this, e) }, _requestAccept: function(e) { this._acceptRequestEvent = e }, _forgetAccept: function() { this._accept(this._acceptRequestEvent); this._acceptRequestEvent = null }, start: noop, move: noop, end: noop, cancel: noop, reset: function() { if (this._acceptRequestEvent) { this._accept(this._acceptRequestEvent) } }, _fireEvent: function(eventName, e, params) { var eventData = extend({ type: eventName, originalEvent: e, target: this._getEmitterTarget(e), delegateTarget: this.getElement().get(0) }, params); e = eventUtils.fireEvent(eventData); if (e.cancel) { this._cancel(e) } return e }, _getEmitterTarget: function(e) { return (this.delegateSelector ? $(e.target).closest(this.delegateSelector) : this.getElement()).get(0) }, dispose: noop }); module.exports = Emitter }, /*!***********************************************!*\ !*** ./js/events/core/emitter_registrator.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, registerEvent = __webpack_require__( /*! ./event_registrator */ 73), eventUtils = __webpack_require__( /*! ../utils */ 71), pointerEvents = __webpack_require__( /*! ../pointer */ 76), wheelEvent = __webpack_require__( /*! ./wheel */ 85); var MANAGER_EVENT = "dxEventManager", EMITTER_DATA = "dxEmitter"; var EventManager = Class.inherit({ ctor: function() { this._attachHandlers(); this.reset(); this._proxiedCancelHandler = this._cancelHandler.bind(this); this._proxiedAcceptHandler = this._acceptHandler.bind(this) }, _attachHandlers: function() { $(document).on(eventUtils.addNamespace(pointerEvents.down, MANAGER_EVENT), this._pointerDownHandler.bind(this)).on(eventUtils.addNamespace(pointerEvents.move, MANAGER_EVENT), this._pointerMoveHandler.bind(this)).on(eventUtils.addNamespace([pointerEvents.up, pointerEvents.cancel].join(" "), MANAGER_EVENT), this._pointerUpHandler.bind(this)).on(eventUtils.addNamespace(wheelEvent.name, MANAGER_EVENT), this._mouseWheelHandler.bind(this)) }, _eachEmitter: function(callback) { var activeEmitters = this._activeEmitters || []; var i = 0; while (activeEmitters.length > i) { var emitter = activeEmitters[i]; if (false === callback(emitter)) { break } if (activeEmitters[i] === emitter) { i++ } } }, _applyToEmitters: function(method, arg) { this._eachEmitter(function(emitter) { emitter[method].call(emitter, arg) }) }, reset: function() { this._eachEmitter(this._proxiedCancelHandler); this._activeEmitters = [] }, resetEmitter: function(emitter) { this._proxiedCancelHandler(emitter) }, _pointerDownHandler: function(e) { if (eventUtils.isMouseEvent(e) && e.which > 1) { return } this._updateEmitters(e) }, _updateEmitters: function(e) { if (!this._isSetChanged(e)) { return } this._cleanEmitters(e); this._fetchEmitters(e) }, _isSetChanged: function(e) { var currentSet = this._closestEmitter(e); var previousSet = this._emittersSet || []; var setChanged = currentSet.length !== previousSet.length; $.each(currentSet, function(index, emitter) { setChanged = setChanged || previousSet[index] !== emitter; return !setChanged }); this._emittersSet = currentSet; return setChanged }, _closestEmitter: function(e) { var that = this, result = [], $element = $(e.target); function handleEmitter(_, emitter) { if (!!emitter && emitter.validatePointers(e) && emitter.validate(e)) { emitter.addCancelCallback(that._proxiedCancelHandler); emitter.addAcceptCallback(that._proxiedAcceptHandler); result.push(emitter) } } while ($element.length) { var emitters = $.data($element.get(0), EMITTER_DATA) || []; $.each(emitters, handleEmitter); $element = $element.parent() } return result }, _acceptHandler: function(acceptedEmitter, e) { var that = this; this._eachEmitter(function(emitter) { if (emitter !== acceptedEmitter) { that._cancelEmitter(emitter, e) } }) }, _cancelHandler: function(canceledEmitter, e) { this._cancelEmitter(canceledEmitter, e) }, _cancelEmitter: function(emitter, e) { var activeEmitters = this._activeEmitters; if (e) { emitter.cancel(e) } else { emitter.reset() } emitter.removeCancelCallback(); emitter.removeAcceptCallback(); var emitterIndex = inArray(emitter, activeEmitters); if (emitterIndex > -1) { activeEmitters.splice(emitterIndex, 1) } }, _cleanEmitters: function(e) { this._applyToEmitters("end", e); this.reset(e) }, _fetchEmitters: function(e) { this._activeEmitters = this._emittersSet.slice(); this._applyToEmitters("start", e) }, _pointerMoveHandler: function(e) { this._applyToEmitters("move", e) }, _pointerUpHandler: function(e) { this._updateEmitters(e) }, _mouseWheelHandler: function(e) { if (!this._allowInterruptionByMouseWheel()) { return } e.pointers = [null]; this._pointerDownHandler(e); this._adjustWheelEvent(e); this._pointerMoveHandler(e); e.pointers = []; this._pointerUpHandler(e) }, _allowInterruptionByMouseWheel: function() { var allowInterruption = true; this._eachEmitter(function(emitter) { allowInterruption = emitter.allowInterruptionByMouseWheel() && allowInterruption; return allowInterruption }); return allowInterruption }, _adjustWheelEvent: function(e) { var closestGestureEmitter = null; this._eachEmitter(function(emitter) { if (!emitter.gesture) { return } var direction = emitter.getDirection(e); if ("horizontal" !== direction && !e.shiftKey || "vertical" !== direction && e.shiftKey) { closestGestureEmitter = emitter; return false } }); if (!closestGestureEmitter) { return } var direction = closestGestureEmitter.getDirection(e), verticalGestureDirection = "both" === direction && !e.shiftKey || "vertical" === direction, prop = verticalGestureDirection ? "pageY" : "pageX"; e[prop] += e.delta }, isActive: function(element) { var result = false; this._eachEmitter(function(emitter) { result = result || emitter.getElement().is(element) }); return result } }); var eventManager = new EventManager; var EMITTER_SUBSCRIPTION_DATA = "dxEmitterSubscription"; var registerEmitter = function(emitterConfig) { var emitterClass = emitterConfig.emitter, emitterName = emitterConfig.events[0], emitterEvents = emitterConfig.events; $.each(emitterEvents, function(_, eventName) { registerEvent(eventName, { noBubble: !emitterConfig.bubble, setup: function(element) { var subscriptions = $.data(element, EMITTER_SUBSCRIPTION_DATA) || {}, emitters = $.data(element, EMITTER_DATA) || {}, emitter = emitters[emitterName] || new emitterClass(element); subscriptions[eventName] = true; emitters[emitterName] = emitter; $.data(element, EMITTER_DATA, emitters); $.data(element, EMITTER_SUBSCRIPTION_DATA, subscriptions) }, add: function(element, handleObj) { var emitters = $.data(element, EMITTER_DATA), emitter = emitters[emitterName]; emitter.configure(extend({ delegateSelector: handleObj.selector }, handleObj.data), handleObj.type) }, teardown: function(element) { var subscriptions = $.data(element, EMITTER_SUBSCRIPTION_DATA), emitters = $.data(element, EMITTER_DATA), emitter = emitters[emitterName]; delete subscriptions[eventName]; var disposeEmitter = true; $.each(emitterEvents, function(_, eventName) { disposeEmitter = disposeEmitter && !subscriptions[eventName]; return disposeEmitter }); if (disposeEmitter) { if (eventManager.isActive(element)) { eventManager.resetEmitter(emitter) } emitter && emitter.dispose(); delete emitters[emitterName] } } }) }) }; module.exports = registerEmitter }, /*!*********************************!*\ !*** ./js/events/core/wheel.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), registerEvent = __webpack_require__( /*! ./event_registrator */ 73), eventUtils = __webpack_require__( /*! ../utils */ 71); var EVENT_NAME = "dxmousewheel", EVENT_NAMESPACE = "dxWheel"; var wheelEvent = void 0 !== document.onwheel ? "wheel" : "mousewheel"; var wheel = { setup: function(element) { var $element = $(element); $element.on(eventUtils.addNamespace(wheelEvent, EVENT_NAMESPACE), wheel._wheelHandler.bind(wheel)) }, teardown: function(element) { var $element = $(element); $element.off("." + EVENT_NAMESPACE) }, _wheelHandler: function(e) { var delta = this._getWheelDelta(e.originalEvent); eventUtils.fireEvent({ type: EVENT_NAME, originalEvent: e, delta: delta, pointerType: "mouse" }); e.stopPropagation() }, _getWheelDelta: function(event) { return event.wheelDelta ? event.wheelDelta : 30 * -event.deltaY } }; registerEvent(EVENT_NAME, wheel); exports.name = EVENT_NAME }, /*!**********************************************!*\ !*** ./js/events/gesture/emitter.gesture.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), devices = __webpack_require__( /*! ../../core/devices */ 53), support = __webpack_require__( /*! ../../core/utils/support */ 61), browser = __webpack_require__( /*! ../../core/utils/browser */ 23), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), mathUtils = __webpack_require__( /*! ../../core/utils/math */ 87), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), eventUtils = __webpack_require__( /*! ../utils */ 71), Emitter = __webpack_require__( /*! ../core/emitter */ 83), sign = mathUtils.sign, abs = Math.abs; var SLEEP = 0, INITED = 1, STARTED = 2, TOUCH_BOUNDARY = 10, IMMEDIATE_TOUCH_BOUNDARY = 0, IMMEDIATE_TIMEOUT = 180; var isMouseWheelEvent = function(e) { return e && "dxmousewheel" === e.type }; var supportPointerEvents = function() { var cssSupport = support.styleProp("pointer-events"); var msieLess11 = browser.msie && parseInt(browser.version, 10) < 11; return cssSupport && !msieLess11 }; var gestureCover = function() { var GESTURE_COVER_CLASS = "dx-gesture-cover"; var isDesktop = "generic" === devices.real().platform; if (!supportPointerEvents() || !isDesktop) { return commonUtils.noop } var $cover = $("<div>").addClass(GESTURE_COVER_CLASS).css("pointerEvents", "none"); $cover.on("dxmousewheel", function(e) { e.preventDefault() }); domUtils.ready(function() { $cover.appendTo("body") }); return function(toggle, cursor) { $cover.css("pointerEvents", toggle ? "all" : "none"); toggle && $cover.css("cursor", cursor) } }(); var GestureEmitter = Emitter.inherit({ gesture: true, configure: function(data) { this.getElement().css("msTouchAction", data.immediate ? "pinch-zoom" : ""); this.callBase(data) }, allowInterruptionByMouseWheel: function() { return this._stage !== STARTED }, getDirection: function() { return this.direction }, _cancel: function() { this.callBase.apply(this, arguments); this._toggleGestureCover(false); this._stage = SLEEP }, start: function(e) { if (eventUtils.needSkipEvent(e)) { this._cancel(e); return } this._startEvent = eventUtils.createEvent(e); this._startEventData = eventUtils.eventData(e); this._stage = INITED; this._init(e); this._setupImmediateTimer() }, _setupImmediateTimer: function() { clearTimeout(this._immediateTimer); this._immediateAccepted = false; if (!this.immediate) { return } this._immediateTimer = setTimeout(function() { this._immediateAccepted = true }.bind(this), IMMEDIATE_TIMEOUT) }, move: function(e) { if (this._stage === INITED && this._directionConfirmed(e)) { this._stage = STARTED; this._resetActiveElement(); this._toggleGestureCover(true); this._clearSelection(e); this._adjustStartEvent(e); this._start(this._startEvent); if (this._stage === SLEEP) { return } this._requestAccept(e); this._move(e); this._forgetAccept() } else { if (this._stage === STARTED) { this._clearSelection(e); this._move(e) } } }, _directionConfirmed: function(e) { var touchBoundary = this._getTouchBoundary(e), delta = eventUtils.eventDelta(this._startEventData, eventUtils.eventData(e)), deltaX = abs(delta.x), deltaY = abs(delta.y); var horizontalMove = this._validateMove(touchBoundary, deltaX, deltaY), verticalMove = this._validateMove(touchBoundary, deltaY, deltaX); var direction = this.getDirection(e), bothAccepted = "both" === direction && (horizontalMove || verticalMove), horizontalAccepted = "horizontal" === direction && horizontalMove, verticalAccepted = "vertical" === direction && verticalMove; return bothAccepted || horizontalAccepted || verticalAccepted || this._immediateAccepted }, _validateMove: function(touchBoundary, mainAxis, crossAxis) { return mainAxis && mainAxis >= touchBoundary && (this.immediate ? mainAxis >= crossAxis : true) }, _getTouchBoundary: function(e) { return this.immediate || isMouseWheelEvent(e) ? IMMEDIATE_TOUCH_BOUNDARY : TOUCH_BOUNDARY }, _adjustStartEvent: function(e) { var touchBoundary = this._getTouchBoundary(e), delta = eventUtils.eventDelta(this._startEventData, eventUtils.eventData(e)); this._startEvent.pageX += sign(delta.x) * touchBoundary; this._startEvent.pageY += sign(delta.y) * touchBoundary }, _resetActiveElement: function() { if ("ios" === devices.real().platform && $(":focus", this.getElement()).length) { domUtils.resetActiveElement() } }, _toggleGestureCover: function(toggle) { var isStarted = this._stage === STARTED; if (isStarted) { gestureCover(toggle, this.getElement().css("cursor")) } }, _clearSelection: function(e) { if (isMouseWheelEvent(e) || eventUtils.isTouchEvent(e)) { return } domUtils.clearSelection() }, end: function(e) { this._toggleGestureCover(false); if (this._stage === STARTED) { this._end(e) } else { if (this._stage === INITED) { this._stop(e) } } this._stage = SLEEP }, dispose: function() { clearTimeout(this._immediateTimer); this.callBase.apply(this, arguments); this._toggleGestureCover(false) }, _init: commonUtils.noop, _start: commonUtils.noop, _move: commonUtils.noop, _stop: commonUtils.noop, _end: commonUtils.noop }); GestureEmitter.initialTouchBoundary = TOUCH_BOUNDARY; GestureEmitter.touchBoundary = function(newBoundary) { if (commonUtils.isDefined(newBoundary)) { TOUCH_BOUNDARY = newBoundary; return } return TOUCH_BOUNDARY }; module.exports = GestureEmitter }, /*!*******************************!*\ !*** ./js/core/utils/math.js ***! \*******************************/ function(module, exports) { var sign = function(value) { if (0 === value) { return 0 } return value / Math.abs(value) }; var fitIntoRange = function(value, minValue, maxValue) { var isMinValueUndefined = !minValue && 0 !== minValue, isMaxValueUndefined = !maxValue && 0 !== maxValue; isMinValueUndefined && (minValue = !isMaxValueUndefined ? Math.min(value, maxValue) : value); isMaxValueUndefined && (maxValue = !isMinValueUndefined ? Math.max(value, minValue) : value); return Math.min(Math.max(value, minValue), maxValue) }; var inRange = function(value, minValue, maxValue) { return value >= minValue && value <= maxValue }; exports.sign = sign; exports.fitIntoRange = fitIntoRange; exports.inRange = inRange }, /*!****************************!*\ !*** ./js/localization.js ***! \****************************/ function(module, exports, __webpack_require__) { exports.locale = __webpack_require__( /*! ./localization/core */ 34).locale; exports.loadMessages = __webpack_require__( /*! ./localization/message */ 89).load; exports.message = __webpack_require__( /*! ./localization/message */ 89); exports.number = __webpack_require__( /*! ./localization/number */ 32); exports.date = __webpack_require__( /*! ./localization/date */ 33); exports.currency = __webpack_require__( /*! ./localization/currency */ 36) }, /*!************************************!*\ !*** ./js/localization/message.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), dependencyInjector = __webpack_require__( /*! ../core/utils/dependency_injector */ 29), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, stringFormat = __webpack_require__( /*! ../core/utils/string */ 18).format, humanize = __webpack_require__( /*! ../core/utils/inflector */ 39).humanize, coreLocalization = __webpack_require__( /*! ./core */ 34); __webpack_require__( /*! ./core */ 34); var baseDictionary = extend(true, {}, __webpack_require__( /*! ./default_messages */ 90)); var newMessages = {}; var messageLocalization = dependencyInjector({ _dictionary: baseDictionary, load: function(messages) { extend(true, this._dictionary, messages) }, _localizablePrefix: "@", setup: function(localizablePrefix) { this._localizablePrefix = localizablePrefix }, localizeString: function(text) { var that = this, regex = new RegExp("(^|[^a-zA-Z_0-9" + that._localizablePrefix + "-]+)(" + that._localizablePrefix + "{1,2})([a-zA-Z_0-9-]+)", "g"), escapeString = that._localizablePrefix + that._localizablePrefix; return text.replace(regex, function(str, prefix, escape, localizationKey) { var result, defaultResult = that._localizablePrefix + localizationKey; if (escape !== escapeString) { result = that.format(localizationKey) } if (!result) { newMessages[localizationKey] = humanize(localizationKey) } return prefix + (result || defaultResult) }) }, _messageLoaded: function(key, locale) { return void 0 !== this._dictionary[locale || coreLocalization.locale()][key] }, localizeNode: function(node) { var that = this; $(node).each(function(index, nodeItem) { if (!nodeItem.nodeType) { return } if (3 === nodeItem.nodeType) { nodeItem.nodeValue = that.localizeString(nodeItem.nodeValue) } else { if (!$(nodeItem).is("iframe")) { $.each(nodeItem.attributes || [], function(index, attr) { if ("string" === typeof attr.value) { var localizedValue = that.localizeString(attr.value); if (attr.value !== localizedValue) { attr.value = localizedValue } } }); $(nodeItem).contents().each(function(index, node) { that.localizeNode(node) }) } } }) }, getMessagesByLocales: function() { return this._dictionary }, getDictionary: function(onlyNew) { if (onlyNew) { return newMessages } return extend({}, newMessages, this.getMessagesByLocales()[coreLocalization.locale()]) }, getFormatter: function(key) { return this._getFormatterBase(key) || this._getFormatterBase(key, "en") }, _getFormatterBase: function(key, locale) { var localeMessages = this._dictionary[locale || coreLocalization.locale()], message = localeMessages && localeMessages[key]; if (message) { return function() { var args = 1 === arguments.length && Array.isArray(arguments[0]) ? arguments[0].slice(0) : Array.prototype.slice.call(arguments, 0); args.unshift(message); return stringFormat.apply(this, args) } } }, format: function(key) { var formatter = this.getFormatter(key); return formatter && formatter() || "" } }); module.exports = messageLocalization }, /*!*********************************************!*\ !*** ./js/localization/default_messages.js ***! \*********************************************/ function(module, exports) { module.exports = { en: { Yes: "Yes", No: "No", Cancel: "Cancel", Clear: "Clear", Done: "Done", Loading: "Loading...", Select: "Select...", Search: "Search", Back: "Back", OK: "OK", "dxCollectionWidget-noDataText": "No data to display", "validation-required": "Required", "validation-required-formatted": "{0} is required", "validation-numeric": "Value must be a number", "validation-numeric-formatted": "{0} must be a number", "validation-range": "Value is out of range", "validation-range-formatted": "{0} is out of range", "validation-stringLength": "The length of the value is not correct", "validation-stringLength-formatted": "The length of {0} is not correct", "validation-custom": "Value is invalid", "validation-custom-formatted": "{0} is invalid", "validation-compare": "Values do not match", "validation-compare-formatted": "{0} does not match", "validation-pattern": "Value does not match pattern", "validation-pattern-formatted": "{0} does not match pattern", "validation-email": "Email is invalid", "validation-email-formatted": "{0} is invalid", "validation-mask": "Value is invalid", "dxLookup-searchPlaceholder": "Minimum character number: {0}", "dxList-pullingDownText": "Pull down to refresh...", "dxList-pulledDownText": "Release to refresh...", "dxList-refreshingText": "Refreshing...", "dxList-pageLoadingText": "Loading...", "dxList-nextButtonText": "More", "dxList-selectAll": "Select All", "dxListEditDecorator-delete": "Delete", "dxListEditDecorator-more": "More", "dxScrollView-pullingDownText": "Pull down to refresh...", "dxScrollView-pulledDownText": "Release to refresh...", "dxScrollView-refreshingText": "Refreshing...", "dxScrollView-reachBottomText": "Loading...", "dxDateBox-simulatedDataPickerTitleTime": "Select time", "dxDateBox-simulatedDataPickerTitleDate": "Select date", "dxDateBox-simulatedDataPickerTitleDateTime": "Select date and time", "dxDateBox-validation-datetime": "Value must be a date or time", "dxFileUploader-selectFile": "Select file", "dxFileUploader-dropFile": "or Drop file here", "dxFileUploader-bytes": "bytes", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Upload", "dxFileUploader-uploaded": "Uploaded", "dxFileUploader-readyToUpload": "Ready to upload", "dxFileUploader-uploadFailedMessage": "Upload failed", "dxRangeSlider-ariaFrom": "From", "dxRangeSlider-ariaTill": "Till", "dxSwitch-onText": "ON", "dxSwitch-offText": "OFF", "dxForm-optionalMark": "optional", "dxForm-requiredMessage": "{0} is required", "dxNumberBox-invalidValueMessage": "Value must be a number", "dxDataGrid-columnChooserTitle": "Column Chooser", "dxDataGrid-columnChooserEmptyText": "Drag a column here to hide it", "dxDataGrid-groupContinuesMessage": "Continues on the next page", "dxDataGrid-groupContinuedMessage": "Continued from the previous page", "dxDataGrid-groupHeaderText": "Group by This Column", "dxDataGrid-ungroupHeaderText": "Ungroup", "dxDataGrid-ungroupAllText": "Ungroup All", "dxDataGrid-editingEditRow": "Edit", "dxDataGrid-editingSaveRowChanges": "Save", "dxDataGrid-editingCancelRowChanges": "Cancel", "dxDataGrid-editingDeleteRow": "Delete", "dxDataGrid-editingUndeleteRow": "Undelete", "dxDataGrid-editingConfirmDeleteMessage": "Are you sure you want to delete this record?", "dxDataGrid-validationCancelChanges": "Cancel changes", "dxDataGrid-groupPanelEmptyText": "Drag a column header here to group by that column", "dxDataGrid-noDataText": "No data", "dxDataGrid-searchPanelPlaceholder": "Search...", "dxDataGrid-filterRowShowAllText": "(All)", "dxDataGrid-filterRowResetOperationText": "Reset", "dxDataGrid-filterRowOperationEquals": "Equals", "dxDataGrid-filterRowOperationNotEquals": "Does not equal", "dxDataGrid-filterRowOperationLess": "Less than", "dxDataGrid-filterRowOperationLessOrEquals": "Less than or equal to", "dxDataGrid-filterRowOperationGreater": "Greater than", "dxDataGrid-filterRowOperationGreaterOrEquals": "Greater than or equal to", "dxDataGrid-filterRowOperationStartsWith": "Starts with", "dxDataGrid-filterRowOperationContains": "Contains", "dxDataGrid-filterRowOperationNotContains": "Does not contain", "dxDataGrid-filterRowOperationEndsWith": "Ends with", "dxDataGrid-filterRowOperationBetween": "Between", "dxDataGrid-filterRowOperationBetweenStartText": "Start", "dxDataGrid-filterRowOperationBetweenEndText": "End", "dxDataGrid-applyFilterText": "Apply filter", "dxDataGrid-trueText": "true", "dxDataGrid-falseText": "false", "dxDataGrid-sortingAscendingText": "Sort Ascending", "dxDataGrid-sortingDescendingText": "Sort Descending", "dxDataGrid-sortingClearText": "Clear Sorting", "dxDataGrid-editingSaveAllChanges": "Save changes", "dxDataGrid-editingCancelAllChanges": "Discard changes", "dxDataGrid-editingAddRow": "Add a row", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "Min of {1} is {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "Max of {1} is {0}", "dxDataGrid-summaryAvg": "Avg: {0}", "dxDataGrid-summaryAvgOtherColumn": "Avg of {1} is {0}", "dxDataGrid-summarySum": "Sum: {0}", "dxDataGrid-summarySumOtherColumn": "Sum of {1} is {0}", "dxDataGrid-summaryCount": "Count: {0}", "dxDataGrid-columnFixingFix": "Fix", "dxDataGrid-columnFixingUnfix": "Unfix", "dxDataGrid-columnFixingLeftPosition": "To the left", "dxDataGrid-columnFixingRightPosition": "To the right", "dxDataGrid-exportTo": "Export", "dxDataGrid-exportToExcel": "Export to Excel file", "dxDataGrid-excelFormat": "Excel file", "dxDataGrid-selectedRows": "Selected rows", "dxDataGrid-exportSelectedRows": "Export selected rows", "dxDataGrid-exportAll": "Export all data", "dxDataGrid-headerFilterEmptyValue": "(Blanks)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "Cancel", "dxDataGrid-ariaColumn": "Column", "dxDataGrid-ariaValue": "Value", "dxDataGrid-ariaFilterCell": "Filter cell", "dxDataGrid-ariaCollapse": "Collapse", "dxDataGrid-ariaExpand": "Expand", "dxDataGrid-ariaDataGrid": "Data grid", "dxDataGrid-ariaSearchInGrid": "Search in data grid", "dxDataGrid-ariaSelectAll": "Select all", "dxDataGrid-ariaSelectRow": "Select row", "dxTreeList-ariaTreeList": "Tree list", "dxTreeList-editingAddRowToNode": "Add", "dxPager-infoText": "Page {0} of {1} ({2} items)", "dxPager-pagesCountText": "of", "dxPivotGrid-grandTotal": "Grand Total", "dxPivotGrid-total": "{0} Total", "dxPivotGrid-fieldChooserTitle": "Field Chooser", "dxPivotGrid-showFieldChooser": "Show Field Chooser", "dxPivotGrid-expandAll": "Expand All", "dxPivotGrid-collapseAll": "Collapse All", "dxPivotGrid-sortColumnBySummary": 'Sort "{0}" by This Column', "dxPivotGrid-sortRowBySummary": 'Sort "{0}" by This Row', "dxPivotGrid-removeAllSorting": "Remove All Sorting", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "Row Fields", "dxPivotGrid-columnFields": "Column Fields", "dxPivotGrid-dataFields": "Data Fields", "dxPivotGrid-filterFields": "Filter Fields", "dxPivotGrid-allFields": "All Fields", "dxPivotGrid-columnFieldArea": "Drop Column Fields Here", "dxPivotGrid-dataFieldArea": "Drop Data Fields Here", "dxPivotGrid-rowFieldArea": "Drop Row Fields Here", "dxPivotGrid-filterFieldArea": "Drop Filter Fields Here", "dxScheduler-editorLabelTitle": "Subject", "dxScheduler-editorLabelStartDate": "Start Date", "dxScheduler-editorLabelEndDate": "End Date", "dxScheduler-editorLabelDescription": "Description", "dxScheduler-editorLabelRecurrence": "Repeat", "dxScheduler-openAppointment": "Open appointment", "dxScheduler-recurrenceNever": "Never", "dxScheduler-recurrenceDaily": "Daily", "dxScheduler-recurrenceWeekly": "Weekly", "dxScheduler-recurrenceMonthly": "Monthly", "dxScheduler-recurrenceYearly": "Yearly", "dxScheduler-recurrenceEvery": "Every", "dxScheduler-recurrenceEnd": "End repeat", "dxScheduler-recurrenceAfter": "After", "dxScheduler-recurrenceOn": "On", "dxScheduler-recurrenceRepeatDaily": "day(s)", "dxScheduler-recurrenceRepeatWeekly": "week(s)", "dxScheduler-recurrenceRepeatMonthly": "month(s)", "dxScheduler-recurrenceRepeatYearly": "year(s)", "dxScheduler-switcherDay": "Day", "dxScheduler-switcherWeek": "Week", "dxScheduler-switcherWorkWeek": "Work Week", "dxScheduler-switcherMonth": "Month", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "Timeline Day", "dxScheduler-switcherTimelineWeek": "Timeline Week", "dxScheduler-switcherTimelineWorkWeek": "Timeline Work Week", "dxScheduler-switcherTimelineMonth": "Timeline Month", "dxScheduler-recurrenceRepeatOnDate": "on date", "dxScheduler-recurrenceRepeatCount": "occurrence(s)", "dxScheduler-allDay": "All day", "dxScheduler-confirmRecurrenceEditMessage": "Do you want to edit only this appointment or the whole series?", "dxScheduler-confirmRecurrenceDeleteMessage": "Do you want to delete only this appointment or the whole series?", "dxScheduler-confirmRecurrenceEditSeries": "Edit series", "dxScheduler-confirmRecurrenceDeleteSeries": "Delete series", "dxScheduler-confirmRecurrenceEditOccurrence": "Edit appointment", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Delete appointment", "dxScheduler-noTimezoneTitle": "No timezone", "dxCalendar-todayButtonText": "Today", "dxCalendar-ariaWidgetName": "Calendar", "dxColorView-ariaRed": "Red", "dxColorView-ariaGreen": "Green", "dxColorView-ariaBlue": "Blue", "dxColorView-ariaAlpha": "Transparency", "dxColorView-ariaHex": "Color code", "vizExport-printingButtonText": "Print", "vizExport-titleMenuText": "Exporting/Printing", "vizExport-exportButtonText": "{0} file" } } }, /*!*****************************************!*\ !*** ./js/bundles/modules/framework.js ***! \*****************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 6); __webpack_require__( /*! ../../integration/knockout */ 92); module.exports = DevExpress.framework = {}; DevExpress.framework.dxCommand = __webpack_require__( /*! ../../framework/command */ 121); DevExpress.framework.Router = __webpack_require__( /*! ../../framework/router */ 123); DevExpress.framework.StateManager = __webpack_require__( /*! ../../framework/state_manager */ 124); DevExpress.framework.ViewCache = __webpack_require__( /*! ../../framework/view_cache */ 125); DevExpress.framework.NullViewCache = __webpack_require__( /*! ../../framework/view_cache */ 125).NullViewCache; DevExpress.framework.ConditionalViewCacheDecorator = __webpack_require__( /*! ../../framework/view_cache */ 125).ConditionalViewCacheDecorator; DevExpress.framework.CapacityViewCacheDecorator = __webpack_require__( /*! ../../framework/view_cache */ 125).CapacityViewCacheDecorator; DevExpress.framework.HistoryDependentViewCacheDecorator = __webpack_require__( /*! ../../framework/view_cache */ 125).HistoryDependentViewCacheDecorator; DevExpress.framework.dxCommandContainer = __webpack_require__( /*! ../../framework/html/command_container */ 126); DevExpress.framework.dxView = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxView; DevExpress.framework.dxLayout = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxLayout; DevExpress.framework.dxViewPlaceholder = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxViewPlaceholder; DevExpress.framework.dxContentPlaceholder = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxContentPlaceholder; DevExpress.framework.dxTransition = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxTransition; DevExpress.framework.dxContent = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128).dxContent; DevExpress.framework.html = {}; DevExpress.framework.html.HtmlApplication = __webpack_require__( /*! ../../framework/html/html_application */ 129); DevExpress.framework.Route = __webpack_require__( /*! ../../framework/router */ 123).Route; DevExpress.framework.MemoryKeyValueStorage = __webpack_require__( /*! ../../framework/state_manager */ 124).MemoryKeyValueStorage; DevExpress.framework.NavigationDevices = __webpack_require__( /*! ../../framework/navigation_devices */ 134); DevExpress.framework.NavigationManager = __webpack_require__( /*! ../../framework/navigation_manager */ 133); DevExpress.framework.createActionExecutors = __webpack_require__( /*! ../../framework/action_executors */ 132).createActionExecutors; DevExpress.framework.Application = __webpack_require__( /*! ../../framework/application */ 130).Application; var browserAdapters = __webpack_require__( /*! ../../framework/browser_adapters */ 135); DevExpress.framework.DefaultBrowserAdapter = browserAdapters.DefaultBrowserAdapter; DevExpress.framework.OldBrowserAdapter = browserAdapters.OldBrowserAdapter; DevExpress.framework.BuggyAndroidBrowserAdapter = browserAdapters.BuggyAndroidBrowserAdapter; DevExpress.framework.HistorylessBrowserAdapter = browserAdapters.HistorylessBrowserAdapter; DevExpress.framework.BuggyCordovaWP81BrowserAdapter = browserAdapters.BuggyCordovaWP81BrowserAdapter; DevExpress.framework.CommandMapping = __webpack_require__( /*! ../../framework/command_mapping */ 136); DevExpress.framework.HistoryBasedNavigationDevice = __webpack_require__( /*! ../../framework/navigation_devices */ 134).HistoryBasedNavigationDevice; DevExpress.framework.StackBasedNavigationDevice = __webpack_require__( /*! ../../framework/navigation_devices */ 134).StackBasedNavigationDevice; DevExpress.framework.HistoryBasedNavigationManager = __webpack_require__( /*! ../../framework/navigation_manager */ 133).HistoryBasedNavigationManager; DevExpress.framework.StackBasedNavigationManager = __webpack_require__( /*! ../../framework/navigation_manager */ 133).StackBasedNavigationManager; DevExpress.framework.NavigationStack = __webpack_require__( /*! ../../framework/navigation_manager */ 133).NavigationStack; DevExpress.framework.utils = __webpack_require__( /*! ../../framework/utils */ 131).utils; DevExpress.framework.templateProvider = __webpack_require__( /*! ../../framework/utils */ 131).templateProvider; DevExpress.framework.html.CommandManager = __webpack_require__( /*! ../../framework/html/command_manager */ 139); DevExpress.framework.html.HtmlApplication = __webpack_require__( /*! ../../framework/html/html_application */ 129); DevExpress.framework.html.layoutSets = __webpack_require__( /*! ../../framework/html/presets */ 138).layoutSets; DevExpress.framework.html.animationSets = __webpack_require__( /*! ../../framework/html/presets */ 138).animationSets; DevExpress.framework.html.DefaultLayoutController = __webpack_require__( /*! ../../framework/html/layout_controller */ 142).DefaultLayoutController; DevExpress.framework.html.layoutSets = __webpack_require__( /*! ../../framework/html/layout_controller */ 142).layoutSets; DevExpress.framework.html.MarkupComponent = __webpack_require__( /*! ../../framework/html/markup_component */ 127).MarkupComponent; DevExpress.framework.html.ViewEngine = __webpack_require__( /*! ../../framework/html/view_engine */ 141).ViewEngine; DevExpress.framework.html.ViewEngineComponents = __webpack_require__( /*! ../../framework/html/view_engine_components */ 128); var widgetCommandAdaptersModule = __webpack_require__( /*! ../../framework/html/widget_command_adapters */ 140); DevExpress.framework.html.commandToDXWidgetAdapters = { dxToolbar: widgetCommandAdaptersModule.dxToolbar, dxList: widgetCommandAdaptersModule.dxList, dxNavBar: widgetCommandAdaptersModule.dxNavBar, dxPivot: widgetCommandAdaptersModule.dxPivot, dxSlideOut: widgetCommandAdaptersModule.dxSlideOut } }, /*!************************************!*\ !*** ./js/integration/knockout.js ***! \************************************/ function(module, exports, __webpack_require__) { var ko = __webpack_require__( /*! knockout */ 93); if (ko) { var errors = __webpack_require__( /*! ../core/errors */ 7), compareVersion = __webpack_require__( /*! ../core/utils/version */ 17).compare; if (compareVersion(ko.version, [2, 3]) < 0) { throw errors.Error("E0013") } __webpack_require__( /*! ./knockout/component_registrator */ 94); __webpack_require__( /*! ./knockout/event_registrator */ 113); __webpack_require__( /*! ./knockout/components */ 114); __webpack_require__( /*! ./knockout/validation */ 116); __webpack_require__( /*! ./knockout/variable_wrapper_utils */ 118); __webpack_require__( /*! ./knockout/clean_node */ 119); __webpack_require__( /*! ./knockout/clean_node_old */ 120) } }, /*!****************************!*\ !*** external "window.ko" ***! \****************************/ function(module, exports) { module.exports = window.ko }, /*!**********************************************************!*\ !*** ./js/integration/knockout/component_registrator.js ***! \**********************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ko = __webpack_require__( /*! knockout */ 93), errors = __webpack_require__( /*! ../../core/errors */ 7), inflector = __webpack_require__( /*! ../../core/utils/inflector */ 39), isPlainObject = __webpack_require__( /*! ../../core/utils/type */ 12).isPlainObject, registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), Widget = __webpack_require__( /*! ../../ui/widget/ui.widget */ 95), KoTemplate = __webpack_require__( /*! ./template */ 105), Editor = __webpack_require__( /*! ../../ui/editor/editor */ 106), Locker = __webpack_require__( /*! ../../core/utils/locker */ 112), config = __webpack_require__( /*! ../../core/config */ 15); var LOCKS_DATA_KEY = "dxKoLocks", CREATED_WITH_KO_DATA_KEY = "dxKoCreation"; var editorsBindingHandlers = []; var registerComponentKoBinding = function(componentName, componentClass) { if (componentClass.subclassOf(Editor)) { editorsBindingHandlers.push(componentName) } ko.bindingHandlers[componentName] = { init: function(domNode, valueAccessor) { var component, isBindingPropertyPredicate, $element = $(domNode), optionChangedCallbacks = $.Callbacks(), optionsByReference = {}, knockoutConfig = config().knockout, isBindingPropertyPredicateName = knockoutConfig && knockoutConfig.isBindingPropertyPredicateName, ctorOptions = { onInitializing: function() { optionsByReference = this._getOptionsByReference(); ko.computed(function() { var model = ko.unwrap(valueAccessor()); if (component) { component.beginUpdate() } isBindingPropertyPredicate = isBindingPropertyPredicateName && model && model[isBindingPropertyPredicateName]; unwrapModel(model); if (component) { component.endUpdate() } }, null, { disposeWhenNodeIsRemoved: domNode }); component = this }, modelByElement: function($element) { if ($element.length) { return ko.dataFor($element.get(0)) } }, nestedComponentOptions: function(component) { return { modelByElement: component.option("modelByElement"), nestedComponentOptions: component.option("nestedComponentOptions") } }, _optionChangedCallbacks: optionChangedCallbacks, integrationOptions: { watchMethod: function(fn, callback, options) { options = options || {}; var skipCallback = options.skipImmediate; var watcher = ko.computed(function() { var newValue = ko.unwrap(fn()); if (!skipCallback) { callback(newValue) } skipCallback = false }); return function() { watcher.dispose() } }, templates: { "dx-polymorph-widget": { render: function(options) { var widgetName = ko.utils.unwrapObservable(options.model.widget); if (!widgetName) { return } if ("button" === widgetName || "tabs" === widgetName || "dropDownMenu" === widgetName) { var deprecatedName = widgetName; widgetName = inflector.camelize("dx-" + widgetName); errors.log("W0001", "dxToolbar - 'widget' item field", deprecatedName, "16.1", "Use: '" + widgetName + "' instead") } var markup = $('<div data-bind="' + widgetName + ': options">').get(0); options.container.append(markup); ko.applyBindings(options.model, markup) } } }, createTemplate: function(element) { return new KoTemplate(element) } } }, optionNameToModelMap = {}; var applyModelValueToOption = function(optionName, modelValue, unwrap) { var locks = $element.data(LOCKS_DATA_KEY), optionValue = unwrap ? ko.unwrap(modelValue) : modelValue; if (ko.isWriteableObservable(modelValue)) { optionNameToModelMap[optionName] = modelValue } if (component) { if (locks.locked(optionName)) { return } locks.obtain(optionName); try { if (ko.ignoreDependencies) { ko.ignoreDependencies(component.option, component, [optionName, optionValue]) } else { component.option(optionName, optionValue) } } finally { locks.release(optionName) } } else { ctorOptions[optionName] = optionValue } }; var handleOptionChanged = function(args) { var optionName = args.fullName, optionValue = args.value; if (!(optionName in optionNameToModelMap)) { return } var $element = this._$element, locks = $element.data(LOCKS_DATA_KEY); if (locks.locked(optionName)) { return } locks.obtain(optionName); try { optionNameToModelMap[optionName](optionValue) } finally { locks.release(optionName) } }; var createComponent = function() { optionChangedCallbacks.add(handleOptionChanged); $element.data(CREATED_WITH_KO_DATA_KEY, true).data(LOCKS_DATA_KEY, new Locker)[componentName](ctorOptions); ctorOptions = null }; var unwrapModelValue = function(currentModel, propertyName, propertyPath) { if (propertyPath === isBindingPropertyPredicateName) { return } if (!isBindingPropertyPredicate || isBindingPropertyPredicate(propertyPath, propertyName, currentModel)) { var unwrappedPropertyValue; ko.computed(function() { var propertyValue = currentModel[propertyName]; applyModelValueToOption(propertyPath, propertyValue, true); unwrappedPropertyValue = ko.unwrap(propertyValue) }, null, { disposeWhenNodeIsRemoved: domNode }); if (isPlainObject(unwrappedPropertyValue)) { if (!optionsByReference[propertyPath]) { unwrapModel(unwrappedPropertyValue, propertyPath) } } } else { applyModelValueToOption(propertyPath, currentModel[propertyName], false) } }; var unwrapModel = function(model, propertyPath) { for (var propertyName in model) { if (model.hasOwnProperty(propertyName)) { unwrapModelValue(model, propertyName, propertyPath ? [propertyPath, propertyName].join(".") : propertyName) } } }; createComponent(); return { controlsDescendantBindings: componentClass.subclassOf(Widget) } } }; if ("dxValidator" === componentName) { ko.bindingHandlers.dxValidator.after = editorsBindingHandlers } }; registerComponent.callbacks.add(function(name, componentClass) { registerComponentKoBinding(name, componentClass) }) }, /*!***********************************!*\ !*** ./js/ui/widget/ui.widget.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), errors = __webpack_require__( /*! ./ui.errors */ 22), Action = __webpack_require__( /*! ../../core/action */ 49), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), devices = __webpack_require__( /*! ../../core/devices */ 53), DOMComponent = __webpack_require__( /*! ../../core/dom_component */ 43), Template = __webpack_require__( /*! ./jquery.template */ 96), FunctionTemplate = __webpack_require__( /*! ./function_template */ 98), EmptyTemplate = __webpack_require__( /*! ./empty_template */ 99), ChildDefaultTemplate = __webpack_require__( /*! ./child_default_template */ 100), KeyboardProcessor = __webpack_require__( /*! ./ui.keyboard_processor */ 101), selectors = __webpack_require__( /*! ./jquery.selectors */ 102), eventUtils = __webpack_require__( /*! ../../events/utils */ 71), hoverEvents = __webpack_require__( /*! ../../events/hover */ 103), feedbackEvents = __webpack_require__( /*! ../../events/core/emitter.feedback */ 104), clickEvent = __webpack_require__( /*! ../../events/click */ 75), inflector = __webpack_require__( /*! ../../core/utils/inflector */ 39); var UI_FEEDBACK = "UIFeedback", WIDGET_CLASS = "dx-widget", ACTIVE_STATE_CLASS = "dx-state-active", DISABLED_STATE_CLASS = "dx-state-disabled", INVISIBLE_STATE_CLASS = "dx-state-invisible", HOVER_STATE_CLASS = "dx-state-hover", FOCUSED_STATE_CLASS = "dx-state-focused", FEEDBACK_SHOW_TIMEOUT = 30, FEEDBACK_HIDE_TIMEOUT = 400, FOCUS_NAMESPACE = "Focus", ANONYMOUS_TEMPLATE_NAME = "template", TEXT_NODE = 3, TEMPLATE_SELECTOR = "[data-options*='dxTemplate']", TEMPLATE_WRAPPER_CLASS = "dx-template-wrapper"; var DX_POLYMORPH_WIDGET_TEMPLATE = new FunctionTemplate(function(options) { var widgetName = options.model.widget; if (widgetName) { var widgetElement = $("<div>"), widgetOptions = options.model.options || {}; if ("button" === widgetName || "tabs" === widgetName || "dropDownMenu" === widgetName) { var deprecatedName = widgetName; widgetName = inflector.camelize("dx-" + widgetName); errors.log("W0001", "dxToolbar - 'widget' item field", deprecatedName, "16.1", "Use: '" + widgetName + "' instead") } widgetElement[widgetName](widgetOptions); return widgetElement } return $() }); var beforeActivateExists = void 0 !== document.onbeforeactivate; var Widget = DOMComponent.inherit({ _supportedKeys: function() { return {} }, _getDefaultOptions: function() { return extend(this.callBase(), { disabled: false, visible: true, hint: void 0, activeStateEnabled: false, onContentReady: null, hoverStateEnabled: false, focusStateEnabled: false, tabIndex: 0, accessKey: null, onFocusIn: null, onFocusOut: null, integrationOptions: { watchMethod: function(fn, callback, options) { options = options || {}; if (!options.skipImmediate) { callback(fn()) } return commonUtils.noop }, templates: { "dx-polymorph-widget": DX_POLYMORPH_WIDGET_TEMPLATE }, createTemplate: function(element) { return new Template(element) } }, _keyboardProcessor: void 0 }) }, _feedbackShowTimeout: FEEDBACK_SHOW_TIMEOUT, _feedbackHideTimeout: FEEDBACK_HIDE_TIMEOUT, _init: function() { this.callBase(); this._tempTemplates = []; this._defaultTemplates = {}; this._initTemplates(); this._initContentReadyAction() }, _initTemplates: function() { this._extractTemplates(); this._extractAnonymousTemplate() }, _extractTemplates: function() { var templates = this.option("integrationOptions.templates"), templateElements = this.element().contents().filter(TEMPLATE_SELECTOR); var templatesMap = {}; templateElements.each(function(_, template) { var templateOptions = domUtils.getElementOptions(template).dxTemplate; if (!templateOptions) { return } if (!templateOptions.name) { throw errors.Error("E0023") } $(template).addClass(TEMPLATE_WRAPPER_CLASS).detach(); templatesMap[templateOptions.name] = templatesMap[templateOptions.name] || []; templatesMap[templateOptions.name].push(template) }); $.each(templatesMap, function(templateName, value) { var deviceTemplate = this._findTemplateByDevice(value); if (deviceTemplate) { templates[templateName] = this._createTemplate(deviceTemplate) } }.bind(this)) }, _findTemplateByDevice: function(templates) { var suitableTemplate = commonUtils.findBestMatches(devices.current(), templates, function(template) { return domUtils.getElementOptions(template).dxTemplate })[0]; $.each(templates, function(index, template) { if (template !== suitableTemplate) { $(template).remove() } }); return suitableTemplate }, _extractAnonymousTemplate: function() { var templates = this.option("integrationOptions.templates"), anonymousTemplateName = this._getAnonymousTemplateName(), $anonymousTemplate = this.element().contents().detach(); var $notJunkTemplateContent = $anonymousTemplate.filter(function(_, element) { var isTextNode = element.nodeType === TEXT_NODE, isEmptyText = $.trim($(element).text()).length < 1; return !(isTextNode && isEmptyText) }), onlyJunkTemplateContent = $notJunkTemplateContent.length < 1; if (!templates[anonymousTemplateName] && !onlyJunkTemplateContent) { templates[anonymousTemplateName] = this._createTemplate($anonymousTemplate) } }, _getAriaTarget: function() { return this._focusTarget() }, _getAnonymousTemplateName: function() { return ANONYMOUS_TEMPLATE_NAME }, _getTemplateByOption: function(optionName) { return this._getTemplate(this.option(optionName)) }, _getTemplate: function(templateSource) { if (commonUtils.isFunction(templateSource)) { return new FunctionTemplate(function(options) { var templateSourceResult = templateSource.apply(this, this._getNormalizedTemplateArgs(options)); if (!commonUtils.isDefined(templateSourceResult)) { return new EmptyTemplate } var dispose = false; var template = this._acquireTemplate(templateSourceResult, function(templateSource) { if (templateSource.nodeType || templateSource.jquery && !$(templateSource).is("script")) { return new FunctionTemplate(function() { return templateSource }) } dispose = true; return this._createTemplate(templateSource) }.bind(this)); var result = template.render(options); dispose && template.dispose && template.dispose(); return result }.bind(this)) } return this._acquireTemplate(templateSource, this._createTemplateIfNeeded.bind(this)) }, _acquireTemplate: function(templateSource, createTemplate) { if (null == templateSource) { return new EmptyTemplate } if (templateSource instanceof ChildDefaultTemplate) { return this._defaultTemplates[templateSource.name] } if (commonUtils.isFunction(templateSource.render) && !templateSource.jquery) { return templateSource } if (templateSource.nodeType || templateSource.jquery) { templateSource = $(templateSource); return createTemplate(templateSource) } if ("string" === typeof templateSource) { var userTemplate = this.option("integrationOptions.templates")[templateSource]; if (userTemplate) { return userTemplate } var dynamicTemplate = this._defaultTemplates[templateSource]; if (dynamicTemplate) { return dynamicTemplate } return createTemplate(templateSource) } return this._acquireTemplate(templateSource.toString(), createTemplate) }, _createTemplateIfNeeded: function(templateSource) { var templateKey = function(templateSource) { return templateSource.jquery && templateSource[0] || templateSource }; var cachedTemplate = this._tempTemplates.filter(function(t) { templateSource = templateKey(templateSource); return t.source === templateSource })[0]; if (cachedTemplate) { return cachedTemplate.template } var template = this._createTemplate(templateSource); this._tempTemplates.push({ template: template, source: templateKey(templateSource) }); return template }, _createTemplate: function(templateSource) { templateSource = "string" === typeof templateSource ? domUtils.normalizeTemplateElement(templateSource) : templateSource; return this.option("integrationOptions.createTemplate")(templateSource) }, _getNormalizedTemplateArgs: function(options) { var args = []; if ("model" in options) { args.push(options.model) } if ("index" in options) { args.push(options.index) } args.push(options.container); return args }, _cleanTemplates: function() { this._tempTemplates.forEach(function(t) { t.template.dispose && t.template.dispose() }); this._tempTemplates = [] }, _initContentReadyAction: function() { this._contentReadyAction = this._createActionByOption("onContentReady", { excludeValidators: ["designMode", "disabled", "readOnly"] }) }, _render: function() { this.element().addClass(WIDGET_CLASS); this.callBase(); this._toggleDisabledState(this.option("disabled")); this._toggleVisibility(this.option("visible")); this._renderHint(); this._renderContent(); this._renderFocusState(); this._attachFeedbackEvents(); this._attachHoverEvents() }, _renderHint: function() { domUtils.toggleAttr(this.element(), "title", this.option("hint")) }, _renderContent: function() { var that = this; commonUtils.deferRender(function() { that._renderContentImpl() }); that._fireContentReadyAction() }, _renderContentImpl: commonUtils.noop, _fireContentReadyAction: function() { this._contentReadyAction() }, _dispose: function() { this._cleanTemplates(); this._contentReadyAction = null; this.callBase() }, _clean: function() { this._cleanFocusState(); this.callBase(); this.element().empty() }, _toggleVisibility: function(visible) { this.element().toggleClass(INVISIBLE_STATE_CLASS, !visible); this.setAria("hidden", !visible || void 0) }, _renderFocusState: function() { if (!this.option("focusStateEnabled") || this.option("disabled")) { return } this._renderFocusTarget(); this._attachFocusEvents(); this._attachKeyboardEvents(); this._renderAccessKey() }, _renderAccessKey: function() { var focusTarget = this._focusTarget(); focusTarget.attr("accesskey", this.option("accessKey")); var clickNamespace = eventUtils.addNamespace(clickEvent.name, UI_FEEDBACK); focusTarget.off(clickNamespace); this.option("accessKey") && focusTarget.on(clickNamespace, function(e) { if (eventUtils.isFakeClickEvent(e)) { e.stopImmediatePropagation(); this.focus() } }.bind(this)) }, _eventBindingTarget: function() { return this.element() }, _focusTarget: function() { return this._getActiveElement() }, _getActiveElement: function() { var activeElement = this._eventBindingTarget(); if (this._activeStateUnit) { activeElement = activeElement.find(this._activeStateUnit).not("." + DISABLED_STATE_CLASS) } return activeElement }, _renderFocusTarget: function() { this._focusTarget().attr("tabindex", this.option("tabIndex")) }, _keyboardEventBindingTarget: function() { return this._eventBindingTarget() }, _detachFocusEvents: function() { var $element = this._focusTarget(), namespace = this.NAME + FOCUS_NAMESPACE, focusEvents = eventUtils.addNamespace("focusin", namespace); focusEvents = focusEvents + " " + eventUtils.addNamespace("focusout", namespace); if (beforeActivateExists) { focusEvents = focusEvents + " " + eventUtils.addNamespace("beforeactivate", namespace) } $element.off(focusEvents) }, _attachFocusEvents: function() { var namespace = this.NAME + FOCUS_NAMESPACE, focusInEvent = eventUtils.addNamespace("focusin", namespace), focusOutEvent = eventUtils.addNamespace("focusout", namespace); this._focusTarget().on(focusInEvent, this._focusInHandler.bind(this)).on(focusOutEvent, this._focusOutHandler.bind(this)); if (beforeActivateExists) { var beforeActivateEvent = eventUtils.addNamespace("beforeactivate", namespace); this._focusTarget().on(beforeActivateEvent, function(e) { if (!$(e.target).is(selectors.focusable)) { e.preventDefault() } }) } }, _refreshFocusEvent: function() { this._detachFocusEvents(); this._attachFocusEvents() }, _focusInHandler: function(e) { var that = this; that._createActionByOption("onFocusIn", { beforeExecute: function() { that._updateFocusState(e, true) }, excludeValidators: ["readOnly"] })({ jQueryEvent: e }) }, _focusOutHandler: function(e) { var that = this; that._createActionByOption("onFocusOut", { beforeExecute: function() { that._updateFocusState(e, false) }, excludeValidators: ["readOnly", "disabled"] })({ jQueryEvent: e }) }, _updateFocusState: function(e, isFocused) { var target = e.target; if (inArray(target, this._focusTarget()) !== -1) { this._toggleFocusClass(isFocused, $(target)) } }, _toggleFocusClass: function(isFocused, $element) { var $focusTarget = $element && $element.length ? $element : this._focusTarget(); $focusTarget.toggleClass(FOCUSED_STATE_CLASS, isFocused) }, _hasFocusClass: function(element) { var $focusTarget = $(element || this._focusTarget()); return $focusTarget.hasClass(FOCUSED_STATE_CLASS) }, _attachKeyboardEvents: function() { var processor = this.option("_keyboardProcessor") || new KeyboardProcessor({ element: this._keyboardEventBindingTarget(), focusTarget: this._focusTarget() }); this._keyboardProcessor = processor.reinitialize(this._keyboardHandler, this) }, _keyboardHandler: function(options) { var e = options.originalEvent, key = options.key; var keys = this._supportedKeys(), func = keys[key]; if (void 0 !== func) { var handler = func.bind(this); return handler(e) || false } else { return true } }, _refreshFocusState: function() { this._cleanFocusState(); this._renderFocusState() }, _cleanFocusState: function() { var $element = this._focusTarget(); this._detachFocusEvents(); this._toggleFocusClass(false); $element.removeAttr("tabindex"); if (this._keyboardProcessor) { this._keyboardProcessor.dispose() } }, _attachHoverEvents: function() { var that = this, hoverableSelector = that._activeStateUnit, nameStart = eventUtils.addNamespace(hoverEvents.start, UI_FEEDBACK), nameEnd = eventUtils.addNamespace(hoverEvents.end, UI_FEEDBACK); that._eventBindingTarget().off(nameStart, hoverableSelector).off(nameEnd, hoverableSelector); if (that.option("hoverStateEnabled")) { var startAction = new Action(function(args) { that._hoverStartHandler(args.event); var $target = args.element; that._refreshHoveredElement($target) }, { excludeValidators: ["readOnly"] }); that._eventBindingTarget().on(nameStart, hoverableSelector, function(e) { startAction.execute({ element: $(e.target), event: e }) }).on(nameEnd, hoverableSelector, function(e) { that._hoverEndHandler(e); that._forgetHoveredElement() }) } else { that._toggleHoverClass(false) } }, _hoverStartHandler: commonUtils.noop, _hoverEndHandler: commonUtils.noop, _attachFeedbackEvents: function() { var feedbackAction, feedbackActionDisabled, that = this, feedbackSelector = that._activeStateUnit, activeEventName = eventUtils.addNamespace(feedbackEvents.active, UI_FEEDBACK), inactiveEventName = eventUtils.addNamespace(feedbackEvents.inactive, UI_FEEDBACK); that._eventBindingTarget().off(activeEventName, feedbackSelector).off(inactiveEventName, feedbackSelector); if (that.option("activeStateEnabled")) { var feedbackActionHandler = function(args) { var $element = args.element, value = args.value, jQueryEvent = args.jQueryEvent; that._toggleActiveState($element, value, jQueryEvent) }; that._eventBindingTarget().on(activeEventName, feedbackSelector, { timeout: that._feedbackShowTimeout }, function(e) { feedbackAction = feedbackAction || new Action(feedbackActionHandler); feedbackAction.execute({ element: $(e.currentTarget), value: true, jQueryEvent: e }) }).on(inactiveEventName, feedbackSelector, { timeout: that._feedbackHideTimeout }, function(e) { feedbackActionDisabled = feedbackActionDisabled || new Action(feedbackActionHandler, { excludeValidators: ["disabled", "readOnly"] }); feedbackActionDisabled.execute({ element: $(e.currentTarget), value: false, jQueryEvent: e }) }) } }, _toggleActiveState: function($element, value) { this._toggleHoverClass(!value); $element.toggleClass(ACTIVE_STATE_CLASS, value) }, _refreshHoveredElement: function(hoveredElement) { var selector = this._activeStateUnit || this._eventBindingTarget(); this._forgetHoveredElement(); this._hoveredElement = hoveredElement.closest(selector); this._toggleHoverClass(true) }, _forgetHoveredElement: function() { this._toggleHoverClass(false); delete this._hoveredElement }, _toggleHoverClass: function(value) { if (this._hoveredElement) { this._hoveredElement.toggleClass(HOVER_STATE_CLASS, value && this.option("hoverStateEnabled")) } }, _toggleDisabledState: function(value) { this.element().toggleClass(DISABLED_STATE_CLASS, Boolean(value)); this._toggleHoverClass(!value); this.setAria("disabled", value || void 0) }, _setWidgetOption: function(widgetName, args) { if (!this[widgetName]) { return } if (typeUtils.isPlainObject(args[0])) { $.each(args[0], function(option, value) { this._setWidgetOption(widgetName, [option, value]) }.bind(this)); return } var optionName = args[0]; var value = args[1]; if (1 === args.length) { value = this.option(optionName) } var widgetOptionMap = this[widgetName + "OptionMap"]; this[widgetName].option(widgetOptionMap ? widgetOptionMap(optionName) : optionName, value) }, _optionChanged: function(args) { switch (args.name) { case "disabled": this._toggleDisabledState(args.value); this._refreshFocusState(); break; case "hint": this._renderHint(); break; case "activeStateEnabled": this._attachFeedbackEvents(); break; case "hoverStateEnabled": this._attachHoverEvents(); break; case "tabIndex": case "_keyboardProcessor": case "focusStateEnabled": this._refreshFocusState(); break; case "onFocusIn": case "onFocusOut": break; case "accessKey": this._renderAccessKey(); break; case "visible": var visible = args.value; this._toggleVisibility(visible); if (this._isVisibilityChangeSupported()) { this._checkVisibilityChanged(args.value ? "shown" : "hiding") } break; case "onContentReady": this._initContentReadyAction(); break; default: this.callBase(args) } }, _isVisible: function() { return this.callBase() && this.option("visible") }, beginUpdate: function() { this._ready(false); this.callBase() }, endUpdate: function() { this.callBase(); if (this._initialized) { this._ready(true) } }, _ready: function(value) { if (0 === arguments.length) { return this._isReady } this._isReady = value }, setAria: function() { var setAttribute = function(option) { var attrName = "role" === option.name || "id" === option.name ? option.name : "aria-" + option.name, attrValue = option.value; if (null === attrValue || void 0 === attrValue) { attrValue = void 0 } else { attrValue = attrValue.toString() } domUtils.toggleAttr(option.target, attrName, attrValue) }; if (!typeUtils.isPlainObject(arguments[0])) { setAttribute({ name: arguments[0], value: arguments[1], target: arguments[2] || this._getAriaTarget() }) } else { var $target = arguments[1] || this._getAriaTarget(); $.each(arguments[0], function(key, value) { setAttribute({ name: key, value: value, target: $target }) }) } }, isReady: function() { return this._ready() }, repaint: function() { this._refresh() }, focus: function() { this._focusTarget().focus() }, registerKeyHandler: function(key, handler) { var currentKeys = this._supportedKeys(), addingKeys = {}; addingKeys[key] = handler; this._supportedKeys = function() { return extend(currentKeys, addingKeys) } } }); module.exports = Widget }, /*!*****************************************!*\ !*** ./js/ui/widget/jquery.template.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), errors = __webpack_require__( /*! ../../core/errors */ 7), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), TemplateBase = __webpack_require__( /*! ./ui.template_base */ 97), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56); var templateEngines = {}; var registerTemplateEngine = function(name, templateEngine) { templateEngines[name] = templateEngine }; var outerHtml = function(element) { element = $(element); var templateTag = element.length && element[0].nodeName.toLowerCase(); if ("script" === templateTag) { return element.html() } else { element = $("<div>").append(element); return element.html() } }; registerTemplateEngine("default", { compile: function(element) { return domUtils.normalizeTemplateElement(element) }, render: function(template) { return template.clone() } }); registerTemplateEngine("jquery-tmpl", { compile: function(element) { return outerHtml(element) }, render: function(template, data) { return $.tmpl(template, data) } }); registerTemplateEngine("jsrender", { compile: function(element) { return $.templates(outerHtml(element)) }, render: function(template, data) { return template.render(data) } }); registerTemplateEngine("mustache", { compile: function(element) { return outerHtml(element) }, render: function(template, data) { return Mustache.render(template, data) } }); registerTemplateEngine("hogan", { compile: function(element) { return Hogan.compile(outerHtml(element)) }, render: function(template, data) { return template.render(data) } }); registerTemplateEngine("underscore", { compile: function(element) { return _.template(outerHtml(element)) }, render: function(template, data) { return template(data) } }); registerTemplateEngine("handlebars", { compile: function(element) { return Handlebars.compile(outerHtml(element)) }, render: function(template, data) { return template(data) } }); registerTemplateEngine("doT", { compile: function(element) { return doT.template(outerHtml(element)) }, render: function(template, data) { return template(data) } }); var currentTemplateEngine; var setTemplateEngine = function(templateEngine) { if (commonUtils.isString(templateEngine)) { currentTemplateEngine = templateEngines[templateEngine]; if (!currentTemplateEngine) { throw errors.Error("E0020", templateEngine) } } else { currentTemplateEngine = templateEngine } }; setTemplateEngine("default"); var Template = TemplateBase.inherit({ ctor: function(element) { this._element = element; this._compiledTemplate = currentTemplateEngine.compile(element) }, _renderCore: function(options) { return $("<div>").append(currentTemplateEngine.render(this._compiledTemplate, options.model)).contents() }, source: function() { return $(this._element).clone() } }); module.exports = Template; module.exports.setTemplateEngine = setTemplateEngine }, /*!******************************************!*\ !*** ./js/ui/widget/ui.template_base.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), triggerShownEvent = __webpack_require__( /*! ../../core/utils/dom */ 56).triggerShownEvent, Class = __webpack_require__( /*! ../../core/class */ 25), abstract = Class.abstract; var renderedCallbacks = $.Callbacks(); var TemplateBase = Class.inherit({ render: function(options) { options = options || {}; var $result = this._renderCore(options); this._ensureResultInContainer($result, options.container); renderedCallbacks.fire($result, options.container); return $result }, _ensureResultInContainer: function($result, $container) { if (!$container) { return } var resultInContainer = $.contains($container.get(0), $result.get(0)); $container.append($result); if (resultInContainer) { return } var resultInBody = $.contains(document.body, $container.get(0)); if (!resultInBody) { return } triggerShownEvent($result) }, _renderCore: abstract }); module.exports = TemplateBase; module.exports.renderedCallbacks = renderedCallbacks }, /*!*******************************************!*\ !*** ./js/ui/widget/function_template.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var TemplateBase = __webpack_require__( /*! ./ui.template_base */ 97), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56); var FunctionTemplate = TemplateBase.inherit({ ctor: function(render) { this._render = render }, _renderCore: function(options) { return domUtils.normalizeTemplateElement(this._render(options)) } }); module.exports = FunctionTemplate }, /*!****************************************!*\ !*** ./js/ui/widget/empty_template.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), TemplateBase = __webpack_require__( /*! ./ui.template_base */ 97); var EmptyTemplate = TemplateBase.inherit({ _renderCore: function() { return $() } }); module.exports = EmptyTemplate }, /*!************************************************!*\ !*** ./js/ui/widget/child_default_template.js ***! \************************************************/ function(module, exports, __webpack_require__) { var TemplateBase = __webpack_require__( /*! ./ui.template_base */ 97); module.exports = TemplateBase.inherit({ ctor: function(name) { this.name = name } }) }, /*!***********************************************!*\ !*** ./js/ui/widget/ui.keyboard_processor.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, eventUtils = __webpack_require__( /*! ../../events/utils */ 71); var KeyboardProcessor = Class.inherit({ _keydown: eventUtils.addNamespace("keydown", "KeyboardProcessor"), codes: { 8: "backspace", 9: "tab", 13: "enter", 27: "escape", 33: "pageUp", 34: "pageDown", 35: "end", 36: "home", 37: "leftArrow", 38: "upArrow", 39: "rightArrow", 40: "downArrow", 46: "del", 32: "space", 70: "F", 65: "A", 106: "asterisk", 109: "minus" }, ctor: function(options) { var _this = this; options = options || {}; if (options.element) { this._element = $(options.element) } if (options.focusTarget) { this._focusTarget = options.focusTarget } this._handler = options.handler; this._context = options.context; this._childProcessors = []; if (this._element) { this._processFunction = function(e) { _this.process(e) }; this._element.on(this._keydown, this._processFunction) } }, dispose: function() { if (this._element) { this._element.off(this._keydown, this._processFunction) } this._element = void 0; this._handler = void 0; this._context = void 0; this._childProcessors = void 0 }, clearChildren: function() { this._childProcessors = [] }, push: function(child) { if (!this._childProcessors) { this.clearChildren() } this._childProcessors.push(child); return child }, attachChildProcessor: function() { var childProcessor = new KeyboardProcessor; this._childProcessors.push(childProcessor); return childProcessor }, reinitialize: function(childHandler, childContext) { this._context = childContext; this._handler = childHandler; return this }, process: function(e) { if (this._focusTarget && this._focusTarget !== e.target && inArray(e.target, this._focusTarget) < 0) { return false } var args = { key: this.codes[e.which] || e.which, ctrl: e.ctrlKey, shift: e.shiftKey, alt: e.altKey, originalEvent: e }; var handlerResult = this._handler && this._handler.call(this._context, args); if (handlerResult && this._childProcessors) { $.each(this._childProcessors, function(index, childProcessor) { childProcessor.process(e) }) } } }); module.exports = KeyboardProcessor }, /*!******************************************!*\ !*** ./js/ui/widget/jquery.selectors.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var focusable = function(element, tabIndex) { if (!visible(element)) { return false } var nodeName = element.nodeName.toLowerCase(), isTabIndexNotNaN = !isNaN(tabIndex), isDisabled = element.disabled, isDefaultFocus = /^(input|select|textarea|button|object|iframe)$/.test(nodeName), isHyperlink = "a" === nodeName, isFocusable = true; if (isDefaultFocus) { isFocusable = !isDisabled } else { if (isHyperlink) { isFocusable = element.href || isTabIndexNotNaN } else { isFocusable = isTabIndexNotNaN } } return isFocusable }; var visible = function(element) { var $element = $(element); return $element.is(":visible") && "hidden" !== $element.css("visibility") && "hidden" !== $element.parents().css("visibility") }; module.exports = { focusable: function(index, element) { return focusable(element, $(element).attr("tabindex")) }, tabbable: function(index, element) { var tabIndex = $(element).attr("tabindex"); return (isNaN(tabIndex) || tabIndex >= 0) && focusable(element, tabIndex) } } }, /*!****************************!*\ !*** ./js/events/hover.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), devices = __webpack_require__( /*! ../core/devices */ 53), registerEvent = __webpack_require__( /*! ./core/event_registrator */ 73), eventUtils = __webpack_require__( /*! ./utils */ 71), pointerEvents = __webpack_require__( /*! ./pointer */ 76); var HOVERSTART_NAMESPACE = "dxHoverStart", HOVERSTART = "dxhoverstart", POINTERENTER_NAMESPACED_EVENT_NAME = eventUtils.addNamespace(pointerEvents.enter, HOVERSTART_NAMESPACE), HOVEREND_NAMESPACE = "dxHoverEnd", HOVEREND = "dxhoverend", POINTERLEAVE_NAMESPACED_EVENT_NAME = eventUtils.addNamespace(pointerEvents.leave, HOVEREND_NAMESPACE); var Hover = Class.inherit({ noBubble: true, ctor: function() { this._handlerArrayKeyPath = this._eventNamespace + "_HandlerStore" }, setup: function(element) { $.data(element, this._handlerArrayKeyPath, {}) }, add: function(element, handleObj) { var that = this, $element = $(element), handler = function(e) { that._handler(e) }; $element.on(this._originalEventName, handleObj.selector, handler); $.data(element, this._handlerArrayKeyPath)[handleObj.guid] = handler }, _handler: function(e) { if (eventUtils.isTouchEvent(e) || devices.isSimulator()) { return } eventUtils.fireEvent({ type: this._eventName, originalEvent: e, delegateTarget: e.delegateTarget }) }, remove: function(element, handleObj) { var handler = $.data(element, this._handlerArrayKeyPath)[handleObj.guid]; $(element).off(this._originalEventName, handleObj.selector, handler) }, teardown: function(element) { $.removeData(element, this._handlerArrayKeyPath) } }); var HoverStart = Hover.inherit({ ctor: function() { this._eventNamespace = HOVERSTART_NAMESPACE; this._eventName = HOVERSTART; this._originalEventName = POINTERENTER_NAMESPACED_EVENT_NAME; this.callBase() }, _handler: function(e) { var pointers = e.pointers || []; if (!pointers.length) { this.callBase(e) } } }); var HoverEnd = Hover.inherit({ ctor: function() { this._eventNamespace = HOVEREND_NAMESPACE; this._eventName = HOVEREND; this._originalEventName = POINTERLEAVE_NAMESPACED_EVENT_NAME; this.callBase() } }); registerEvent(HOVERSTART, new HoverStart); registerEvent(HOVEREND, new HoverEnd); exports.start = HOVERSTART; exports.end = HOVEREND }, /*!********************************************!*\ !*** ./js/events/core/emitter.feedback.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), devices = __webpack_require__( /*! ../../core/devices */ 53), eventUtils = __webpack_require__( /*! ../utils */ 71), pointerEvents = __webpack_require__( /*! ../pointer */ 76), Emitter = __webpack_require__( /*! ./emitter */ 83), registerEmitter = __webpack_require__( /*! ./emitter_registrator */ 84); var ACTIVE_EVENT_NAME = "dxactive", INACTIVE_EVENT_NAME = "dxinactive", ACTIVE_TIMEOUT = 30, INACTIVE_TIMEOUT = 400; var FeedbackEvent = Class.inherit({ ctor: function(timeout, fire) { this._timeout = timeout; this._fire = fire }, start: function() { var that = this; this._schedule(function() { that.force() }) }, _schedule: function(fn) { this.stop(); this._timer = window.setTimeout(fn, this._timeout) }, stop: function() { clearTimeout(this._timer) }, force: function() { if (this._fired) { return } this.stop(); this._fire(); this._fired = true }, fired: function() { return this._fired } }); var activeFeedback; var FeedbackEmitter = Emitter.inherit({ ctor: function() { this.callBase.apply(this, arguments); this._active = new FeedbackEvent(0, commonUtils.noop); this._inactive = new FeedbackEvent(0, commonUtils.noop) }, configure: function(data, eventName) { switch (eventName) { case ACTIVE_EVENT_NAME: data.activeTimeout = data.timeout; break; case INACTIVE_EVENT_NAME: data.inactiveTimeout = data.timeout } this.callBase(data) }, start: function(e) { if (activeFeedback) { var activeChildExists = $.contains(this.getElement().get(0), activeFeedback.getElement().get(0)); var childJustActivated = !activeFeedback._active.fired(); if (activeChildExists && childJustActivated) { this._cancel(); return } activeFeedback._inactive.force() } activeFeedback = this; this._initEvents(e); this._active.start() }, _initEvents: function(e) { var that = this, eventTarget = this._getEmitterTarget(e), mouseEvent = eventUtils.isMouseEvent(e), isSimulator = devices.isSimulator(), deferFeedback = isSimulator || !mouseEvent, activeTimeout = commonUtils.ensureDefined(this.activeTimeout, ACTIVE_TIMEOUT), inactiveTimeout = commonUtils.ensureDefined(this.inactiveTimeout, INACTIVE_TIMEOUT); this._active = new FeedbackEvent(deferFeedback ? activeTimeout : 0, function() { that._fireEvent(ACTIVE_EVENT_NAME, e, { target: eventTarget }) }); this._inactive = new FeedbackEvent(deferFeedback ? inactiveTimeout : 0, function() { that._fireEvent(INACTIVE_EVENT_NAME, e, { target: eventTarget }); activeFeedback = null }) }, cancel: function(e) { this.end(e) }, end: function(e) { var skipTimers = e.type !== pointerEvents.up; if (skipTimers) { this._active.stop() } else { this._active.force() } this._inactive.start(); if (skipTimers) { this._inactive.force() } }, dispose: function() { this._active.stop(); this._inactive.stop(); this.callBase() }, lockInactive: function() { this._active.force(); this._inactive.stop(); activeFeedback = null; this._cancel(); return this._inactive.force.bind(this._inactive) } }); FeedbackEmitter.lock = function(deferred) { var lockInactive = activeFeedback ? activeFeedback.lockInactive() : commonUtils.noop; deferred.done(lockInactive) }; registerEmitter({ emitter: FeedbackEmitter, events: [ACTIVE_EVENT_NAME, INACTIVE_EVENT_NAME] }); exports.lock = FeedbackEmitter.lock; exports.active = ACTIVE_EVENT_NAME; exports.inactive = INACTIVE_EVENT_NAME }, /*!*********************************************!*\ !*** ./js/integration/knockout/template.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ko = __webpack_require__( /*! knockout */ 93), TemplateBase = __webpack_require__( /*! ../../ui/widget/ui.template_base */ 97), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56); var KoTemplate = TemplateBase.inherit({ ctor: function(element) { this._element = element; this._template = $("<div>").append(domUtils.normalizeTemplateElement(element)); this._registerKoTemplate() }, _registerKoTemplate: function() { var template = this._template.get(0); new ko.templateSources.anonymousTemplate(template).nodes(template) }, _prepareDataForContainer: function(data, container) { var containerElement, containerContext, result = data; if (container.length) { containerElement = container.get(0); data = void 0 !== data ? data : ko.dataFor(containerElement) || {}; containerContext = ko.contextFor(containerElement); if (containerContext) { result = data === containerContext.$data ? containerContext : containerContext.createChildContext(data) } else { result = data } } return result }, _renderCore: function(options) { var model = options.model; if (options.container) { model = this._prepareDataForContainer(model, options.container) } var $placeholder = $("<div>").appendTo(options.container); var $result; ko.renderTemplate(this._template.get(0), model, { afterRender: function(nodes) { $result = $(nodes) } }, $placeholder.get(0), "replaceNode"); return $result }, source: function() { return $(this._element).clone() }, dispose: function() { this._template.remove() } }); module.exports = KoTemplate }, /*!********************************!*\ !*** ./js/ui/editor/editor.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), getDefaultAlignment = __webpack_require__( /*! ../../core/utils/position */ 107).getDefaultAlignment, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, Widget = __webpack_require__( /*! ../widget/ui.widget */ 95), ValidationMixin = __webpack_require__( /*! ../validation/validation_mixin */ 108), Overlay = __webpack_require__( /*! ../overlay */ 109); var READONLY_STATE_CLASS = "dx-state-readonly", INVALID_CLASS = "dx-invalid", INVALID_MESSAGE = "dx-invalid-message", INVALID_MESSAGE_AUTO = "dx-invalid-message-auto", INVALID_MESSAGE_ALWAYS = "dx-invalid-message-always", VALIDATION_TARGET = "dx-validation-target", VALIDATION_MESSAGE_MIN_WIDTH = 100; var Editor = Widget.inherit({ _init: function() { this.callBase(); this.validationRequest = $.Callbacks(); var $element = this.element(); if ($element) { $.data($element[0], VALIDATION_TARGET, this) } }, _getDefaultOptions: function() { return extend(this.callBase(), { value: null, name: "", onValueChanged: null, readOnly: false, isValid: true, validationError: null, validationMessageMode: "auto", validationBoundary: void 0, validationMessageOffset: { h: 0, v: 0 } }) }, _attachKeyboardEvents: function() { if (this.option("readOnly")) { return } this.callBase(); this._attachChildKeyboardEvents() }, _attachChildKeyboardEvents: commonUtils.noop, _setOptionsByReference: function() { this.callBase(); extend(this._optionsByReference, { validationError: true }) }, _createValueChangeAction: function() { this._valueChangeAction = this._createActionByOption("onValueChanged", { excludeValidators: ["disabled", "readOnly"] }) }, _suppressValueChangeAction: function() { this._valueChangeActionSuppressed = true }, _resumeValueChangeAction: function() { this._valueChangeActionSuppressed = false }, _render: function() { this.callBase(); this._renderValidationState(); this._toggleReadOnlyState(); this._setSubmitElementName(this.option("name")) }, _raiseValueChangeAction: function(value, previousValue) { if (!this._valueChangeAction) { this._createValueChangeAction() } this._valueChangeAction(this._valueChangeArgs(value, previousValue)) }, _valueChangeArgs: function(value, previousValue) { return { value: value, previousValue: previousValue, jQueryEvent: this._valueChangeEventInstance } }, _saveValueChangeEvent: function(e) { this._valueChangeEventInstance = e }, _renderValidationState: function() { var isValid = this.option("isValid"), validationError = this.option("validationError"), validationMessageMode = this.option("validationMessageMode"), $element = this.element(); $element.toggleClass(INVALID_CLASS, !isValid); this.setAria("invalid", !isValid || void 0); if (this._$validationMessage) { this._$validationMessage.remove(); this._$validationMessage = null } if (!isValid && validationError && validationError.message) { this._$validationMessage = $("<div/>", { "class": INVALID_MESSAGE }).html(validationError.message).appendTo($element); this._validationMessage = this._createComponent(this._$validationMessage, Overlay, { integrationOptions: {}, templatesRenderAsynchronously: false, target: this._getValidationMessageTarget(), shading: false, width: "auto", height: "auto", container: $element, position: this._getValidationMessagePosition("below"), closeOnOutsideClick: false, closeOnTargetScroll: false, animation: null, visible: true, propagateOutsideClick: true, _checkParentVisibility: false }); this._$validationMessage.toggleClass(INVALID_MESSAGE_AUTO, "auto" === validationMessageMode).toggleClass(INVALID_MESSAGE_ALWAYS, "always" === validationMessageMode); this._setValidationMessageMaxWidth() } }, _setValidationMessageMaxWidth: function() { if (!this._validationMessage) { return } if (0 === this._getValidationMessageTarget().outerWidth()) { this._validationMessage.option("maxWidth", "100%"); return } var validationMessageMaxWidth = Math.max(VALIDATION_MESSAGE_MIN_WIDTH, this._getValidationMessageTarget().outerWidth()); this._validationMessage.option("maxWidth", validationMessageMaxWidth) }, _getValidationMessageTarget: function() { return this.element() }, _getValidationMessagePosition: function(positionRequest) { var rtlEnabled = this.option("rtlEnabled"), messagePositionSide = getDefaultAlignment(rtlEnabled), messageOriginalOffset = this.option("validationMessageOffset"), messageOffset = { h: messageOriginalOffset.h, v: messageOriginalOffset.v }, verticalPositions = "below" === positionRequest ? [" top", " bottom"] : [" bottom", " top"]; if (rtlEnabled) { messageOffset.h = -messageOffset.h } if ("below" !== positionRequest) { messageOffset.v = -messageOffset.v } return { offset: messageOffset, boundary: this.option("validationBoundary"), my: messagePositionSide + verticalPositions[0], at: messagePositionSide + verticalPositions[1], collision: "none flip" } }, _toggleReadOnlyState: function() { this.element().toggleClass(READONLY_STATE_CLASS, !!this.option("readOnly")); this.setAria("readonly", this.option("readOnly") || void 0) }, _dispose: function() { var element = this.element()[0]; $.data(element, VALIDATION_TARGET, null); this.callBase() }, _setSubmitElementName: function(name) { var $submitElement = this._getSubmitElement(); if (!$submitElement) { return } if (name.length > 0) { $submitElement.attr("name", name) } else { $submitElement.removeAttr("name") } }, _getSubmitElement: function() { return null }, _optionChanged: function(args) { switch (args.name) { case "onValueChanged": this._createValueChangeAction(); break; case "isValid": case "validationError": case "validationBoundary": case "validationMessageMode": this._renderValidationState(); break; case "readOnly": this._toggleReadOnlyState(); this._refreshFocusState(); break; case "value": if (!this._valueChangeActionSuppressed) { this._raiseValueChangeAction(args.value, args.previousValue); this._saveValueChangeEvent(void 0) } if (args.value != args.previousValue) { this.validationRequest.fire({ value: args.value, editor: this }) } break; case "width": this.callBase(args); this._setValidationMessageMaxWidth(); break; case "name": this._setSubmitElementName(args.value); break; default: this.callBase(args) } }, reset: function() { this.option("value", null) } }).include(ValidationMixin); module.exports = Editor }, /*!***********************************!*\ !*** ./js/core/utils/position.js ***! \***********************************/ function(module, exports, __webpack_require__) { var config = __webpack_require__( /*! ../config */ 15); var getDefaultAlignment = function(isRtlEnabled) { var rtlEnabled = isRtlEnabled || config().rtlEnabled; return rtlEnabled ? "right" : "left" }; exports.getDefaultAlignment = getDefaultAlignment }, /*!**********************************************!*\ !*** ./js/ui/validation/validation_mixin.js ***! \**********************************************/ function(module, exports) { var ValidationMixin = { _findGroup: function() { var $dxGroup, group = this.option("validationGroup"); if (!group) { $dxGroup = this.element().parents(".dx-validationgroup").first(); if ($dxGroup.length) { group = $dxGroup.dxValidationGroup("instance") } else { group = this._modelByElement(this.element()) } } return group } }; module.exports = ValidationMixin }, /*!**************************!*\ !*** ./js/ui/overlay.js ***! \**************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), fx = __webpack_require__( /*! ../animation/fx */ 68), translator = __webpack_require__( /*! ../animation/translator */ 69), compareVersions = __webpack_require__( /*! ../core/utils/version */ 17).compare, viewPortUtils = __webpack_require__( /*! ../core/utils/view_port */ 55), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, viewPortChanged = viewPortUtils.changeCallback, hideTopOverlayCallback = __webpack_require__( /*! ../mobile/hide_top_overlay */ 65).hideCallback, positionUtils = __webpack_require__( /*! ../animation/position */ 70), fitIntoRange = __webpack_require__( /*! ../core/utils/math */ 87).fitIntoRange, domUtils = __webpack_require__( /*! ../core/utils/dom */ 56), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), devices = __webpack_require__( /*! ../core/devices */ 53), registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), Widget = __webpack_require__( /*! ./widget/ui.widget */ 95), KeyboardProcessor = __webpack_require__( /*! ./widget/ui.keyboard_processor */ 101), selectors = __webpack_require__( /*! ./widget/jquery.selectors */ 102), dragEvents = __webpack_require__( /*! ../events/drag */ 110), eventUtils = __webpack_require__( /*! ../events/utils */ 71), pointerEvents = __webpack_require__( /*! ../events/pointer */ 76), Resizable = __webpack_require__( /*! ./resizable */ 111), EmptyTemplate = __webpack_require__( /*! ./widget/empty_template */ 99); var OVERLAY_CLASS = "dx-overlay", OVERLAY_WRAPPER_CLASS = "dx-overlay-wrapper", OVERLAY_CONTENT_CLASS = "dx-overlay-content", OVERLAY_SHADER_CLASS = "dx-overlay-shader", OVERLAY_MODAL_CLASS = "dx-overlay-modal", INVISIBLE_STATE_CLASS = "dx-state-invisible", ANONYMOUS_TEMPLATE_NAME = "content", RTL_DIRECTION_CLASS = "dx-rtl", ACTIONS = ["onShowing", "onShown", "onHiding", "onHidden", "onPositioning", "onPositioned", "onResizeStart", "onResize", "onResizeEnd"], FIRST_Z_INDEX = 1500, OVERLAY_STACK = [], DISABLED_STATE_CLASS = "dx-state-disabled", TAB_KEY = 9; var realDevice = devices.real(), realVersion = realDevice.version, iOS = "ios" === realDevice.platform, iOS7_0andBelow = iOS && compareVersions(realVersion, [7, 1]) < 0, android4_0nativeBrowser = "android" === realDevice.platform && 0 === compareVersions(realVersion, [4, 0], 2) && navigator.userAgent.indexOf("Chrome") === -1; var forceRepaint = function($element) { if (iOS7_0andBelow) { $element.width() } if (android4_0nativeBrowser) { var $parents = $element.parents(), inScrollView = $parents.is(".dx-scrollable-native"); if (!inScrollView) { $parents.css("backface-visibility", "hidden"); $parents.css("backface-visibility"); $parents.css("backface-visibility", "visible") } } }; var getElement = function(value) { return value && $(value instanceof $.Event ? value.target : value) }; $(document).on(pointerEvents.down, function(e) { for (var i = OVERLAY_STACK.length - 1; i >= 0; i--) { if (!OVERLAY_STACK[i]._proxiedDocumentDownHandler(e)) { return } } }); var Overlay = Widget.inherit({ _supportedKeys: function() { var offsetSize = 5, move = function(top, left, e) { if (!this.option("dragEnabled")) { return } e.preventDefault(); e.stopPropagation(); var allowedOffsets = this._allowedOffsets(); var offset = { top: fitIntoRange(top, -allowedOffsets.top, allowedOffsets.bottom), left: fitIntoRange(left, -allowedOffsets.left, allowedOffsets.right) }; this._changePosition(offset) }; return extend(this.callBase(), { escape: function() { this.hide() }, upArrow: move.bind(this, -offsetSize, 0), downArrow: move.bind(this, offsetSize, 0), leftArrow: move.bind(this, 0, -offsetSize), rightArrow: move.bind(this, 0, offsetSize) }) }, _getDefaultOptions: function() { return extend(this.callBase(), { activeStateEnabled: false, visible: false, deferRendering: true, shading: true, shadingColor: "", position: { my: "center", at: "center" }, width: function() { return .8 * $(window).width() }, minWidth: null, maxWidth: null, height: function() { return .8 * $(window).height() }, minHeight: null, maxHeight: null, animation: { show: { type: "pop", duration: 300, from: { scale: .55 } }, hide: { type: "pop", duration: 300, to: { opacity: 0, scale: .55 }, from: { opacity: 1, scale: 1 } } }, closeOnOutsideClick: false, closeOnBackButton: true, onShowing: null, onShown: null, onHiding: null, onHidden: null, contentTemplate: "content", dragEnabled: false, resizeEnabled: false, onResizeStart: null, onResize: null, onResizeEnd: null, onContentReady: null, target: void 0, container: void 0, hideTopOverlayHandler: void 0, closeOnTargetScroll: false, onPositioned: null, boundaryOffset: { h: 0, v: 0 }, propagateOutsideClick: false, _checkParentVisibility: true }) }, _defaultOptionsRules: function() { return this.callBase().concat([{ device: function() { var realDevice = devices.real(), realPlatform = realDevice.platform, realVersion = realDevice.version; return "android" === realPlatform && compareVersions(realVersion, [4, 2]) < 0 }, options: { animation: { show: { type: "fade", duration: 400 }, hide: { type: "fade", duration: 400, to: { opacity: 0 }, from: { opacity: 1 } } } } }]) }, _setOptionsByReference: function() { this.callBase(); extend(this._optionsByReference, { animation: true }) }, _getAnonymousTemplateName: function() { return ANONYMOUS_TEMPLATE_NAME }, _wrapper: function() { return this._$wrapper }, _container: function() { return this._$content }, _eventBindingTarget: function() { return this._$content }, _init: function() { this.callBase(); this._initActions(); this._initCloseOnOutsideClickHandler(); this._initTabTerminatorHandler(); this._$wrapper = $("<div>").addClass(OVERLAY_WRAPPER_CLASS); this._$content = $("<div>").addClass(OVERLAY_CONTENT_CLASS); var $element = this.element(); this._$wrapper.addClass($element.attr("class")); $element.addClass(OVERLAY_CLASS); this._$wrapper.attr("data-bind", "dxControlsDescendantBindings: true"); this._$wrapper.on("MSPointerDown", commonUtils.noop); this._$wrapper.on("focusin", function(e) { e.stopPropagation() }); this._toggleViewPortSubscription(true) }, _initOptions: function(options) { this._initTarget(options.target); this._initContainer(options.container); this._initHideTopOverlayHandler(options.hideTopOverlayHandler); this.callBase(options) }, _initTarget: function(target) { if (!commonUtils.isDefined(target)) { return } var options = this.option(); $.each(["position.of", "animation.show.from.position.of", "animation.show.to.position.of", "animation.hide.from.position.of", "animation.hide.to.position.of"], function(_, path) { var pathParts = path.split("."); var option = options; while (option) { if (1 === pathParts.length) { if (typeUtils.isPlainObject(option)) { option[pathParts.shift()] = target } break } else { option = option[pathParts.shift()] } } }) }, _initContainer: function(container) { container = void 0 === container ? viewPortUtils.value() : container; var $element = this.element(), $container = $element.closest(container); if (!$container.length) { $container = $(container).first() } this._$container = $container.length ? $container : $element.parent() }, _initHideTopOverlayHandler: function(handler) { this._hideTopOverlayHandler = void 0 !== handler ? handler : this._defaultHideTopOverlayHandler.bind(this) }, _defaultHideTopOverlayHandler: function() { this.hide() }, _initActions: function() { this._actions = {}; $.each(ACTIONS, function(_, action) { this._actions[action] = this._createActionByOption(action, { excludeValidators: ["disabled", "readOnly"] }) || commonUtils.noop }.bind(this)) }, _initCloseOnOutsideClickHandler: function() { var that = this; this._proxiedDocumentDownHandler = function() { return that._documentDownHandler.apply(that, arguments) } }, _documentDownHandler: function(e) { if (this._showAnimationProcessing) { this._stopAnimation() } var closeOnOutsideClick = this.option("closeOnOutsideClick"); if (commonUtils.isFunction(closeOnOutsideClick)) { closeOnOutsideClick = closeOnOutsideClick(e) } if (closeOnOutsideClick) { var $container = this._$content, outsideClick = !$container.is(e.target) && !$.contains($container.get(0), e.target) && $(e.target).closest(document).length; if (outsideClick) { if (this.option("shading")) { e.preventDefault() } this.hide() } } return this.option("propagateOutsideClick") }, _initTemplates: function() { this.callBase(); this._defaultTemplates.content = new EmptyTemplate(this) }, _isTopOverlay: function() { var overlayStack = this._overlayStack(); return overlayStack[overlayStack.length - 1] === this }, _overlayStack: function() { return OVERLAY_STACK }, _zIndexInitValue: function() { return FIRST_Z_INDEX }, _toggleViewPortSubscription: function(toggle) { viewPortChanged.remove(this._viewPortChangeHandle); if (toggle) { this._viewPortChangeHandle = this._viewPortChangeHandler.bind(this); viewPortChanged.add(this._viewPortChangeHandle) } }, _viewPortChangeHandler: function() { this._initContainer(this.option("container")); this._refresh() }, _renderVisibilityAnimate: function(visible) { this._stopAnimation(); return visible ? this._show() : this._hide() }, _normalizePosition: function() { this._position = this.option("position") }, _getAnimationConfig: function() { var animation = this.option("animation"); if (commonUtils.isFunction(animation)) { animation = animation.call(this) } return animation }, _show: function() { var that = this, deferred = $.Deferred(); this._parentHidden = this._isParentHidden(); deferred.done(function() { delete that._parentHidden }); if (this._parentHidden) { return deferred.resolve() } if (this._currentVisible) { return $.Deferred().resolve().promise() } this._currentVisible = true; this._normalizePosition(); var animation = that._getAnimationConfig() || {}, showAnimation = this._normalizeAnimation(animation.show, "to"), startShowAnimation = showAnimation && showAnimation.start || commonUtils.noop, completeShowAnimation = showAnimation && showAnimation.complete || commonUtils.noop; if (this._isHidingActionCanceled) { delete this._isHidingActionCanceled; deferred.resolve() } else { var show = function() { this._renderVisibility(true); this._animate(showAnimation, function() { if (that.option("focusStateEnabled")) { that._focusTarget().focus() } completeShowAnimation.apply(this, arguments); that._showAnimationProcessing = false; that._actions.onShown(); deferred.resolve() }, function() { startShowAnimation.apply(this, arguments); that._showAnimationProcessing = true }) }.bind(this); if (this.option("templatesRenderAsynchronously")) { this._asyncShowTimeout = setTimeout(show) } else { show() } } return deferred.promise() }, _normalizeAnimation: function(animation, prop) { if (animation) { animation = extend({ type: "slide" }, animation); if (animation[prop] && "object" === typeof animation[prop]) { extend(animation[prop], { position: this._position }) } } return animation }, _hide: function() { if (!this._currentVisible) { return $.Deferred().resolve().promise() } this._currentVisible = false; var that = this, deferred = $.Deferred(), animation = that._getAnimationConfig() || {}, hideAnimation = this._normalizeAnimation(animation.hide, "from"), startHideAnimation = hideAnimation && hideAnimation.start || commonUtils.noop, completeHideAnimation = hideAnimation && hideAnimation.complete || commonUtils.noop, hidingArgs = { cancel: false }; this._actions.onHiding(hidingArgs); if (hidingArgs.cancel) { this._isHidingActionCanceled = true; this.option("visible", true); deferred.resolve() } else { this._forceFocusLost(); this._toggleShading(false); this._toggleSubscriptions(false); this._animate(hideAnimation, function() { that._$content.css("pointer-events", ""); that._renderVisibility(false); completeHideAnimation.apply(this, arguments); that._actions.onHidden(); deferred.resolve() }, function() { that._$content.css("pointer-events", "none"); startHideAnimation.apply(this, arguments) }) } return deferred.promise() }, _forceFocusLost: function() { document.activeElement && this._$content.find(document.activeElement).length && document.activeElement.blur() }, _animate: function(animation, completeCallback, startCallback) { if (animation) { startCallback = startCallback || animation.start || commonUtils.noop; fx.animate(this._$content, extend({}, animation, { start: startCallback, complete: completeCallback })) } else { completeCallback() } }, _stopAnimation: function() { fx.stop(this._$content, true) }, _renderVisibility: function(visible) { if (visible && this._isParentHidden()) { return } this._currentVisible = visible; this._stopAnimation(); clearTimeout(this._asyncShowTimeout); if (!visible) { domUtils.triggerHidingEvent(this._$content) } this._toggleVisibility(visible); this._$content.toggleClass(INVISIBLE_STATE_CLASS, !visible); this._updateZIndexStackPosition(visible); if (visible) { this._renderContent(); this._actions.onShowing(); this._moveToContainer(); this._renderGeometry(); domUtils.triggerShownEvent(this._$content); domUtils.triggerResizeEvent(this._$content) } else { this._moveFromContainer() } this._toggleShading(visible); this._toggleSubscriptions(visible) }, _updateZIndexStackPosition: function(pushToStack) { var overlayStack = this._overlayStack(), index = inArray(this, overlayStack); if (pushToStack) { if (index === -1) { var length = overlayStack.length; this._zIndex = (length ? overlayStack[length - 1]._zIndex : this._zIndexInitValue()) + 1; overlayStack.push(this) } this._$wrapper.css("z-index", this._zIndex); this._$content.css("z-index", this._zIndex) } else { if (index !== -1) { overlayStack.splice(index, 1) } } }, _toggleShading: function(visible) { this._$wrapper.toggleClass(OVERLAY_MODAL_CLASS, this.option("shading") && !this.option("container")); this._$wrapper.toggleClass(OVERLAY_SHADER_CLASS, visible && this.option("shading")); this._$wrapper.css("background-color", this.option("shading") ? this.option("shadingColor") : ""); this._toggleTabTerminator(visible && this.option("shading")) }, _initTabTerminatorHandler: function() { var that = this; this._proxiedTabTerminatorHandler = function() { that._tabKeyHandler.apply(that, arguments) } }, _toggleTabTerminator: function(enabled) { var eventName = eventUtils.addNamespace("keydown", this.NAME); if (enabled) { $(document).on(eventName, this._proxiedTabTerminatorHandler) } else { $(document).off(eventName, this._proxiedTabTerminatorHandler) } }, _tabKeyHandler: function(e) { if (e.keyCode !== TAB_KEY || !this._isTopOverlay()) { return } var tabbableElements = this._$wrapper.find("*").filter(selectors.tabbable), $firstTabbable = tabbableElements.first(), $lastTabbable = tabbableElements.last(), isTabOnLast = !e.shiftKey && e.target === $lastTabbable.get(0), isShiftTabOnFirst = e.shiftKey && e.target === $firstTabbable.get(0), isEmptyTabList = 0 === tabbableElements.length, isOutsideTarget = inArray(e.target, tabbableElements) === -1; if (isTabOnLast || isShiftTabOnFirst || isEmptyTabList || isOutsideTarget) { e.preventDefault(); (e.shiftKey ? $lastTabbable : $firstTabbable).focusin().focus() } }, _toggleSubscriptions: function(enabled) { this._toggleHideTopOverlayCallback(enabled); this._toggleParentsScrollSubscription(enabled) }, _toggleHideTopOverlayCallback: function(subscribe) { if (!this._hideTopOverlayHandler) { return } if (subscribe && this.option("closeOnBackButton")) { hideTopOverlayCallback.add(this._hideTopOverlayHandler) } else { hideTopOverlayCallback.remove(this._hideTopOverlayHandler) } }, _toggleParentsScrollSubscription: function(subscribe) { if (!this._position) { return } var target = this._position.of || $(), closeOnScroll = this.option("closeOnTargetScroll"), $parents = getElement(target).parents(), scrollEvent = eventUtils.addNamespace("scroll", this.NAME); if ("generic" === devices.real().platform) { $parents = $parents.add(window) } this._proxiedTargetParentsScrollHandler = this._proxiedTargetParentsScrollHandler || function(e) { this._targetParentsScrollHandler(e) }.bind(this); $().add(this._$prevTargetParents).off(scrollEvent, this._proxiedTargetParentsScrollHandler); if (subscribe && closeOnScroll) { $parents.on(scrollEvent, this._proxiedTargetParentsScrollHandler); this._$prevTargetParents = $parents } }, _targetParentsScrollHandler: function(e) { var closeHandled = false, closeOnScroll = this.option("closeOnTargetScroll"); if (commonUtils.isFunction(closeOnScroll)) { closeHandled = closeOnScroll(e) } if (!closeHandled && !this._showAnimationProcessing) { this.hide() } }, _render: function() { this.callBase(); this._$content.appendTo(this.element()); this._renderVisibilityAnimate(this.option("visible")) }, _renderContent: function() { var shouldDeferRendering = !this._currentVisible && this.option("deferRendering"); var isParentHidden = this.option("visible") && this._isParentHidden(); if (isParentHidden) { this._isHidden = true; return } if (this._contentAlreadyRendered || shouldDeferRendering) { return } this._contentAlreadyRendered = true; this.callBase() }, _isParentHidden: function() { if (!this.option("_checkParentVisibility")) { return false } if (void 0 !== this._parentHidden) { return this._parentHidden } var $parent = this.element().parent(); if ($parent.is(":visible")) { return false } var isHidden = false; $parent.add($parent.parents()).each(function() { var $element = $(this); if ("none" === $element.css("display")) { isHidden = true; return false } }); return isHidden || !$.contains(document, $parent.get(0)) }, _renderContentImpl: function() { var $element = this.element(); this._$content.appendTo($element); var contentTemplate = this._getTemplate(this.option("contentTemplate")); contentTemplate && contentTemplate.render({ container: this.content(), noModel: true }); this._renderDrag(); this._renderResize(); this._renderScrollTerminator() }, _renderDrag: function() { var $dragTarget = this._getDragTarget(); if (!$dragTarget) { return } var startEventName = eventUtils.addNamespace(dragEvents.start, this.NAME), updateEventName = eventUtils.addNamespace(dragEvents.move, this.NAME); $dragTarget.off(startEventName).off(updateEventName); if (!this.option("dragEnabled")) { return } $dragTarget.on(startEventName, this._dragStartHandler.bind(this)).on(updateEventName, this._dragUpdateHandler.bind(this)) }, _renderResize: function() { this._resizable = this._createComponent(this._$content, Resizable, { handles: this.option("resizeEnabled") ? "all" : "none", onResizeEnd: this._resizeEndHandler.bind(this), onResize: this._actions.onResize.bind(this), onResizeStart: this._actions.onResizeStart.bind(this), minHeight: 100, minWidth: 100, area: this._getDragResizeContainer() }) }, _resizeEndHandler: function() { this._positionChangeHandled = true; var width = this._resizable.option("width"), height = this._resizable.option("height"); width && this.option("width", width); height && this.option("height", height); this._actions.onResizeEnd() }, _renderScrollTerminator: function() { var $scrollTerminator = this._wrapper(); var terminatorEventName = eventUtils.addNamespace(dragEvents.move, this.NAME); $scrollTerminator.off(terminatorEventName).on(terminatorEventName, { validate: function() { return true }, getDirection: function() { return "both" }, _toggleGestureCover: commonUtils.noop, _clearSelection: commonUtils.noop, isNative: true }, function(e) { var originalEvent = e.originalEvent.originalEvent; e._cancelPreventDefault = true; if (originalEvent && "mousemove" !== originalEvent.type) { e.preventDefault() } }) }, _getDragTarget: function() { return this.content() }, _dragStartHandler: function(e) { e.targetElements = []; this._prevOffset = { x: 0, y: 0 }; var allowedOffsets = this._allowedOffsets(); e.maxTopOffset = allowedOffsets.top; e.maxBottomOffset = allowedOffsets.bottom; e.maxLeftOffset = allowedOffsets.left; e.maxRightOffset = allowedOffsets.right }, _getDragResizeContainer: function() { var isContainerDefined = viewPortUtils.originalViewPort().get(0) || this.option("container"), $container = !isContainerDefined ? $(window) : this._$container; return $container }, _deltaSize: function() { var $content = this._$content, $container = this._getDragResizeContainer(); var contentWidth = $content.outerWidth(), contentHeight = $content.outerHeight(), containerWidth = $container.outerWidth(), containerHeight = $container.outerHeight(); return { width: containerWidth - contentWidth, height: containerHeight - contentHeight } }, _dragUpdateHandler: function(e) { var offset = e.offset, prevOffset = this._prevOffset, targetOffset = { top: offset.y - prevOffset.y, left: offset.x - prevOffset.x }; this._changePosition(targetOffset); this._prevOffset = offset }, _changePosition: function(offset) { var position = translator.locate(this._$content); translator.move(this._$content, { left: position.left + offset.left, top: position.top + offset.top }); this._positionChangeHandled = true }, _allowedOffsets: function() { var position = translator.locate(this._$content), deltaSize = this._deltaSize(), isAllowedDrag = deltaSize.height >= 0 && deltaSize.width >= 0, shaderOffset = this.option("shading") && !this.option("container") && !this._isWindow(this._getContainer()) ? translator.locate(this._$wrapper) : { top: 0, left: 0 }, boundaryOffset = this.option("boundaryOffset"); return { top: isAllowedDrag ? position.top + shaderOffset.top + boundaryOffset.v : 0, bottom: isAllowedDrag ? -position.top - shaderOffset.top + deltaSize.height - boundaryOffset.v : 0, left: isAllowedDrag ? position.left + shaderOffset.left + boundaryOffset.h : 0, right: isAllowedDrag ? -position.left - shaderOffset.left + deltaSize.width - boundaryOffset.h : 0 } }, _fireContentReadyAction: function() { if (this.option("visible")) { this._moveToContainer() } this.callBase.apply(this, arguments) }, _moveFromContainer: function() { this._$content.appendTo(this.element()); this._detachWrapperToContainer() }, _detachWrapperToContainer: function() { this._$wrapper.detach() }, _moveToContainer: function() { this._attachWrapperToContainer(); this._$content.appendTo(this._$wrapper) }, _attachWrapperToContainer: function() { var $element = this.element(); if (this._$container && this._$container[0] !== $element.parent()[0]) { this._$wrapper.appendTo(this._$container) } else { this._$wrapper.appendTo($element) } }, _renderGeometry: function() { if (this.option("visible")) { this._renderGeometryImpl() } }, _renderGeometryImpl: function() { this._stopAnimation(); this._normalizePosition(); this._renderShading(); this._renderDimensions(); var resultPosition = this._renderPosition(); this._actions.onPositioned({ position: resultPosition }) }, _renderShading: function() { var $wrapper = this._$wrapper, $container = this._getContainer(); $wrapper.css("position", this._isWindow($container) && !iOS ? "fixed" : "absolute"); this._renderShadingDimensions(); this._renderShadingPosition() }, _renderShadingPosition: function() { if (this.option("shading")) { var $container = this._getContainer(); positionUtils.setup(this._$wrapper, { my: "top left", at: "top left", of: $container }) } }, _renderShadingDimensions: function() { var wrapperWidth, wrapperHeight; if (this.option("shading")) { var $container = this._getContainer(); wrapperWidth = this._isWindow($container) ? "100%" : $container.outerWidth(), wrapperHeight = this._isWindow($container) ? "100%" : $container.outerHeight() } else { wrapperWidth = ""; wrapperHeight = "" } this._$wrapper.css({ width: wrapperWidth, height: wrapperHeight }) }, _isWindow: function($element) { return !!$element && commonUtils.isWindow($element.get(0)) }, _getContainer: function() { var position = this._position, container = this.option("container"), positionOf = position ? position.of || window : null; return getElement(container || positionOf) }, _renderDimensions: function() { this._$content.css({ minWidth: this.option("minWidth"), maxWidth: this.option("maxWidth"), minHeight: this.option("minHeight"), maxHeight: this.option("maxHeight") }); this._$content.outerWidth(this.option("width")).outerHeight(this.option("height")) }, _renderPosition: function() { if (this._positionChangeHandled) { var allowedOffsets = this._allowedOffsets(); this._changePosition({ top: fitIntoRange(0, -allowedOffsets.top, allowedOffsets.bottom), left: fitIntoRange(0, -allowedOffsets.left, allowedOffsets.right) }) } else { this._renderOverlayBoundaryOffset(); translator.resetPosition(this._$content); var resultPosition = positionUtils.setup(this._$content, this._position); forceRepaint(this._$content); this._actions.onPositioning(); return resultPosition } }, _renderOverlayBoundaryOffset: function() { var boundaryOffset = this.option("boundaryOffset"); this._$content.css("margin", boundaryOffset.v + "px " + boundaryOffset.h + "px") }, _focusTarget: function() { return this._$content }, _attachKeyboardEvents: function() { this._keyboardProcessor = new KeyboardProcessor({ element: this._$content, handler: this._keyboardHandler, context: this }) }, _keyboardHandler: function(options) { var e = options.originalEvent, $target = $(e.target); if ($target.is(this._$content)) { this.callBase.apply(this, arguments) } }, _isVisible: function() { return this.option("visible") }, _visibilityChanged: function(visible) { if (visible) { if (this.option("visible")) { this._renderVisibilityAnimate(visible) } } else { this._renderVisibilityAnimate(visible) } }, _dimensionChanged: function() { this._renderGeometry() }, _clean: function() { if (!this._contentAlreadyRendered) { this.content().empty() } this._renderVisibility(false); this._cleanFocusState() }, _dispose: function() { fx.stop(this._$content, false); clearTimeout(this._deferShowTimer); this._toggleViewPortSubscription(false); this._toggleSubscriptions(false); this._updateZIndexStackPosition(false); this._toggleTabTerminator(false); this._actions = null; this.callBase(); this._$wrapper.remove(); this._$content.remove() }, _toggleDisabledState: function(value) { this.callBase.apply(this, arguments); this._$content.toggleClass(DISABLED_STATE_CLASS, Boolean(value)) }, _toggleRTLDirection: function(rtl) { this._$content.toggleClass(RTL_DIRECTION_CLASS, rtl) }, _optionChanged: function(args) { var value = args.value; if (inArray(args.name, ACTIONS) > -1) { this._initActions(); return } switch (args.name) { case "dragEnabled": this._renderDrag(); this._renderGeometry(); break; case "resizeEnabled": this._renderResize(); this._renderGeometry(); break; case "shading": case "shadingColor": this._toggleShading(this.option("visible")); break; case "width": case "height": case "minWidth": case "maxWidth": case "minHeight": case "maxHeight": case "position": case "boundaryOffset": this._renderGeometry(); break; case "visible": this._renderVisibilityAnimate(value).done(function() { if (!this._animateDeferred) { return } this._animateDeferred.resolveWith(this) }.bind(this)); break; case "target": this._initTarget(value); this._invalidate(); break; case "container": this._initContainer(value); this._invalidate(); break; case "deferRendering": case "contentTemplate": this._contentAlreadyRendered = false; this._invalidate(); break; case "closeOnBackButton": this._toggleHideTopOverlayCallback(this.option("visible")); break; case "closeOnTargetScroll": this._toggleParentsScrollSubscription(this.option("visible")); break; case "closeOnOutsideClick": case "animation": case "propagateOutsideClick": break; default: this.callBase(args) } }, toggle: function(showing) { showing = void 0 === showing ? !this.option("visible") : showing; if (showing === this.option("visible")) { return $.Deferred().resolve().promise() } var animateDeferred = $.Deferred(); this._animateDeferred = animateDeferred; this.option("visible", showing); return animateDeferred.promise().done(function() { delete this._animateDeferred }.bind(this)) }, show: function() { return this.toggle(true) }, hide: function() { return this.toggle(false) }, content: function() { return this._$content }, repaint: function() { this._renderGeometry() } }); Overlay.baseZIndex = function(zIndex) { FIRST_Z_INDEX = zIndex }; registerComponent("dxOverlay", Overlay); module.exports = Overlay }, /*!***************************!*\ !*** ./js/events/drag.js ***! \***************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), wrapToArray = __webpack_require__( /*! ../core/utils/array */ 26).wrapToArray, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, registerEvent = __webpack_require__( /*! ./core/event_registrator */ 73), eventUtils = __webpack_require__( /*! ./utils */ 71), GestureEmitter = __webpack_require__( /*! ./gesture/emitter.gesture */ 86), registerEmitter = __webpack_require__( /*! ./core/emitter_registrator */ 84); var DRAG_START_EVENT = "dxdragstart", DRAG_EVENT = "dxdrag", DRAG_END_EVENT = "dxdragend", DRAG_ENTER_EVENT = "dxdragenter", DRAG_LEAVE_EVENT = "dxdragleave", DROP_EVENT = "dxdrop"; var knownDropTargets = [], knownDropTargetSelectors = [], knownDropTargetConfigs = []; var dropTargetRegistration = { setup: function(element, data) { var knownDropTarget = inArray(element, knownDropTargets) !== -1; if (!knownDropTarget) { knownDropTargets.push(element); knownDropTargetSelectors.push([]); knownDropTargetConfigs.push(data || {}) } }, add: function(element, handleObj) { var index = inArray(element, knownDropTargets); var selector = handleObj.selector; if (inArray(selector, knownDropTargetSelectors[index]) === -1) { knownDropTargetSelectors[index].push(selector) } }, teardown: function(element) { var elementEvents = $._data(element, "events"), handlersCount = 0; $.each([DRAG_ENTER_EVENT, DRAG_LEAVE_EVENT, DROP_EVENT], function(_, eventName) { var eventHandlers = elementEvents[eventName]; if (eventHandlers) { handlersCount += eventHandlers.length } }); if (!handlersCount) { var index = inArray(element, knownDropTargets); knownDropTargets.splice(index, 1); knownDropTargetSelectors.splice(index, 1); knownDropTargetConfigs.splice(index, 1) } } }; registerEvent(DRAG_ENTER_EVENT, dropTargetRegistration); registerEvent(DRAG_LEAVE_EVENT, dropTargetRegistration); registerEvent(DROP_EVENT, dropTargetRegistration); var getItemDelegatedTargets = function($element) { var dropTargetIndex = inArray($element.get(0), knownDropTargets), dropTargetSelectors = knownDropTargetSelectors[dropTargetIndex]; var $delegatedTargets = $element.find(dropTargetSelectors.join(", ")); if (inArray(void 0, dropTargetSelectors) !== -1) { $delegatedTargets = $delegatedTargets.add($element) } return $delegatedTargets }; var getItemConfig = function($element) { var dropTargetIndex = inArray($element.get(0), knownDropTargets); return knownDropTargetConfigs[dropTargetIndex] }; var getItemPosition = function(dropTargetConfig, $element) { if (dropTargetConfig.itemPositionFunc) { return dropTargetConfig.itemPositionFunc($element) } else { return $element.offset() } }; var getItemSize = function(dropTargetConfig, $element) { if (dropTargetConfig.itemSizeFunc) { return dropTargetConfig.itemSizeFunc($element) } return { width: $element.width(), height: $element.height() } }; var DragEmitter = GestureEmitter.inherit({ ctor: function(element) { this.callBase(element); this.direction = "both" }, _init: function(e) { this._initEvent = e }, _start: function(e) { e = this._fireEvent(DRAG_START_EVENT, this._initEvent); this._maxLeftOffset = e.maxLeftOffset; this._maxRightOffset = e.maxRightOffset; this._maxTopOffset = e.maxTopOffset; this._maxBottomOffset = e.maxBottomOffset; var dropTargets = wrapToArray(e.targetElements || (null === e.targetElements ? [] : knownDropTargets)); this._dropTargets = $.map(dropTargets, function(element) { return $(element).get(0) }) }, _move: function(e) { var eventData = eventUtils.eventData(e), dragOffset = this._calculateOffset(eventData); e = this._fireEvent(DRAG_EVENT, e, { offset: dragOffset }); this._processDropTargets(e); if (!e._cancelPreventDefault) { e.preventDefault() } }, _calculateOffset: function(eventData) { return { x: this._calculateXOffset(eventData), y: this._calculateYOffset(eventData) } }, _calculateXOffset: function(eventData) { if ("vertical" !== this.direction) { var offset = eventData.x - this._startEventData.x; return this._fitOffset(offset, this._maxLeftOffset, this._maxRightOffset) } return 0 }, _calculateYOffset: function(eventData) { if ("horizontal" !== this.direction) { var offset = eventData.y - this._startEventData.y; return this._fitOffset(offset, this._maxTopOffset, this._maxBottomOffset) } return 0 }, _fitOffset: function(offset, minOffset, maxOffset) { if (null != minOffset) { offset = Math.max(offset, -minOffset) } if (null != maxOffset) { offset = Math.min(offset, maxOffset) } return offset }, _processDropTargets: function(e) { var target = this._findDropTarget(e), sameTarget = target === this._currentDropTarget; if (!sameTarget) { this._fireDropTargetEvent(e, DRAG_LEAVE_EVENT); this._currentDropTarget = target; this._fireDropTargetEvent(e, DRAG_ENTER_EVENT) } }, _fireDropTargetEvent: function(event, eventName) { if (!this._currentDropTarget) { return } var eventData = { type: eventName, originalEvent: event, draggingElement: this._$element.get(0), target: this._currentDropTarget }; eventUtils.fireEvent(eventData) }, _findDropTarget: function(e) { var result, that = this; $.each(knownDropTargets, function(_, target) { if (!that._checkDropTargetActive(target)) { return } var $target = $(target); $.each(getItemDelegatedTargets($target), function(_, delegatedTarget) { var $delegatedTarget = $(delegatedTarget); if (that._checkDropTarget(getItemConfig($target), $delegatedTarget, e)) { result = delegatedTarget } }) }); return result }, _checkDropTargetActive: function(target) { var active = false; $.each(this._dropTargets, function(_, activeTarget) { active = active || activeTarget === target || $.contains(activeTarget, target); return !active }); return active }, _checkDropTarget: function(config, $target, e) { var isDraggingElement = $target.get(0) === this._$element.get(0); if (isDraggingElement) { return false } var targetPosition = getItemPosition(config, $target); if (e.pageX < targetPosition.left) { return false } if (e.pageY < targetPosition.top) { return false } var targetSize = getItemSize(config, $target); if (e.pageX > targetPosition.left + targetSize.width) { return false } if (e.pageY > targetPosition.top + targetSize.height) { return false } return $target }, _end: function(e) { var eventData = eventUtils.eventData(e); this._fireEvent(DRAG_END_EVENT, e, { offset: this._calculateOffset(eventData) }); this._fireDropTargetEvent(e, DROP_EVENT); delete this._currentDropTarget } }); registerEmitter({ emitter: DragEmitter, events: [DRAG_START_EVENT, DRAG_EVENT, DRAG_END_EVENT] }); exports.dropTargets = knownDropTargets; exports.move = DRAG_EVENT; exports.start = DRAG_START_EVENT; exports.end = DRAG_END_EVENT; exports.enter = DRAG_ENTER_EVENT; exports.leave = DRAG_LEAVE_EVENT; exports.drop = DROP_EVENT }, /*!****************************!*\ !*** ./js/ui/resizable.js ***! \****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), stringUtils = __webpack_require__( /*! ../core/utils/string */ 18), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), translator = __webpack_require__( /*! ../animation/translator */ 69), fitIntoRange = __webpack_require__( /*! ../core/utils/math */ 87).fitIntoRange, DOMComponent = __webpack_require__( /*! ../core/dom_component */ 43), eventUtils = __webpack_require__( /*! ../events/utils */ 71), dragEvents = __webpack_require__( /*! ../events/drag */ 110), isPlainObject = typeUtils.isPlainObject, isFunction = commonUtils.isFunction; var RESIZABLE = "dxResizable", RESIZABLE_CLASS = "dx-resizable", RESIZABLE_RESIZING_CLASS = "dx-resizable-resizing", RESIZABLE_HANDLE_CLASS = "dx-resizable-handle", RESIZABLE_HANDLE_TOP_CLASS = "dx-resizable-handle-top", RESIZABLE_HANDLE_BOTTOM_CLASS = "dx-resizable-handle-bottom", RESIZABLE_HANDLE_LEFT_CLASS = "dx-resizable-handle-left", RESIZABLE_HANDLE_RIGHT_CLASS = "dx-resizable-handle-right", RESIZABLE_HANDLE_CORNER_CLASS = "dx-resizable-handle-corner", DRAGSTART_START_EVENT_NAME = eventUtils.addNamespace(dragEvents.start, RESIZABLE), DRAGSTART_EVENT_NAME = eventUtils.addNamespace(dragEvents.move, RESIZABLE), DRAGSTART_END_EVENT_NAME = eventUtils.addNamespace(dragEvents.end, RESIZABLE); var Resizable = DOMComponent.inherit({ _getDefaultOptions: function() { return extend(this.callBase(), { handles: "all", step: "1", stepPrecision: "simple", area: void 0, minWidth: 30, maxWidth: 1 / 0, minHeight: 30, maxHeight: 1 / 0, onResizeStart: null, onResize: null, onResizeEnd: null }) }, _init: function() { this.callBase(); this.element().addClass(RESIZABLE_CLASS) }, _render: function() { this.callBase(); this._renderActions(); this._renderHandles() }, _renderActions: function() { this._resizeStartAction = this._createActionByOption("onResizeStart"); this._resizeEndAction = this._createActionByOption("onResizeEnd"); this._resizeAction = this._createActionByOption("onResize") }, _renderHandles: function() { var handles = this.option("handles"); if ("none" === handles) { return } var directions = "all" === handles ? ["top", "bottom", "left", "right"] : handles.split(" "); $.each(directions, function(index, handleName) { this._renderHandle(handleName) }.bind(this)); inArray("bottom", directions) + 1 && inArray("right", directions) + 1 && this._renderHandle("corner-bottom-right"); inArray("bottom", directions) + 1 && inArray("left", directions) + 1 && this._renderHandle("corner-bottom-left"); inArray("top", directions) + 1 && inArray("right", directions) + 1 && this._renderHandle("corner-top-right"); inArray("top", directions) + 1 && inArray("left", directions) + 1 && this._renderHandle("corner-top-left") }, _renderHandle: function(handleName) { var $element = this.element(), $handle = $("<div>"); $handle.addClass(RESIZABLE_HANDLE_CLASS).addClass(RESIZABLE_HANDLE_CLASS + "-" + handleName).appendTo($element); this._attachEventHandlers($handle) }, _attachEventHandlers: function($handle) { if (this.option("disabled")) { return } var handlers = {}; handlers[DRAGSTART_START_EVENT_NAME] = this._dragStartHandler.bind(this); handlers[DRAGSTART_EVENT_NAME] = this._dragHandler.bind(this); handlers[DRAGSTART_END_EVENT_NAME] = this._dragEndHandler.bind(this); $handle.on(handlers, { direction: "both", immediate: true }) }, _dragStartHandler: function(e) { var $element = this.element(); if ($element.is(".dx-state-disabled, .dx-state-disabled *")) { e.cancel = true; return } this._toggleResizingClass(true); this._movingSides = this._getMovingSides(e); this._elementLocation = translator.locate($element); this._elementSize = { width: $element.outerWidth(), height: $element.outerHeight() }; this._renderDragOffsets(e); this._resizeStartAction({ jQueryEvent: e, width: this._elementSize.width, height: this._elementSize.height, handles: this._movingSides }); e.targetElements = null }, _toggleResizingClass: function(value) { this.element().toggleClass(RESIZABLE_RESIZING_CLASS, value) }, _renderDragOffsets: function(e) { var area = this._getArea(); if (!area) { return } var $handle = $(e.target).closest("." + RESIZABLE_HANDLE_CLASS), handleWidth = $handle.outerWidth(), handleHeight = $handle.outerHeight(), handleOffset = $handle.offset(), areaOffset = area.offset; e.maxLeftOffset = handleOffset.left - areaOffset.left; e.maxRightOffset = areaOffset.left + area.width - handleOffset.left - handleWidth; e.maxTopOffset = handleOffset.top - areaOffset.top; e.maxBottomOffset = areaOffset.top + area.height - handleOffset.top - handleHeight }, _getBorderWidth: function($element, direction) { if (commonUtils.isWindow($element.get(0))) { return 0 } var borderWidth = $element.css("border-" + direction + "-width"); return parseInt(borderWidth) || 0 }, _dragHandler: function(e) { var $element = this.element(), sides = this._movingSides; var location = this._elementLocation, size = this._elementSize, offset = this._getOffset(e); var width = size.width + offset.x * (sides.left ? -1 : 1), height = size.height + offset.y * (sides.top ? -1 : 1); if (offset.x || "strict" === this.option("stepPrecision")) { this._renderWidth(width) } if (offset.y || "strict" === this.option("stepPrecision")) { this._renderHeight(height) } var offsetTop = offset.y - ((this.element().outerHeight() || height) - height), offsetLeft = offset.x - ((this.element().outerWidth() || width) - width); translator.move($element, { top: location.top + (sides.top ? offsetTop : 0), left: location.left + (sides.left ? offsetLeft : 0) }); this._resizeAction({ jQueryEvent: e, width: this.option("width") || width, height: this.option("height") || height, handles: this._movingSides }) }, _getOffset: function(e) { var offset = e.offset, steps = stringUtils.pairToObject(this.option("step")), sides = this._getMovingSides(e), strictPrecision = "strict" === this.option("stepPrecision"); if (!sides.left && !sides.right) { offset.x = 0 } if (!sides.top && !sides.bottom) { offset.y = 0 } return strictPrecision ? this._getStrictOffset(offset, steps, sides) : this._getSimpleOffset(offset, steps) }, _getSimpleOffset: function(offset, steps) { return { x: offset.x - offset.x % steps.h, y: offset.y - offset.y % steps.v } }, _getStrictOffset: function(offset, steps, sides) { var location = this._elementLocation, size = this._elementSize, xPos = sides.left ? location.left : location.left + size.width, yPos = sides.top ? location.top : location.top + size.height, newXShift = (xPos + offset.x) % steps.h, newYShift = (yPos + offset.y) % steps.v, sign = Math.sign || function(x) { x = +x; if (0 === x || isNaN(x)) { return x } return x > 0 ? 1 : -1 }, separatorOffset = function(steps, offset) { return (1 + .2 * sign(offset)) % 1 * steps }, isSmallOffset = function(offset, steps) { return Math.abs(offset) < .2 * steps }; var newOffsetX = offset.x - newXShift, newOffsetY = offset.y - newYShift; if (newXShift > separatorOffset(steps.h, offset.x)) { newOffsetX += steps.h } if (newYShift > separatorOffset(steps.v, offset.y)) { newOffsetY += steps.v } return { x: (sides.left || sides.right) && !isSmallOffset(offset.x, steps.h) ? newOffsetX : 0, y: (sides.top || sides.bottom) && !isSmallOffset(offset.y, steps.v) ? newOffsetY : 0 } }, _getMovingSides: function(e) { var $target = $(e.target), hasCornerTopLeftClass = $target.hasClass(RESIZABLE_HANDLE_CORNER_CLASS + "-top-left"), hasCornerTopRightClass = $target.hasClass(RESIZABLE_HANDLE_CORNER_CLASS + "-top-right"), hasCornerBottomLeftClass = $target.hasClass(RESIZABLE_HANDLE_CORNER_CLASS + "-bottom-left"), hasCornerBottomRightClass = $target.hasClass(RESIZABLE_HANDLE_CORNER_CLASS + "-bottom-right"); return { top: $target.hasClass(RESIZABLE_HANDLE_TOP_CLASS) || hasCornerTopLeftClass || hasCornerTopRightClass, left: $target.hasClass(RESIZABLE_HANDLE_LEFT_CLASS) || hasCornerTopLeftClass || hasCornerBottomLeftClass, bottom: $target.hasClass(RESIZABLE_HANDLE_BOTTOM_CLASS) || hasCornerBottomLeftClass || hasCornerBottomRightClass, right: $target.hasClass(RESIZABLE_HANDLE_RIGHT_CLASS) || hasCornerTopRightClass || hasCornerBottomRightClass } }, _getArea: function() { var area = this.option("area"); if (isFunction(area)) { area = area.call(this) } if (isPlainObject(area)) { return this._getAreaFromObject(area) } return this._getAreaFromElement(area) }, _getAreaFromObject: function(area) { var result = { width: area.right - area.left, height: area.bottom - area.top, offset: { left: area.left, top: area.top } }; this._correctAreaGeometry(result); return result }, _getAreaFromElement: function(area) { var result, $area = $(area); if ($area.length) { result = { width: $area.innerWidth(), height: $area.innerHeight(), offset: extend({ top: 0, left: 0 }, commonUtils.isWindow($area[0]) ? {} : $area.offset()) }; this._correctAreaGeometry(result, $area) } return result }, _correctAreaGeometry: function(result, $area) { var areaBorderLeft = $area ? this._getBorderWidth($area, "left") : 0, areaBorderTop = $area ? this._getBorderWidth($area, "top") : 0; result.offset.left += areaBorderLeft + this._getBorderWidth(this.element(), "left"); result.offset.top += areaBorderTop + this._getBorderWidth(this.element(), "top"); result.width -= this.element().outerWidth() - this.element().innerWidth(); result.height -= this.element().outerHeight() - this.element().innerHeight() }, _dragEndHandler: function(e) { var $element = this.element(); this._resizeEndAction({ jQueryEvent: e, width: $element.outerWidth(), height: $element.outerHeight(), handles: this._movingSides }); this._toggleResizingClass(false) }, _renderWidth: function(width) { this.option("width", fitIntoRange(width, this.option("minWidth"), this.option("maxWidth"))) }, _renderHeight: function(height) { this.option("height", fitIntoRange(height, this.option("minHeight"), this.option("maxHeight"))) }, _optionChanged: function(args) { switch (args.name) { case "disabled": case "handles": this._invalidate(); break; case "minWidth": case "maxWidth": this._renderWidth(this.element().outerWidth()); break; case "minHeight": case "maxHeight": this._renderHeight(this.element().outerHeight()); break; case "onResize": case "onResizeStart": case "onResizeEnd": this._renderActions(); break; case "area": case "stepPrecision": case "step": break; default: this.callBase(args) } }, _clean: function() { this.element().find("." + RESIZABLE_HANDLE_CLASS).remove() } }); registerComponent(RESIZABLE, Resizable); module.exports = Resizable }, /*!*********************************!*\ !*** ./js/core/utils/locker.js ***! \*********************************/ function(module, exports, __webpack_require__) { var errors = __webpack_require__( /*! ../errors */ 7); var Locker = function() { var info = {}; var currentCount = function(lockName) { return info[lockName] || 0 }; return { obtain: function(lockName) { info[lockName] = currentCount(lockName) + 1 }, release: function(lockName) { var count = currentCount(lockName); if (count < 1) { throw errors.Error("E0014") } if (1 === count) { delete info[lockName] } else { info[lockName] = count - 1 } }, locked: function(lockName) { return currentCount(lockName) > 0 } } }; module.exports = Locker }, /*!******************************************************!*\ !*** ./js/integration/knockout/event_registrator.js ***! \******************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ko = __webpack_require__( /*! knockout */ 93), isPlainObject = __webpack_require__( /*! ../../core/utils/type */ 12).isPlainObject, eventRegistrator = __webpack_require__( /*! ../../events/core/event_registrator */ 73), eventUtils = __webpack_require__( /*! ../../events/utils */ 71); eventRegistrator.callbacks.add(function(name) { var koBindingEventName = eventUtils.addNamespace(name, name + "Binding"); ko.bindingHandlers[name] = { update: function(element, valueAccessor, allBindingsAccessor, viewModel) { var $element = $(element), unwrappedValue = ko.utils.unwrapObservable(valueAccessor()), eventSource = unwrappedValue.execute ? unwrappedValue.execute : unwrappedValue; $element.off(koBindingEventName).on(koBindingEventName, isPlainObject(unwrappedValue) ? unwrappedValue : {}, function(e) { eventSource.call(viewModel, viewModel, e) }) } } }) }, /*!***********************************************!*\ !*** ./js/integration/knockout/components.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Action = __webpack_require__( /*! ../../core/action */ 49), compileGetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileGetter, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, ko = __webpack_require__( /*! knockout */ 93), iconUtils = __webpack_require__( /*! ../../core/utils/icon */ 115), clickEvent = __webpack_require__( /*! ../../events/click */ 75); ko.bindingHandlers.dxAction = { update: function(element, valueAccessor, allBindingsAccessor, viewModel) { var $element = $(element); var unwrappedValue = ko.utils.unwrapObservable(valueAccessor()), actionSource = unwrappedValue, actionOptions = { context: element }; if (unwrappedValue.execute) { actionSource = unwrappedValue.execute; extend(actionOptions, unwrappedValue) } var action = new Action(actionSource, actionOptions); $element.off(".dxActionBinding").on(clickEvent.name + ".dxActionBinding", function(e) { action.execute({ element: $element, model: viewModel, evaluate: function(expression) { var context = viewModel; if (expression.length > 0 && "$" === expression[0]) { context = ko.contextFor(element) } var getter = compileGetter(expression); return getter(context) }, jQueryEvent: e }); if (!actionOptions.bubbling) { e.stopPropagation() } }) } }; ko.bindingHandlers.dxControlsDescendantBindings = { init: function(_, valueAccessor) { return { controlsDescendantBindings: ko.unwrap(valueAccessor()) } } }; ko.bindingHandlers.dxIcon = { init: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}, iconElement = iconUtils.getImageContainer(options); ko.virtualElements.emptyNode(element); if (iconElement) { ko.virtualElements.prepend(element, iconElement.get(0)) } }, update: function(element, valueAccessor) { var options = ko.utils.unwrapObservable(valueAccessor()) || {}, iconElement = iconUtils.getImageContainer(options); ko.virtualElements.emptyNode(element); if (iconElement) { ko.virtualElements.prepend(element, iconElement.get(0)) } } }; ko.virtualElements.allowedBindings.dxIcon = true }, /*!*******************************!*\ !*** ./js/core/utils/icon.js ***! \*******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var getImageSourceType = function(source) { if (!source || "string" !== typeof source) { return false } if (/data:.*base64|\.|\//.test(source)) { return "image" } if (/^[\w-_]+$/.test(source)) { return "dxIcon" } return "fontIcon" }; var getImageContainer = function(source) { var imageType = getImageSourceType(source), ICON_CLASS = "dx-icon"; switch (imageType) { case "image": return $("<img>", { src: source }).addClass(ICON_CLASS); case "fontIcon": return $("<i>", { "class": ICON_CLASS + " " + source }); case "dxIcon": return $("<i>", { "class": ICON_CLASS + " " + ICON_CLASS + "-" + source }); default: return null } }; exports.getImageSourceType = getImageSourceType; exports.getImageContainer = getImageContainer }, /*!***********************************************!*\ !*** ./js/integration/knockout/validation.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), EventsMixin = __webpack_require__( /*! ../../core/events_mixin */ 51), ValidationEngine = __webpack_require__( /*! ../../ui/validation_engine */ 117), ko = __webpack_require__( /*! knockout */ 93); var koDxValidator = Class.inherit({ ctor: function(target, option) { var that = this; that.target = target; that.validationRules = option.validationRules; that.name = option.name; that.isValid = ko.observable(true); that.validationError = ko.observable(); $.each(this.validationRules, function(_, rule) { rule.validator = that }) }, validate: function() { var result = ValidationEngine.validate(this.target(), this.validationRules, this.name); this._applyValidationResult(result); return result }, reset: function() { this.target(null); var result = { isValid: true, brokenRule: null }; this._applyValidationResult(result); return result }, _applyValidationResult: function(result) { result.validator = this; this.target.dxValidator.isValid(result.isValid); this.target.dxValidator.validationError(result.brokenRule); this.fireEvent("validated", [result]) } }).include(EventsMixin); ko.extenders.dxValidator = function(target, option) { target.dxValidator = new koDxValidator(target, option); target.subscribe(target.dxValidator.validate.bind(target.dxValidator)); return target }; ValidationEngine.registerModelForValidation = function(model) { $.each(model, function(name, member) { if (ko.isObservable(member) && member.dxValidator) { ValidationEngine.registerValidatorInGroup(model, member.dxValidator) } }) }; ValidationEngine.unregisterModelForValidation = function(model) { $.each(model, function(name, member) { if (ko.isObservable(member) && member.dxValidator) { ValidationEngine.removeRegisteredValidator(model, member.dxValidator) } }) }; ValidationEngine.validateModel = ValidationEngine.validateGroup }, /*!************************************!*\ !*** ./js/ui/validation_engine.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, EventsMixin = __webpack_require__( /*! ../core/events_mixin */ 51), errors = __webpack_require__( /*! ../core/errors */ 7), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), numberLocalization = __webpack_require__( /*! ../localization/number */ 32), messageLocalization = __webpack_require__( /*! ../localization/message */ 89); var BaseRuleValidator = Class.inherit({ NAME: "base", defaultMessage: function(value) { return messageLocalization.getFormatter("validation-" + this.NAME)(value) }, defaultFormattedMessage: function(value) { return messageLocalization.getFormatter("validation-" + this.NAME + "-formatted")(value) }, validate: function(value, rule) { var valueArray = Array.isArray(value) ? value : [value], result = true; valueArray.every(function(itemValue) { result = this._validate(itemValue, rule); return result }, this); return result } }); var RequiredRuleValidator = BaseRuleValidator.inherit({ NAME: "required", _validate: function(value, rule) { if (!commonUtils.isDefined(value)) { return false } if (false === value) { return false } value = String(value); if (rule.trim || !commonUtils.isDefined(rule.trim)) { value = $.trim(value) } return "" !== value } }); var NumericRuleValidator = BaseRuleValidator.inherit({ NAME: "numeric", _validate: function(value, rule) { if (!rulesValidators.required.validate(value, {})) { return true } if (rule.useCultureSettings && commonUtils.isString(value)) { return !isNaN(numberLocalization.parse(value)) } else { return commonUtils.isNumeric(value) } } }); var RangeRuleValidator = BaseRuleValidator.inherit({ NAME: "range", _validate: function(value, rule) { if (!rulesValidators.required.validate(value, {})) { return true } var validNumber = rulesValidators.numeric.validate(value, rule), validValue = commonUtils.isDefined(value), number = validNumber ? parseFloat(value) : validValue && value.valueOf(), min = rule.min, max = rule.max; if (!(validNumber || commonUtils.isDate(value)) && !validValue) { return false } if (commonUtils.isDefined(min)) { if (commonUtils.isDefined(max)) { return number >= min && number <= max } return number >= min } else { if (commonUtils.isDefined(max)) { return number <= max } else { throw errors.Error("E0101") } } } }); var StringLengthRuleValidator = BaseRuleValidator.inherit({ NAME: "stringLength", _validate: function(value, rule) { value = commonUtils.isDefined(value) ? String(value) : ""; if (rule.trim || !commonUtils.isDefined(rule.trim)) { value = $.trim(value) } return rulesValidators.range.validate(value.length, extend({}, rule)) } }); var CustomRuleValidator = BaseRuleValidator.inherit({ NAME: "custom", validate: function(value, rule) { return rule.validationCallback({ value: value, validator: rule.validator, rule: rule }) } }); var CompareRuleValidator = BaseRuleValidator.inherit({ NAME: "compare", _validate: function(value, rule) { if (!rule.comparisonTarget) { throw errors.Error("E0102") } extend(rule, { reevaluate: true }); var otherValue = rule.comparisonTarget(), type = rule.comparisonType || "=="; switch (type) { case "==": return value == otherValue; case "!=": return value != otherValue; case "===": return value === otherValue; case "!==": return value !== otherValue; case ">": return value > otherValue; case ">=": return value >= otherValue; case "<": return value < otherValue; case "<=": return value <= otherValue } } }); var PatternRuleValidator = BaseRuleValidator.inherit({ NAME: "pattern", _validate: function(value, rule) { if (!rulesValidators.required.validate(value, {})) { return true } var pattern = rule.pattern; if (commonUtils.isString(pattern)) { pattern = new RegExp(pattern) } return pattern.test(value) } }); var EmailRuleValidator = BaseRuleValidator.inherit({ NAME: "email", _validate: function(value, rule) { if (!rulesValidators.required.validate(value, {})) { return true } return rulesValidators.pattern.validate(value, extend({}, rule, { pattern: /^[\d\w\._\-]+@([\d\w\._\-]+\.)+[\w]+$/i })) } }); var rulesValidators = { required: new RequiredRuleValidator, numeric: new NumericRuleValidator, range: new RangeRuleValidator, stringLength: new StringLengthRuleValidator, custom: new CustomRuleValidator, compare: new CompareRuleValidator, pattern: new PatternRuleValidator, email: new EmailRuleValidator }; var GroupConfig = Class.inherit({ ctor: function(group) { this.group = group; this.validators = [] }, validate: function() { var result = { isValid: true, brokenRules: [], validators: [] }; $.each(this.validators, function(_, validator) { var validatorResult = validator.validate(); result.isValid = result.isValid && validatorResult.isValid; if (validatorResult.brokenRule) { result.brokenRules.push(validatorResult.brokenRule) } result.validators.push(validator) }); this.fireEvent("validated", [{ validators: result.validators, brokenRules: result.brokenRules, isValid: result.isValid }]); return result }, reset: function() { $.each(this.validators, function(_, validator) { validator.reset() }) } }).include(EventsMixin); var ValidationEngine = { groups: [], getGroupConfig: function(group) { var result = commonUtils.grep(this.groups, function(config) { return config.group === group }); if (result.length) { return result[0] } }, initGroups: function() { this.groups = []; this.addGroup() }, addGroup: function(group) { var config = this.getGroupConfig(group); if (!config) { config = new GroupConfig(group); this.groups.push(config) } return config }, removeGroup: function(group) { var config = this.getGroupConfig(group), index = inArray(config, this.groups); if (index > -1) { this.groups.splice(index, 1) } return config }, _setDefaultMessage: function(rule, validator, name) { if (!commonUtils.isDefined(rule.message)) { if (validator.defaultFormattedMessage && commonUtils.isDefined(name)) { rule.message = validator.defaultFormattedMessage(name) } else { rule.message = validator.defaultMessage() } } }, validate: function(value, rules, name) { var result = { name: name, value: value, brokenRule: null, isValid: true, validationRules: rules }, that = this; $.each(rules || [], function(_, rule) { var ruleValidationResult, ruleValidator = rulesValidators[rule.type]; if (ruleValidator) { if (commonUtils.isDefined(rule.isValid) && rule.value === value && !rule.reevaluate) { if (!rule.isValid) { result.isValid = false; result.brokenRule = rule; return false } return true } rule.value = value; ruleValidationResult = ruleValidator.validate(value, rule); rule.isValid = ruleValidationResult; if (!ruleValidationResult) { result.isValid = false; that._setDefaultMessage(rule, ruleValidator, name); result.brokenRule = rule } if (!rule.isValid) { return false } } else { throw errors.Error("E0100") } }); return result }, registerValidatorInGroup: function(group, validator) { var groupConfig = ValidationEngine.addGroup(group); if (inArray(validator, groupConfig.validators) < 0) { groupConfig.validators.push(validator) } }, _shouldRemoveGroup: function(group, validatorsInGroup) { var isDefaultGroup = void 0 === group, isValidationGroupInstance = group && "dxValidationGroup" === group.NAME; return !isDefaultGroup && !isValidationGroupInstance && !validatorsInGroup.length }, removeRegisteredValidator: function(group, validator) { var config = ValidationEngine.getGroupConfig(group), validatorsInGroup = config && config.validators; var index = inArray(validator, validatorsInGroup); if (index > -1) { validatorsInGroup.splice(index, 1); if (this._shouldRemoveGroup(group, validatorsInGroup)) { this.removeGroup(group) } } }, validateGroup: function(group) { var groupConfig = ValidationEngine.getGroupConfig(group); if (!groupConfig) { throw errors.Error("E0110") } return groupConfig.validate() }, resetGroup: function(group) { var groupConfig = ValidationEngine.getGroupConfig(group); if (!groupConfig) { throw errors.Error("E0110") } return groupConfig.reset() } }; ValidationEngine.initGroups(); module.exports = ValidationEngine }, /*!***********************************************************!*\ !*** ./js/integration/knockout/variable_wrapper_utils.js ***! \***********************************************************/ function(module, exports, __webpack_require__) { var ko = __webpack_require__( /*! knockout */ 93), variableWrapper = __webpack_require__( /*! ../../core/utils/variable_wrapper */ 28); variableWrapper.inject({ isWrapped: ko.isObservable, isWritableWrapped: ko.isWritableObservable, wrap: ko.observable, unwrap: function(value) { if (ko.isObservable(value)) { return ko.utils.unwrapObservable(value) } return this.callBase(value) }, assign: function(variable, value) { if (ko.isObservable(variable)) { variable(value) } else { this.callBase(variable, value) } } }) }, /*!***********************************************!*\ !*** ./js/integration/knockout/clean_node.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! jquery */ 10), ko = __webpack_require__( /*! knockout */ 93), cleanData = $.cleanData, compareVersion = __webpack_require__( /*! ../../core/utils/version */ 17).compare; if (compareVersion($.fn.jquery, [2, 0]) >= 0) { $.cleanData = function(nodes) { var result = cleanData(nodes); for (var i = 0; i < nodes.length; i++) { nodes[i].cleanedByJquery = true } for (i = 0; i < nodes.length; i++) { if (!nodes[i].cleanedByKo) { ko.cleanNode(nodes[i]) } delete nodes[i].cleanedByKo } for (i = 0; i < nodes.length; i++) { delete nodes[i].cleanedByJquery } return result }; ko.utils.domNodeDisposal.cleanExternalData = function(node) { node.cleanedByKo = true; if (!node.cleanedByJquery) { $.cleanData([node]) } } } }, /*!***************************************************!*\ !*** ./js/integration/knockout/clean_node_old.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ko = __webpack_require__( /*! knockout */ 93), compareVersion = __webpack_require__( /*! ../../core/utils/version */ 17).compare; if (compareVersion($.fn.jquery, [2, 0]) < 0) { var cleanKoData = function(element, andSelf) { var cleanNode = function() { ko.cleanNode(this) }; if (andSelf) { element.each(cleanNode) } else { element.find("*").each(cleanNode) } }; var originalEmpty = $.fn.empty; $.fn.empty = function() { cleanKoData(this, false); return originalEmpty.apply(this, arguments) }; var originalRemove = $.fn.remove; $.fn.remove = function(selector, keepData) { if (!keepData) { var subject = this; if (selector) { subject = subject.filter(selector) } cleanKoData(subject, true) } return originalRemove.call(this, selector, keepData) }; var originalHtml = $.fn.html; $.fn.html = function(value) { if ("string" === typeof value) { cleanKoData(this, false) } return originalHtml.apply(this, arguments) }; var originalReplaceWith = $.fn.replaceWith; $.fn.replaceWith = function() { var result = originalReplaceWith.apply(this, arguments); if (!this.parent().length) { cleanKoData(this, true) } return result } } }, /*!*********************************!*\ !*** ./js/framework/command.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ./errors */ 122), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), DOMComponent = __webpack_require__( /*! ../core/dom_component */ 43), isFunction = commonUtils.isFunction, isPlainObject = typeUtils.isPlainObject, noop = commonUtils.noop; __webpack_require__( /*! ../integration/knockout */ 92); var Command = DOMComponent.inherit({ ctor: function(element, options) { if (isPlainObject(element)) { options = element; element = $("<div />") } this.callBase(element, options) }, _setDeprecatedOptions: function() { this.callBase(); extend(this._deprecatedOptions, { iconSrc: { since: "15.1", alias: "icon" } }) }, _getDefaultOptions: function() { return extend(this.callBase(), { onExecute: null, id: null, title: "", icon: "", visible: true, disabled: false, renderStage: "onViewShown" }) }, execute: function() { var isDisabled = this._options.disabled; if (isFunction(isDisabled)) { isDisabled = !!isDisabled.apply(this, arguments) } if (isDisabled) { throw errors.Error("E3004", this._options.id) } this.fireEvent("beforeExecute", arguments); this._createActionByOption("onExecute").apply(this, arguments); this.fireEvent("afterExecute", arguments) }, _render: function() { this.callBase(); this.element().addClass("dx-command") }, _renderDisabledState: noop, _dispose: function() { this.callBase(); this.element().removeData(this.NAME) } }); registerComponent("dxCommand", Command); module.exports = Command }, /*!********************************!*\ !*** ./js/framework/errors.js ***! \********************************/ function(module, exports, __webpack_require__) { var errorUtils = __webpack_require__( /*! ../core/utils/error */ 8), errors = __webpack_require__( /*! ../core/errors */ 7); module.exports = errorUtils(errors.ERROR_MESSAGES, { E3001: "Routing rule is not found for the '{0}' URI.", E3002: "The passed object cannot be formatted into a URI string by the application's router. An appropriate route should be registered.", E3003: "Unable to navigate. Application is being initialized.", E3004: "Cannot execute the command: {0}.", E3005: "The '{0}' command {1} is not registered in the application's command mapping. Go to http://dxpr.es/1bTjfj1 for more details.", E3006: "Unknown navigation target: '{0}'. Use the 'current', 'back' or 'blank' values.", E3007: "Error while restoring the application state. The state has been cleared. Refresh the page.", E3008: "Unable to go back.", E3009: "Unable to go forward.", E3010: "The command's 'id' option should be specified.\r\nProcessed markup: {0}\n", E3011: "Layout controller cannot be resolved. There are no appropriate layout controllers for the current context. Check browser console for details.", E3012: "Layout controller cannot be resolved. Two or more layout controllers suit the current context. Check browser console for details.", E3013: "The '{0}' template with the '{1}' name is not found. Make sure the case is correct in the specified view name and the template fits the current context.", E3014: "All the children of the dxView element should be either of the dxCommand or dxContent type.\r\nProcessed markup: {0}", E3015: "The 'exec' method should be called before the 'finalize' method.", E3016: "Unknown transition type '{0}'.", E3018: "Unable to parse options.\nMessage: {0};\nOptions value: {1}.", E3019: "View templates should be updated according to the 13.1 changes. Go to http://dxpr.es/15ikrJA for more details.", E3020: "Concurrent templates are found:\r\n{0}Target device:\r\n{1}.", E3021: "Remote template cannot be loaded.\r\nUrl:{0}\r\nError:{1}.", E3022: "Cannot initialize the HtmlApplication component.", E3023: "Navigation item is not found", E3024: "Layout controller is not initialized", W3001: "A view with the '{0}' key doesn't exist.", W3002: "A view with the '{0}' key has already been released.", W3003: "Layout resolving context:\n{0}\nAvailable layout controller registrations:\n{1}\n", W3004: "Layout resolving context:\n{0}\nConcurent layout controller registrations for the context:\n{1}\n", W3005: 'Direct hash-based navigation is detected in a mobile application. Use data-bind="dxAction: url" instead of href="#url" to avoid navigation issues.\nFound markup:\n{0}\n' }) }, /*!********************************!*\ !*** ./js/framework/router.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, Class = __webpack_require__( /*! ../core/class */ 25); var JSON_URI_PREFIX = encodeURIComponent("json:"); var Route = Class.inherit({ _trimSeparators: function(str) { return str.replace(/^[\/.]+|\/+$/g, "") }, _escapeRe: function(str) { return str.replace(/[^-\w]/g, "\\$1") }, _checkConstraint: function(param, constraint) { param = String(param); if ("string" === typeof constraint) { constraint = new RegExp(constraint) } var match = constraint.exec(param); if (!match || match[0] !== param) { return false } return true }, _ensureReady: function() { var that = this; if (this._patternRe) { return false } this._pattern = this._trimSeparators(this._pattern); this._patternRe = ""; this._params = []; this._segments = []; this._separators = []; this._pattern.replace(/[^\/]+/g, function(segment, index) { that._segments.push(segment); if (index) { that._separators.push(that._pattern.substr(index - 1, 1)) } }); $.each(this._segments, function(index) { var segment = this, separator = index ? that._separators[index - 1] : ""; if (":" === segment.charAt(0)) { segment = segment.substr(1); that._params.push(segment); that._patternRe += "(?:" + separator + "([^/]*))"; if (segment in that._defaults) { that._patternRe += "?" } } else { that._patternRe += separator + that._escapeRe(segment) } }); this._patternRe = new RegExp("^" + this._patternRe + "$") }, ctor: function(pattern, defaults, constraints) { this._pattern = pattern || ""; this._defaults = defaults || {}; this._constraints = constraints || {} }, parse: function(uri) { var that = this; this._ensureReady(); var matches = this._patternRe.exec(uri); if (!matches) { return false } var result = extend({}, this._defaults); $.each(this._params, function(i) { var index = i + 1; if (matches.length >= index && matches[index]) { result[this] = that.parseSegment(matches[index]) } }); $.each(this._constraints, function(key) { if (!that._checkConstraint(result[key], that._constraints[key])) { result = false; return false } }); return result }, format: function(routeValues) { var that = this, query = ""; this._ensureReady(); var mergeValues = extend({}, this._defaults), useStatic = 0, result = [], dels = [], unusedRouteValues = {}; $.each(routeValues, function(paramName, paramValue) { routeValues[paramName] = that.formatSegment(paramValue); if (!(paramName in mergeValues)) { unusedRouteValues[paramName] = true } }); $.each(this._segments, function(index, segment) { result[index] = index ? that._separators[index - 1] : ""; if (":" === segment.charAt(0)) { var paramName = segment.substr(1); if (!(paramName in routeValues) && !(paramName in that._defaults)) { result = null; return false } if (paramName in that._constraints && !that._checkConstraint(routeValues[paramName], that._constraints[paramName])) { result = null; return false } if (paramName in routeValues) { if (void 0 !== routeValues[paramName]) { mergeValues[paramName] = routeValues[paramName]; result[index] += routeValues[paramName]; useStatic = index } delete unusedRouteValues[paramName] } else { if (paramName in mergeValues) { result[index] += mergeValues[paramName]; dels.push(index) } } } else { result[index] += segment; useStatic = index } }); $.each(mergeValues, function(key, value) { if (!!value && inArray(":" + key, that._segments) === -1 && routeValues[key] !== value) { result = null; return false } }); var unusedCount = 0; if (!typeUtils.isEmptyObject(unusedRouteValues)) { query = "?"; $.each(unusedRouteValues, function(key) { query += key + "=" + routeValues[key] + "&"; unusedCount++ }); query = query.substr(0, query.length - 1) } if (null === result) { return false } if (dels.length) { $.map(dels, function(i) { if (i >= useStatic) { result[i] = "" } }) } var path = result.join(""); path = path.replace(/\/+$/, ""); return { uri: path + query, unusedCount: unusedCount } }, formatSegment: function(value) { if (Array.isArray(value) || typeUtils.isPlainObject(value)) { return JSON_URI_PREFIX + encodeURIComponent(JSON.stringify(value)) } return encodeURIComponent(value) }, parseSegment: function(value) { if (value.substr(0, JSON_URI_PREFIX.length) === JSON_URI_PREFIX) { try { return JSON.parse(decodeURIComponent(value.substr(JSON_URI_PREFIX.length))) } catch (x) {} } return decodeURIComponent(value) } }); var Router = Class.inherit({ ctor: function() { this._registry = [] }, _trimSeparators: function(str) { return str.replace(/^[\/.]+|\/+$/g, "") }, _createRoute: function(pattern, defaults, constraints) { return new Route(pattern, defaults, constraints) }, register: function(pattern, defaults, constraints) { this._registry.push(this._createRoute(pattern, defaults, constraints)) }, _parseQuery: function(query) { var result = {}, values = query.split("&"); $.each(values, function(index, value) { var keyValuePair = value.split("="); result[keyValuePair[0]] = decodeURIComponent(keyValuePair[1]) }); return result }, parse: function(uri) { var result, that = this; uri = this._trimSeparators(uri); var parts = uri.split("?", 2), path = parts[0], query = parts[1]; $.each(this._registry, function() { var parseResult = this.parse(path); if (false !== parseResult) { result = parseResult; if (query) { result = extend(result, that._parseQuery(query)) } return false } }); return result ? result : false }, format: function(obj) { var result = false, minUnusedCount = 99999; obj = obj || {}; $.each(this._registry, function() { var toFormat = extend(true, {}, obj); var formatResult = this.format(toFormat); if (false !== formatResult) { if (minUnusedCount > formatResult.unusedCount) { minUnusedCount = formatResult.unusedCount; result = formatResult.uri } } }); return result } }); Route.__internals = { JSON_URI_PREFIX: JSON_URI_PREFIX }; module.exports = Router; module.exports.Route = Route }, /*!***************************************!*\ !*** ./js/framework/state_manager.js ***! \***************************************/ function(module, exports, __webpack_require__) { var Class = __webpack_require__( /*! ../core/class */ 25), inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, $ = __webpack_require__( /*! ../core/renderer */ 9); var MemoryKeyValueStorage = Class.inherit({ ctor: function() { this.storage = {} }, getItem: function(key) { return this.storage[key] }, setItem: function(key, value) { this.storage[key] = value }, removeItem: function(key) { delete this.storage[key] } }); var StateManager = Class.inherit({ ctor: function(options) { options = options || {}; this.storage = options.storage || new MemoryKeyValueStorage; this.stateSources = options.stateSources || [] }, addStateSource: function(stateSource) { this.stateSources.push(stateSource) }, removeStateSource: function(stateSource) { var index = inArray(stateSource, this.stateSources); if (index > -1) { this.stateSources.splice(index, 1); stateSource.removeState(this.storage) } }, saveState: function() { var that = this; $.each(this.stateSources, function(index, stateSource) { stateSource.saveState(that.storage) }) }, restoreState: function() { var that = this; $.each(this.stateSources, function(index, stateSource) { stateSource.restoreState(that.storage) }) }, clearState: function() { var that = this; $.each(this.stateSources, function(index, stateSource) { stateSource.removeState(that.storage) }) } }); module.exports = StateManager; module.exports.MemoryKeyValueStorage = MemoryKeyValueStorage }, /*!************************************!*\ !*** ./js/framework/view_cache.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, Class = __webpack_require__( /*! ../core/class */ 25), EventsMixin = __webpack_require__( /*! ../core/events_mixin */ 51); var ViewCache = Class.inherit({ ctor: function() { this._cache = {} }, setView: function(key, viewInfo) { this._cache[key] = viewInfo }, getView: function(key) { return this._cache[key] }, removeView: function(key) { var result = this._cache[key]; if (result) { delete this._cache[key]; this.fireEvent("viewRemoved", [{ viewInfo: result }]) } return result }, clear: function() { var that = this; $.each(this._cache, function(key) { that.removeView(key) }) }, hasView: function(key) { return key in this._cache } }).include(EventsMixin); var NullViewCache = ViewCache.inherit({ setView: function(key, viewInfo) { this.callBase(key, viewInfo); this.removeView(key) } }); function delegateEvent(eventName, source, target) { source.on(eventName, function() { target.fireEvent(eventName, arguments) }) } var ConditionalViewCacheDecorator = Class.inherit({ ctor: function(options) { this._filter = options.filter; this._viewCache = options.viewCache; this.viewRemoved = this._viewCache.viewRemoved; delegateEvent("viewRemoved", this._viewCache, this) }, setView: function(key, viewInfo) { this._viewCache.setView(key, viewInfo); if (!this._filter(key, viewInfo)) { this._viewCache.removeView(key) } }, getView: function(key) { return this._viewCache.getView(key) }, removeView: function(key) { return this._viewCache.removeView(key) }, clear: function() { return this._viewCache.clear() }, hasView: function(key) { return this._viewCache.hasView(key) } }).include(EventsMixin); var DEFAULT_VIEW_CACHE_CAPACITY = 5; var CapacityViewCacheDecorator = Class.inherit({ ctor: function(options) { this._keys = []; this._size = options.size || DEFAULT_VIEW_CACHE_CAPACITY; this._viewCache = options.viewCache; this.viewRemoved = this._viewCache.viewRemoved; delegateEvent("viewRemoved", this._viewCache, this) }, setView: function(key, viewInfo) { if (!this.hasView(key)) { if (this._keys.length === this._size) { this.removeView(this._keys[0]) } this._keys.push(key) } this._viewCache.setView(key, viewInfo) }, getView: function(key) { var index = inArray(key, this._keys); if (index < 0) { return null } this._keys.push(key); this._keys.splice(index, 1); return this._viewCache.getView(key) }, removeView: function(key) { var index = inArray(key, this._keys); if (index > -1) { this._keys.splice(index, 1) } return this._viewCache.removeView(key) }, clear: function() { this._keys = []; return this._viewCache.clear() }, hasView: function(key) { return this._viewCache.hasView(key) } }).include(EventsMixin); var HistoryDependentViewCacheDecorator = Class.inherit({ ctor: function(options) { this._viewCache = options.viewCache || new ViewCache; this._navigationManager = options.navigationManager; this._navigationManager.on("itemRemoved", this._onNavigationItemRemoved.bind(this)); this.viewRemoved = this._viewCache.viewRemoved; delegateEvent("viewRemoved", this._viewCache, this) }, _onNavigationItemRemoved: function(item) { this.removeView(item.key) }, setView: function(key, viewInfo) { this._viewCache.setView(key, viewInfo) }, getView: function(key) { return this._viewCache.getView(key) }, removeView: function(key) { return this._viewCache.removeView(key) }, clear: function() { return this._viewCache.clear() }, hasView: function(key) { return this._viewCache.hasView(key) } }).include(EventsMixin); module.exports = ViewCache; module.exports.NullViewCache = NullViewCache; module.exports.ConditionalViewCacheDecorator = ConditionalViewCacheDecorator; module.exports.CapacityViewCacheDecorator = CapacityViewCacheDecorator; module.exports.HistoryDependentViewCacheDecorator = HistoryDependentViewCacheDecorator }, /*!************************************************!*\ !*** ./js/framework/html/command_container.js ***! \************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), MarkupComponent = __webpack_require__( /*! ./markup_component */ 127).MarkupComponent, isPlainObject = __webpack_require__( /*! ../../core/utils/type */ 12).isPlainObject, registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57); __webpack_require__( /*! ../../integration/knockout */ 92); var CommandContainer = MarkupComponent.inherit({ ctor: function(element, options) { if (isPlainObject(element)) { options = element; element = $("<div />") } this.callBase(element, options) }, _setDefaultOptions: function() { this.callBase(); this.option({ id: null }) }, _render: function() { this.callBase(); this.element().addClass("dx-command-container") } }); registerComponent("dxCommandContainer", CommandContainer); module.exports = CommandContainer }, /*!***********************************************!*\ !*** ./js/framework/html/markup_component.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, publicComponentUtils = __webpack_require__( /*! ../../core/utils/public_component */ 45); var MarkupComponent = Class.inherit({ ctor: function(element, options) { this.NAME = publicComponentUtils.name(this.constructor); options = options || {}; this._$element = $(element); publicComponentUtils.attachInstanceToElement(this._$element, this, this._dispose); if (options.fromCache) { this._options = options } else { this._options = {}; this._setDefaultOptions(); if (options) { this.option(options) } this._render() } }, _setDefaultOptions: noop, _render: noop, _dispose: noop, element: function() { return this._$element }, option: function(name, value) { if (0 === arguments.length) { return this._options } else { if (1 === arguments.length) { if ("string" === typeof name) { return this._options[name] } else { value = name; extend(this._options, value) } } else { this._options[name] = value } } }, instance: function() { return this } }); MarkupComponent.getInstance = function($element) { return publicComponentUtils.getInstanceByElement($($element), this) }; exports.MarkupComponent = MarkupComponent }, /*!*****************************************************!*\ !*** ./js/framework/html/view_engine_components.js ***! \*****************************************************/ function(module, exports, __webpack_require__) { var errors = __webpack_require__( /*! ../errors */ 122), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), MarkupComponent = __webpack_require__( /*! ./markup_component */ 127).MarkupComponent; __webpack_require__( /*! ../../integration/knockout */ 92); var View = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ name: null, title: null }) }, ctor: function() { this._id = domUtils.uniqueId(); this.callBase.apply(this, arguments) }, _render: function() { this.callBase(); this.element().addClass("dx-view"); this.element().attr("dx-data-template-id", this._id) }, getId: function() { return this._id } }); var Layout = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ name: null }) }, _render: function() { this.callBase(); this.element().addClass("dx-layout") } }); var ViewPlaceholder = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ viewName: null }) }, _render: function() { this.callBase(); this.element().addClass("dx-view-placeholder") } }); var setupTransitionElement = function($element, transitionType, transitionName, contentCssPosition) { if ("absolute" === contentCssPosition) { $element.addClass("dx-transition-absolute") } else { $element.addClass("dx-transition-static") } $element.addClass("dx-transition").addClass("dx-transition-" + transitionName).addClass("dx-transition-" + transitionType).attr("data-dx-transition-type", transitionType).attr("data-dx-transition-name", transitionName) }; var setupTransitionInnerElement = function($element) { $element.addClass("dx-transition-inner-wrapper") }; var Transition = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ name: null, type: void 0, animation: "slide" }) }, _render: function() { this.callBase(); var element = this.element(); setupTransitionElement(element, this.option("type") || this.option("animation"), this.option("name"), "absolute"); element.wrapInner("<div/>"); setupTransitionInnerElement(element.children()); if (this.option("type")) { errors.log("W0003", "dxTransition", "type", "15.1", "Use the 'animation' property instead") } }, _clean: function() { this.callBase(); this.element().empty() } }); var ContentPlaceholder = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ name: null, transition: void 0, animation: "none", contentCssPosition: "absolute" }) }, _render: function() { this.callBase(); var $element = this.element(); $element.addClass("dx-content-placeholder").addClass("dx-content-placeholder-" + this.option("name")); $element.attr("data-dx-content-placeholder-name", this.option("name")); setupTransitionElement($element, this.option("transition") || this.option("animation"), this.option("name"), this.option("contentCssPosition")); if (this.option("transition")) { errors.log("W0003", "dxContentPlaceholder", "transition", "15.1", "Use the 'animation' property instead") } } }); var Content = MarkupComponent.inherit({ _setDefaultOptions: function() { this.callBase(); this.option({ targetPlaceholder: null }) }, _optionChanged: function() { this._refresh() }, _clean: function() { this.callBase(); this.element().removeClass(this._currentClass) }, _render: function() { this.callBase(); var element = this.element(); element.addClass("dx-content"); this._currentClass = "dx-content-" + this.option("targetPlaceholder"); element.attr("data-dx-target-placeholder-id", this.option("targetPlaceholder")); element.addClass(this._currentClass); setupTransitionInnerElement(element) } }); registerComponent("dxView", View); registerComponent("dxLayout", Layout); registerComponent("dxViewPlaceholder", ViewPlaceholder); registerComponent("dxContentPlaceholder", ContentPlaceholder); registerComponent("dxTransition", Transition); registerComponent("dxContent", Content); exports.dxView = View; exports.dxLayout = Layout; exports.dxViewPlaceholder = ViewPlaceholder; exports.dxContentPlaceholder = ContentPlaceholder; exports.dxTransition = Transition; exports.dxContent = Content }, /*!***********************************************!*\ !*** ./js/framework/html/html_application.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), Component = __webpack_require__( /*! ../../core/component */ 48), extendUtils = __webpack_require__( /*! ../../core/utils/extend */ 11), errors = __webpack_require__( /*! ../errors */ 122), Application = __webpack_require__( /*! ../application */ 130).Application, ConditionalViewCacheDecorator = __webpack_require__( /*! ../view_cache */ 125).ConditionalViewCacheDecorator, html = __webpack_require__( /*! ./presets */ 138), CommandManager = __webpack_require__( /*! ./command_manager */ 139), ViewEngine = __webpack_require__( /*! ./view_engine */ 141).ViewEngine, messageLocalization = __webpack_require__( /*! ../../localization/message */ 89), viewPort = __webpack_require__( /*! ../../core/utils/view_port */ 55).value, initMobileViewportModule = __webpack_require__( /*! ../../mobile/init_mobile_viewport/init_mobile_viewport */ 60), devices = __webpack_require__( /*! ../../core/devices */ 53), feedbackEvents = __webpack_require__( /*! ../../events/core/emitter.feedback */ 104), TransitionExecutorModule = __webpack_require__( /*! ../../animation/transition_executor/transition_executor */ 74), animationPresetsModule = __webpack_require__( /*! ../../animation/presets/presets */ 67), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; __webpack_require__( /*! ./layout_controller */ 142); __webpack_require__( /*! ../../ui/themes */ 143); var VIEW_PORT_CLASSNAME = "dx-viewport", LAYOUT_CHANGE_ANIMATION_NAME = "layout-change"; var HtmlApplication = Application.inherit({ ctor: function(options) { options = options || {}; this.callBase(options); this._$root = $(options.rootNode || document.body); this._initViewport(options.viewPort); if ("mobileApp" === this._applicationMode) { initMobileViewportModule.initMobileViewport(options.viewPort) } this.device = options.device || devices.current(); this.commandManager = options.commandManager || new CommandManager({ commandMapping: this.commandMapping }); this._initTemplateContext(); this.viewEngine = options.viewEngine || new ViewEngine({ $root: this._$root, device: this.device, templateCacheStorage: options.templateCacheStorage || window.localStorage, templatesVersion: options.templatesVersion, templateContext: this._templateContext }); this.components.push(this.viewEngine); this._initMarkupFilters(this.viewEngine); this._layoutSet = options.layoutSet || html.layoutSets.default; this._animationSet = options.animationSet || html.animationSets.default; this._availableLayoutControllers = []; this._activeLayoutControllersStack = []; this.transitionExecutor = new TransitionExecutorModule.TransitionExecutor; this._initAnimations(this._animationSet) }, _initAnimations: function(animationSet) { if (!animationSet) { return } $.each(animationSet, function(name, configs) { $.each(configs, function(index, config) { animationPresetsModule.presets.registerPreset(name, config) }) }); animationPresetsModule.presets.applyChanges() }, _localizeMarkup: function($markup) { messageLocalization.localizeNode($markup) }, _notifyIfBadMarkup: function($markup) { $markup.each(function() { var html = $(this).html(); if (/href="#/.test(html)) { errors.log("W3005", html) } }) }, _initMarkupFilters: function(viewEngine) { var filters = []; filters.push(this._localizeMarkup); if ("mobileApp" === this._applicationMode) { filters.push(this._notifyIfBadMarkup) } if (viewEngine.markupLoaded) { viewEngine.markupLoaded.add(function(args) { $.each(filters, function(_, filter) { filter(args.markup) }) }) } }, _createViewCache: function(options) { var result = this.callBase(options); if (!options.viewCache) { result = new ConditionalViewCacheDecorator({ filter: function(key, viewInfo) { return !viewInfo.viewTemplateInfo.disableCache }, viewCache: result }) } return result }, _initViewport: function() { this._$viewPort = this._getViewPort(); viewPort(this._$viewPort) }, _getViewPort: function() { var $viewPort = $("." + VIEW_PORT_CLASSNAME); if (!$viewPort.length) { $viewPort = $("<div>").addClass(VIEW_PORT_CLASSNAME).appendTo(this._$root) } return $viewPort }, _initTemplateContext: function() { this._templateContext = new Component({ orientation: devices.orientation() }); devices.on("orientationChanged", function(args) { this._templateContext.option("orientation", args.orientation) }.bind(this)) }, _showViewImpl: function(viewInfo, direction) { var that = this, deferred = $.Deferred(), result = deferred.promise(), layoutController = viewInfo.layoutController; that._obtainViewLink(viewInfo); layoutController.showView(viewInfo, direction).done(function() { that._activateLayoutController(layoutController, that._getTargetNode(viewInfo), direction).done(function() { deferred.resolve() }) }); feedbackEvents.lock(result); return result }, _resolveLayoutController: function(viewInfo) { var args = { viewInfo: viewInfo, layoutController: null, availableLayoutControllers: this._availableLayoutControllers }; this._processEvent("resolveLayoutController", args, viewInfo.model); this._checkLayoutControllerIsInitialized(args.layoutController); return args.layoutController || this._resolveLayoutControllerImpl(viewInfo) }, _checkLayoutControllerIsInitialized: function(layoutController) { if (layoutController) { var isControllerInited = false; $.each(this._layoutSet, function(_, controllerInfo) { if (controllerInfo.controller === layoutController) { isControllerInited = true; return false } }); if (!isControllerInited) { throw errors.Error("E3024") } } }, _ensureOneLayoutControllerFound: function(target, matches) { var toJSONInterceptor = function(key, value) { if ("controller" === key) { return "[controller]: { name:" + value.name + " }" } return value }; if (!matches.length) { errors.log("W3003", JSON.stringify(target, null, 4), JSON.stringify(this._availableLayoutControllers, toJSONInterceptor, 4)); throw errors.Error("E3011") } if (matches.length > 1) { errors.log("W3004", JSON.stringify(target, null, 4), JSON.stringify(matches, toJSONInterceptor, 4)); throw errors.Error("E3012") } }, _resolveLayoutControllerImpl: function(viewInfo) { var templateInfo = viewInfo.viewTemplateInfo || {}, navigateOptions = viewInfo.navigateOptions || {}, target = extendUtils.extend({ root: !viewInfo.canBack, customResolveRequired: false, pane: templateInfo.pane, modal: void 0 !== navigateOptions.modal ? navigateOptions.modal : templateInfo.modal || false }, devices.current()); var matches = commonUtils.findBestMatches(target, this._availableLayoutControllers); this._ensureOneLayoutControllerFound(target, matches); return matches[0].controller }, _onNavigatingBack: function(args) { this.callBase.apply(this, arguments); if (!args.cancel && !this.canBack() && this._activeLayoutControllersStack.length > 1) { var previousActiveLayoutController = this._activeLayoutControllersStack[this._activeLayoutControllersStack.length - 2], previousViewInfo = previousActiveLayoutController.activeViewInfo(); args.cancel = true; this._activateLayoutController(previousActiveLayoutController, void 0, "backward"); this.navigationManager.currentItem(previousViewInfo.key) } }, _activeLayoutController: function() { return this._activeLayoutControllersStack.length ? this._activeLayoutControllersStack[this._activeLayoutControllersStack.length - 1] : void 0 }, _getTargetNode: function(viewInfo) { var jQueryEvent = (viewInfo.navigateOptions || {}).jQueryEvent; return jQueryEvent ? $(jQueryEvent.target) : void 0 }, _activateLayoutController: function(layoutController, targetNode, direction) { var that = this, previousLayoutController = that._activeLayoutController(); if (previousLayoutController === layoutController) { return $.Deferred().resolve().promise() } var d = $.Deferred(); layoutController.ensureActive(targetNode).done(function(result) { that._deactivatePreviousLayoutControllers(layoutController, direction, result).done(function() { that._activeLayoutControllersStack.push(layoutController); d.resolve() }) }); return d.promise() }, _deactivatePreviousLayoutControllers: function(layoutController, direction) { var that = this, tasks = [], controllerToDeactivate = that._activeLayoutControllersStack.pop(); if (!controllerToDeactivate) { return $.Deferred().resolve().promise() } if (layoutController.isOverlay) { that._activeLayoutControllersStack.push(controllerToDeactivate); tasks.push(controllerToDeactivate.disable()) } else { var transitionDeferred = $.Deferred(), skipAnimation = false; var getControllerDeactivator = function(controllerToDeactivate, d) { return function() { controllerToDeactivate.deactivate().done(function() { d.resolve() }) } }; while (controllerToDeactivate && controllerToDeactivate !== layoutController) { var d = $.Deferred(); if (controllerToDeactivate.isOverlay) { skipAnimation = true } else { that.transitionExecutor.leave(controllerToDeactivate.element(), LAYOUT_CHANGE_ANIMATION_NAME, { direction: direction }) } transitionDeferred.promise().done(getControllerDeactivator(controllerToDeactivate, d)); tasks.push(d.promise()); controllerToDeactivate = that._activeLayoutControllersStack.pop() } if (skipAnimation) { transitionDeferred.resolve() } else { that.transitionExecutor.enter(layoutController.element(), LAYOUT_CHANGE_ANIMATION_NAME, { direction: direction }); that.transitionExecutor.start().done(function() { transitionDeferred.resolve() }) } } return when.apply($, tasks) }, init: function() { var that = this, result = this.callBase(); result.done(function() { that._initLayoutControllers(); that.renderNavigation() }); return result }, _disposeView: function(viewInfo) { if (viewInfo.layoutController.disposeView) { viewInfo.layoutController.disposeView(viewInfo) } this.callBase(viewInfo) }, viewPort: function() { return this._$viewPort }, _createViewInfo: function() { var viewInfo = this.callBase.apply(this, arguments), templateInfo = this.getViewTemplateInfo(viewInfo.viewName); if (!templateInfo) { throw errors.Error("E3013", "dxView", viewInfo.viewName) } viewInfo.viewTemplateInfo = templateInfo; viewInfo.layoutController = this._resolveLayoutController(viewInfo); return viewInfo }, _createViewModel: function(viewInfo) { this.callBase(viewInfo); extendUtils.extendFromObject(viewInfo.model, viewInfo.viewTemplateInfo) }, _initLayoutControllers: function() { var that = this; $.each(that._layoutSet, function(index, controllerInfo) { var controller = controllerInfo.controller, target = devices.current(); if (commonUtils.findBestMatches(target, [controllerInfo]).length) { that._availableLayoutControllers.push(controllerInfo); if (controller.init) { controller.init({ app: that, $viewPort: that._$viewPort, navigationManager: that.navigationManager, viewEngine: that.viewEngine, templateContext: that._templateContext, commandManager: that.commandManager }) } if (controller.on) { controller.on("viewReleased", function(viewInfo) { that._onViewReleased(viewInfo) }); controller.on("viewHidden", function(viewInfo) { that._onViewHidden(viewInfo) }); controller.on("viewRendered", function(viewInfo) { that._processEvent("viewRendered", { viewInfo: viewInfo }, viewInfo.model) }); controller.on("viewShowing", function(viewInfo, direction) { that._processEvent("viewShowing", { viewInfo: viewInfo, direction: direction, params: viewInfo.routeData }, viewInfo.model) }); controller.on("viewShown", function(viewInfo, direction) { that._processEvent("viewShown", { viewInfo: viewInfo, direction: direction, params: viewInfo.routeData }, viewInfo.model) }) } } }) }, _onViewReleased: function(viewInfo) { this._releaseViewLink(viewInfo) }, renderNavigation: function() { var that = this; $.each(that._availableLayoutControllers, function(index, controllerInfo) { var controller = controllerInfo.controller; if (controller.renderNavigation) { controller.renderNavigation(that.navigation) } }) }, getViewTemplate: function(viewName) { return this.viewEngine.getViewTemplate(viewName) }, getViewTemplateInfo: function(viewName) { var viewComponent = this.viewEngine.getViewTemplateInfo(viewName); return viewComponent && viewComponent.option() }, loadTemplates: function(source) { return this.viewEngine.loadTemplates(source) }, templateContext: function() { return this._templateContext } }); module.exports = HtmlApplication }, /*!*************************************!*\ !*** ./js/framework/application.js ***! \*************************************/ function(module, exports, __webpack_require__) { var BACK_COMMAND_TITLE, $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), abstract = Class.abstract, Action = __webpack_require__( /*! ../core/action */ 49), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, mergeCommands = __webpack_require__( /*! ./utils */ 131).utils.mergeCommands, createActionExecutors = __webpack_require__( /*! ./action_executors */ 132).createActionExecutors, Router = __webpack_require__( /*! ./router */ 123), NavigationManager = __webpack_require__( /*! ./navigation_manager */ 133), StateManager = __webpack_require__( /*! ./state_manager */ 124), dxCommand = __webpack_require__( /*! ./command */ 121), messageLocalization = __webpack_require__( /*! ../localization/message */ 89), CommandMapping = __webpack_require__( /*! ./command_mapping */ 136), ViewCache = __webpack_require__( /*! ./view_cache */ 125), EventsMixin = __webpack_require__( /*! ../core/events_mixin */ 51), sessionStorage = __webpack_require__( /*! ../core/utils/storage */ 54).sessionStorage, dataUtils = __webpack_require__( /*! ../data/utils */ 137), errors = __webpack_require__( /*! ./errors */ 122), when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when, INIT_IN_PROGRESS = "InProgress", INIT_COMPLETE = "Inited"; var Application = Class.inherit({ ctor: function(options) { options = options || {}; this._options = options; this.namespace = options.namespace || window; this._applicationMode = options.mode ? options.mode : "mobileApp"; this.components = []; BACK_COMMAND_TITLE = messageLocalization.localizeString("@Back"); this.router = options.router || new Router; var navigationManagers = { mobileApp: NavigationManager.StackBasedNavigationManager, webSite: NavigationManager.HistoryBasedNavigationManager }; this.navigationManager = options.navigationManager || new navigationManagers[this._applicationMode]({ keepPositionInStack: "keepHistory" === options.navigateToRootViewMode }); this.navigationManager.on("navigating", this._onNavigating.bind(this)); this.navigationManager.on("navigatingBack", this._onNavigatingBack.bind(this)); this.navigationManager.on("navigated", this._onNavigated.bind(this)); this.navigationManager.on("navigationCanceled", this._onNavigationCanceled.bind(this)); this.stateManager = options.stateManager || new StateManager({ storage: options.stateStorage || sessionStorage() }); this.stateManager.addStateSource(this.navigationManager); this.viewCache = this._createViewCache(options); this.commandMapping = this._createCommandMapping(options.commandMapping); this.createNavigation(options.navigation); this._isNavigating = false; this._viewLinksHash = {}; Action.registerExecutor(createActionExecutors(this)); this.components.push(this.router); this.components.push(this.navigationManager) }, _createViewCache: function(options) { var result; if (options.viewCache) { result = options.viewCache } else { if (options.disableViewCache) { result = new ViewCache.NullViewCache } else { result = new ViewCache.CapacityViewCacheDecorator({ size: options.viewCacheSize, viewCache: new ViewCache }) } } result.on("viewRemoved", function(e) { this._releaseViewLink(e.viewInfo) }.bind(this)); return result }, _createCommandMapping: function(commandMapping) { var result = commandMapping; if (!(commandMapping instanceof CommandMapping)) { result = new CommandMapping; result.load(CommandMapping.defaultMapping || {}).load(commandMapping || {}) } return result }, createNavigation: function(navigationConfig) { this.navigation = this._createNavigationCommands(navigationConfig); this._mapNavigationCommands(this.navigation, this.commandMapping) }, _createNavigationCommands: function(commandConfig) { if (!commandConfig) { return [] } var generatedIdCount = 0; return $.map(commandConfig, function(item) { var command; if (item instanceof dxCommand) { command = item } else { command = new dxCommand(extend({ root: true }, item)) } if (!command.option("id")) { command.option("id", "navigation_" + generatedIdCount++) } return command }) }, _mapNavigationCommands: function(navigationCommands, commandMapping) { var navigationCommandIds = $.map(navigationCommands, function(command) { return command.option("id") }); commandMapping.mapCommands("global-navigation", navigationCommandIds) }, _callComponentMethod: function(methodName, args) { var tasks = []; $.each(this.components, function(index, component) { if (component[methodName] && commonUtils.isFunction(component[methodName])) { var result = component[methodName](args); if (result && result.done) { tasks.push(result) } } }); return when.apply($, tasks) }, init: function() { var that = this; that._initState = INIT_IN_PROGRESS; return that._callComponentMethod("init").done(function() { that._initState = INIT_COMPLETE; that._processEvent("initialized") }).fail(function(error) { throw error || errors.Error("E3022") }) }, _onNavigatingBack: function(args) { this._processEvent("navigatingBack", args) }, _onNavigating: function(args) { var that = this; if (that._isNavigating) { that._pendingNavigationArgs = args; args.cancel = true; return } else { that._isNavigating = true; delete that._pendingNavigationArgs } var routeData = this.router.parse(args.uri); if (!routeData) { throw errors.Error("E3001", args.uri) } var uri = this.router.format(routeData); if (args.uri !== uri && uri) { args.cancel = true; args.cancelReason = "redirect"; commonUtils.executeAsync(function() { that.navigate(uri, args.options) }) } else { that._processEvent("navigating", args) } }, _onNavigated: function(args) { var resultDeferred, that = this, direction = args.options.direction, viewInfo = that._acquireViewInfo(args.item, args.options); if (!viewInfo.model) { this._processEvent("beforeViewSetup", { viewInfo: viewInfo }); that._createViewModel(viewInfo); that._createViewCommands(viewInfo); this._processEvent("afterViewSetup", { viewInfo: viewInfo }) } that._highlightCurrentNavigationCommand(viewInfo); resultDeferred = that._showView(viewInfo, direction).always(function() { that._isNavigating = false; var pendingArgs = that._pendingNavigationArgs; if (pendingArgs) { commonUtils.executeAsync(function() { that.navigate(pendingArgs.uri, pendingArgs.options) }) } }); return resultDeferred }, _isViewReadyToShow: function(viewInfo) { return !!viewInfo.model }, _onNavigationCanceled: function(args) { var that = this; if (!that._pendingNavigationArgs || that._pendingNavigationArgs.uri !== args.uri) { var currentItem = that.navigationManager.currentItem(); if (currentItem) { commonUtils.executeAsync(function() { var viewInfo = that._acquireViewInfo(currentItem, args.options); that._highlightCurrentNavigationCommand(viewInfo, true) }) } that._isNavigating = false } }, _disposeRemovedViews: function() { var args, that = this; $.each(that._viewLinksHash, function(key, link) { if (!link.linkCount) { args = { viewInfo: link.viewInfo }; that._processEvent("viewDisposing", args, args.viewInfo.model); that._disposeView(link.viewInfo); that._processEvent("viewDisposed", args, args.viewInfo.model); delete that._viewLinksHash[key] } }) }, _onViewHidden: function(viewInfo) { var args = { viewInfo: viewInfo }; this._processEvent("viewHidden", args, args.viewInfo.model) }, _disposeView: function(viewInfo) { var commands = viewInfo.commands || []; $.each(commands, function(index, command) { command._dispose() }) }, _acquireViewInfo: function(navigationItem, navigateOptions) { var routeData = this.router.parse(navigationItem.uri), viewInfoKey = this._getViewInfoKey(navigationItem, routeData), viewInfo = this.viewCache.getView(viewInfoKey); if (!viewInfo) { viewInfo = this._createViewInfo(navigationItem, navigateOptions); this._obtainViewLink(viewInfo); this.viewCache.setView(viewInfoKey, viewInfo) } else { this._updateViewInfo(viewInfo, navigationItem, navigateOptions) } return viewInfo }, _getViewInfoKey: function(navigationItem, routeData) { var args = { key: navigationItem.key, navigationItem: navigationItem, routeData: routeData }; this._processEvent("resolveViewCacheKey", args); return args.key }, _processEvent: function(eventName, args, model) { this._callComponentMethod(eventName, args); this.fireEvent(eventName, args && [args]); var modelMethod = (model || {})[eventName]; if (modelMethod) { modelMethod.call(model, args) } }, _updateViewInfo: function(viewInfo, navigationItem, navigateOptions) { var uri = navigationItem.uri, routeData = this.router.parse(uri); viewInfo.viewName = routeData.view; viewInfo.routeData = routeData; viewInfo.uri = uri; viewInfo.navigateOptions = navigateOptions; viewInfo.canBack = this.canBack(navigateOptions.stack); viewInfo.previousViewInfo = this._getPreviousViewInfo(navigateOptions) }, _createViewInfo: function(navigationItem, navigateOptions) { var uri = navigationItem.uri, routeData = this.router.parse(uri), viewInfo = { key: this._getViewInfoKey(navigationItem, routeData) }; this._updateViewInfo(viewInfo, navigationItem, navigateOptions); return viewInfo }, _createViewModel: function(viewInfo) { viewInfo.model = viewInfo.model || this._callViewCodeBehind(viewInfo) }, _createViewCommands: function(viewInfo) { viewInfo.commands = viewInfo.model.commands || []; if (viewInfo.canBack && "webSite" !== this._applicationMode) { this._appendBackCommand(viewInfo) } }, _callViewCodeBehind: function(viewInfo) { var setupFunc = commonUtils.noop, routeData = viewInfo.routeData; if (routeData.view in this.namespace) { setupFunc = this.namespace[routeData.view] } return setupFunc.call(this.namespace, routeData, viewInfo) || {} }, _appendBackCommand: function(viewInfo) { var commands = viewInfo.commands, that = this, backTitle = BACK_COMMAND_TITLE; if (that._options.useViewTitleAsBackText) { backTitle = ((viewInfo.previousViewInfo || {}).model || {}).title || backTitle } var toMergeTo = [new dxCommand({ id: "back", title: backTitle, behavior: "back", onExecute: function() { that.back({ stack: viewInfo.navigateOptions.stack }) }, icon: "arrowleft", type: "back", renderStage: that._options.useViewTitleAsBackText ? "onViewRendering" : "onViewShown" })]; var result = mergeCommands(toMergeTo, commands); commands.length = 0; commands.push.apply(commands, result) }, _showView: function(viewInfo, direction) { var that = this; var eventArgs = { viewInfo: viewInfo, direction: direction, params: viewInfo.routeData }; dataUtils.processRequestResultLock.obtain(); return that._showViewImpl(eventArgs.viewInfo, eventArgs.direction).done(function() { commonUtils.executeAsync(function() { dataUtils.processRequestResultLock.release(); that._processEvent("viewShown", eventArgs, viewInfo.model); that._disposeRemovedViews() }) }) }, _highlightCurrentNavigationCommand: function(viewInfo, forceUpdate) { var selectedCommand, that = this, currentNavigationItemId = viewInfo.model && viewInfo.model.currentNavigationItemId; if (void 0 !== currentNavigationItemId) { $.each(this.navigation, function(index, command) { if (command.option("id") === currentNavigationItemId) { selectedCommand = command; return false } }) } if (!selectedCommand) { $.each(this.navigation, function(index, command) { var commandUri = command.option("onExecute"); if (commonUtils.isString(commandUri)) { commandUri = commandUri.replace(/^#+/, ""); if (commandUri === that.navigationManager.rootUri()) { selectedCommand = command; return false } } }) } $.each(this.navigation, function(index, command) { if (forceUpdate && command === selectedCommand && command.option("highlighted")) { command.fireEvent("optionChanged", [{ name: "highlighted", value: true, previousValue: true }]) } command.option("highlighted", command === selectedCommand) }) }, _showViewImpl: abstract, _obtainViewLink: function(viewInfo) { var key = viewInfo.key; if (!this._viewLinksHash[key]) { this._viewLinksHash[key] = { viewInfo: viewInfo, linkCount: 1 } } else { this._viewLinksHash[key].linkCount++ } }, _releaseViewLink: function(viewInfo) { if (void 0 === this._viewLinksHash[viewInfo.key]) { errors.log("W3001", viewInfo.key) } if (0 === this._viewLinksHash[viewInfo.key].linkCount) { errors.log("W3002", viewInfo.key) } this._viewLinksHash[viewInfo.key].linkCount-- }, navigate: function(uri, options) { var that = this; if (typeUtils.isPlainObject(uri)) { uri = that.router.format(uri); if (false === uri) { throw errors.Error("E3002") } } if (!that._initState) { that.init().done(function() { that.restoreState(); that.navigate(uri, options) }) } else { if (that._initState === INIT_COMPLETE) { if (!that._isNavigating || uri) { that.navigationManager.navigate(uri, options) } } else { throw errors.Error("E3003") } } }, canBack: function(stackKey) { return this.navigationManager.canBack(stackKey) }, _getPreviousViewInfo: function(navigateOptions) { var result, previousNavigationItem = this.navigationManager.previousItem(navigateOptions.stack); if (previousNavigationItem) { var routeData = this.router.parse(previousNavigationItem.uri); result = this.viewCache.getView(this._getViewInfoKey(previousNavigationItem, routeData)) } return result }, back: function(options) { this.navigationManager.back(options) }, saveState: function() { this.stateManager.saveState() }, restoreState: function() { this.stateManager.restoreState() }, clearState: function() { this.stateManager.clearState() } }).include(EventsMixin); exports.Application = Application }, /*!*******************************!*\ !*** ./js/framework/utils.js ***! \*******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), ko = __webpack_require__( /*! knockout */ 93), KoTemplate = __webpack_require__( /*! ../integration/knockout/template */ 105); var mergeWithReplace = function(targetArray, arrayToMerge, needReplaceFn) { var result = []; for (var i = 0, length = targetArray.length; i < length; i++) { if (!needReplaceFn(targetArray[i], arrayToMerge)) { result.push(targetArray[i]) } } result.push.apply(result, arrayToMerge); return result }; var prepareCommandToReplace = function(targetCommand, commandsToMerge) { var needToReplace = false; $.each(commandsToMerge, function(_, commandToMerge) { var idEqual = targetCommand.option("id") === commandToMerge.option("id") && commandToMerge.option("id"), behaviorEqual = targetCommand.option("behavior") === commandToMerge.option("behavior") && targetCommand.option("behavior"); needToReplace = idEqual || behaviorEqual; if (behaviorEqual && null === commandToMerge.option("onExecute")) { commandToMerge.option("onExecute", targetCommand.option("onExecute")) } if (needToReplace) { targetCommand.element().remove(); return false } }); return needToReplace }; var mergeCommands = function(targetCommands, commandsToMerge) { return mergeWithReplace(targetCommands, commandsToMerge, prepareCommandToReplace) }; var resolvePropertyValue = function(command, containerOptions, propertyName, defaultValue) { var containerOption = containerOptions ? containerOptions[propertyName] : void 0, defaultOption = void 0 === containerOption ? defaultValue : containerOption, commandOption = command.option(propertyName); return void 0 === commandOption || commandOption === defaultValue ? defaultOption : commandOption }; var resolveTextValue = function(command, containerOptions) { var showText = resolvePropertyValue(command, containerOptions, "showText"), hasIcon = !!command.option("icon"), titleValue = resolvePropertyValue(command, containerOptions, "title", ""); return showText || !hasIcon ? titleValue : "" }; var resolveIconValue = function(command, containerOptions) { var showIcon = resolvePropertyValue(command, containerOptions, "showIcon"), hasText = !!command.option("title"), iconValue = resolvePropertyValue(command, containerOptions, "icon", ""); return showIcon || !hasText ? iconValue : "" }; exports.utils = { mergeCommands: mergeCommands, commandToContainer: { resolveIconValue: resolveIconValue, resolveTextValue: resolveTextValue, resolvePropertyValue: resolvePropertyValue } }; exports.templateProvider = { createTemplate: function(element) { return new KoTemplate(element) }, applyTemplate: function(element, model) { ko.applyBindings(model, element) } } }, /*!******************************************!*\ !*** ./js/framework/action_executors.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), dataCoreUtils = __webpack_require__( /*! ../core/utils/data */ 50), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, isPlainObject = __webpack_require__( /*! ../core/utils/type */ 12).isPlainObject, Route = __webpack_require__( /*! ./router */ 123).Route; function prepareNavigateOptions(options, actionArguments) { if (actionArguments.args) { var sourceEventArguments = actionArguments.args[0]; options.jQueryEvent = sourceEventArguments.jQueryEvent } if ("dxCommand" === (actionArguments.component || {}).NAME) { extend(options, actionArguments.component.option()) } } function preventDefaultLinkBehavior(e) { if (!e) { return } var $targetElement = $(e.target); if ($targetElement.attr("href")) { e.preventDefault() } } var createActionExecutors = function(app) { return { routing: { execute: function(e) { var routeValues, uri, action = e.action, options = {}; if (isPlainObject(action)) { routeValues = action.routeValues; if (routeValues && isPlainObject(routeValues)) { options = action.options } else { routeValues = action } uri = app.router.format(routeValues); prepareNavigateOptions(options, e); preventDefaultLinkBehavior(options.jQueryEvent); app.navigate(uri, options); e.handled = true } } }, hash: { execute: function(e) { if ("string" !== typeof e.action || "#" !== e.action.charAt(0)) { return } var uriTemplate = e.action.substr(1), args = e.args[0], uri = uriTemplate; var defaultEvaluate = function(expr) { var getter = dataCoreUtils.compileGetter(expr), model = e.args[0].model; return getter(model) }; var evaluate = args.evaluate || defaultEvaluate; uri = uriTemplate.replace(/\{([^}]+)\}/g, function(entry, expr) { expr = $.trim(expr); if (expr.indexOf(",") > -1) { expr = $.map(expr.split(","), $.trim) } var value = evaluate(expr); if (void 0 === value) { value = "" } value = Route.prototype.formatSegment(value); return value }); var options = {}; prepareNavigateOptions(options, e); preventDefaultLinkBehavior(options.jQueryEvent); app.navigate(uri, options); e.handled = true } }, url: { execute: function(e) { if ("string" === typeof e.action && "#" !== e.action.charAt(0)) { document.location = e.action } } } } }; exports.createActionExecutors = createActionExecutors }, /*!********************************************!*\ !*** ./js/framework/navigation_manager.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), isPlainObject = __webpack_require__( /*! ../core/utils/type */ 12).isPlainObject, extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, navigationDevices = __webpack_require__( /*! ./navigation_devices */ 134), EventsMixin = __webpack_require__( /*! ../core/events_mixin */ 51), errors = __webpack_require__( /*! ./errors */ 122), hardwareBackButton = __webpack_require__( /*! ../mobile/process_hardware_back_button */ 64).processCallback, hideTopOverlay = __webpack_require__( /*! ../mobile/hide_top_overlay */ 65), when = __webpack_require__( /*! ../integration/jquery/deferred */ 16).when; var NAVIGATION_TARGETS = { current: "current", blank: "blank", back: "back" }, STORAGE_HISTORY_KEY = "__history"; var HistoryBasedNavigationManager = Class.inherit({ ctor: function(options) { options = options || {}; this._currentItem = void 0; this._previousItem = void 0; this._createNavigationDevice(options) }, _createNavigationDevice: function(options) { this._navigationDevice = options.navigationDevice || new navigationDevices.HistoryBasedNavigationDevice; this._navigationDevice.uriChanged.add(this._uriChangedHandler.bind(this)) }, _uriChangedHandler: function(uri) { while (hideTopOverlay()) {} this.navigate(uri) }, _syncUriWithCurrentNavigationItem: function() { var currentUri = this._currentItem && this._currentItem.uri; this._navigationDevice.setUri(currentUri, true) }, _cancelNavigation: function(args) { this._syncUriWithCurrentNavigationItem(); this.fireEvent("navigationCanceled", [args]) }, _getDefaultOptions: function() { return { direction: "none", target: NAVIGATION_TARGETS.blank } }, _updateHistory: function(uri, options) { this._previousItem = this._currentItem; this._currentItem = { uri: uri, key: uri }; this._navigationDevice.setUri(uri, options.target === NAVIGATION_TARGETS.current) }, _setCurrentItem: function(item) { this._currentItem = item }, navigate: function(uri, options) { options = options || {}; var args, that = this, isFirstNavigate = !that._currentItem, currentItem = that._currentItem || {}, targetItem = options.item || {}, currentUri = currentItem.uri, currentKey = currentItem.key, targetKey = targetItem.key; if (void 0 === uri) { uri = that._navigationDevice.getUri() } if (/^_back$/.test(uri)) { that.back(); return } options = extend(that._getDefaultOptions(), options || {}); if (isFirstNavigate) { options.target = NAVIGATION_TARGETS.current } args = { currentUri: currentUri, uri: uri, cancel: false, navigateWhen: [], options: options }; that.fireEvent("navigating", [args]); uri = args.uri; if (args.cancel || currentUri === uri && (void 0 === targetKey || targetKey === currentKey) && !that._forceNavigate) { that._cancelNavigation(args) } else { that._forceNavigate = false; when.apply($, args.navigateWhen).done(function() { commonUtils.executeAsync(function() { that._updateHistory(uri, options); that.fireEvent("navigated", [{ uri: uri, previousUri: currentUri, options: options, item: that._currentItem }]) }) }) } }, back: function() { return this._navigationDevice.back() }, previousItem: function() { return this._previousItem }, currentItem: function(item) { if (arguments.length > 0) { if (!item) { throw errors.Error("E3023") } this._setCurrentItem(item) } else { return this._currentItem } }, rootUri: function() { return this._currentItem && this._currentItem.uri }, canBack: function() { return true }, saveState: commonUtils.noop, restoreState: commonUtils.noop, removeState: commonUtils.noop }).include(EventsMixin); var StackBasedNavigationManager = HistoryBasedNavigationManager.inherit({ ctor: function(options) { options = options || {}; this.callBase(options); this._createNavigationStacks(options); hardwareBackButton.add(this._deviceBackInitiated.bind(this)); this._stateStorageKey = options.stateStorageKey || STORAGE_HISTORY_KEY }, init: function() { return this._navigationDevice.init() }, _createNavigationDevice: function(options) { if (!options.navigationDevice) { options.navigationDevice = new navigationDevices.StackBasedNavigationDevice } this.callBase(options); this._navigationDevice.backInitiated.add(this._deviceBackInitiated.bind(this)) }, _uriChangedHandler: function(uri) { this.navigate(uri) }, _createNavigationStacks: function(options) { this.navigationStacks = {}; this._keepPositionInStack = options.keepPositionInStack; this.currentStack = new NavigationStack }, _deviceBackInitiated: function() { if (!hideTopOverlay()) { this.back({ isHardwareButton: true }) } else { this._syncUriWithCurrentNavigationItem() } }, _getDefaultOptions: function() { return { target: NAVIGATION_TARGETS.blank } }, _createNavigationStack: function() { var result = new NavigationStack; result.itemsRemoved.add(this._removeItems.bind(this)); return result }, _setCurrentItem: function(item) { this._setCurrentStack(item.stack); this.currentStack.currentItem(item); this.callBase(item); this._syncUriWithCurrentNavigationItem() }, _setCurrentStack: function(stackOrStackKey) { var stack, stackKey; if ("string" === typeof stackOrStackKey) { stackKey = stackOrStackKey; if (!(stackKey in this.navigationStacks)) { this.navigationStacks[stackKey] = this._createNavigationStack() } stack = this.navigationStacks[stackKey] } else { stack = stackOrStackKey; stackKey = $.map(this.navigationStacks, function(stack, key) { if (stack === stackOrStackKey) { return key } return null })[0] } this.currentStack = stack; this.currentStackKey = stackKey }, _getViewTargetStackKey: function(uri, isRoot) { var result; if (isRoot) { if (void 0 !== this.navigationStacks[uri]) { result = uri } else { for (var stackKey in this.navigationStacks) { if (this.navigationStacks[stackKey].items[0].uri === uri) { result = stackKey; break } } result = result || uri } } else { result = this.currentStackKey || uri } return result }, _updateHistory: function(uri, options) { var isRoot = options.root, forceIsRoot = isRoot, forceToRoot = false, previousStack = this.currentStack, keepPositionInStack = void 0 !== options.keepPositionInStack ? options.keepPositionInStack : this._keepPositionInStack; options.stack = options.stack || this._getViewTargetStackKey(uri, isRoot); this._setCurrentStack(options.stack); if (isRoot || !this.currentStack.items.length) { forceToRoot = this.currentStack === previousStack; forceIsRoot = true } if (isRoot && this.currentStack.items.length) { if (!keepPositionInStack || forceToRoot) { this.currentStack.currentIndex = 0; if (this.currentItem().uri !== uri) { this.currentStack.navigate(uri, true) } } options.direction = options.direction || "none" } else { var prevIndex = this.currentStack.currentIndex, prevItem = this.currentItem() || {}; switch (options.target) { case NAVIGATION_TARGETS.blank: this.currentStack.navigate(uri); break; case NAVIGATION_TARGETS.current: this.currentStack.navigate(uri, true); break; case NAVIGATION_TARGETS.back: if (this.currentStack.currentIndex > 0) { this.currentStack.back(uri) } else { this.currentStack.navigate(uri, true) } break; default: throw errors.Error("E3006", options.target) } if (void 0 === options.direction) { var indexDelta = this.currentStack.currentIndex - prevIndex; if (indexDelta < 0) { options.direction = this.currentStack.currentItem().backDirection || "backward" } else { if (indexDelta > 0 && this.currentStack.currentIndex > 0) { options.direction = "forward" } else { options.direction = "none" } } } prevItem.backDirection = "forward" === options.direction ? "backward" : "none" } options.root = forceIsRoot; this._currentItem = this.currentStack.currentItem(); this._syncUriWithCurrentNavigationItem() }, _removeItems: function(items) { var that = this; $.each(items, function(index, item) { that.fireEvent("itemRemoved", [item]) }) }, back: function(options) { options = options || {}; var navigatingBackArgs = extend({ cancel: false }, options); this.fireEvent("navigatingBack", [navigatingBackArgs]); if (navigatingBackArgs.cancel) { this._syncUriWithCurrentNavigationItem(); return } var item = this.previousItem(navigatingBackArgs.stack); if (item) { this.navigate(item.uri, { stack: navigatingBackArgs.stack, target: NAVIGATION_TARGETS.back, item: item }) } else { this.callBase() } }, rootUri: function() { return this.currentStack.items.length ? this.currentStack.items[0].uri : this.callBase() }, canBack: function(stackKey) { var stack = stackKey ? this.navigationStacks[stackKey] : this.currentStack; return stack ? stack.canBack() : false }, saveState: function(storage) { if (this.currentStack.items.length) { var state = { navigationStacks: {}, currentStackKey: this.currentStackKey }; $.each(this.navigationStacks, function(stackKey, stack) { var stackState = {}; state.navigationStacks[stackKey] = stackState; stackState.currentIndex = stack.currentIndex; stackState.items = $.map(stack.items, function(item) { return { key: item.key, uri: item.uri } }) }); var json = JSON.stringify(state); storage.setItem(this._stateStorageKey, json) } else { this.removeState(storage) } }, restoreState: function(storage) { if (this.disableRestoreState) { return } var json = storage.getItem(this._stateStorageKey); if (json) { try { var that = this, state = JSON.parse(json); $.each(state.navigationStacks, function(stackKey, stackState) { var stack = that._createNavigationStack(); that.navigationStacks[stackKey] = stack; stack.currentIndex = stackState.currentIndex; stack.items = $.map(stackState.items, function(item) { item.stack = stack; return item }) }); this.currentStackKey = state.currentStackKey; this.currentStack = this.navigationStacks[this.currentStackKey]; this._currentItem = this.currentStack.currentItem(); this._navigationDevice.setUri(this.currentItem().uri); this._forceNavigate = true } catch (e) { this.removeState(storage); throw errors.Error("E3007") } } }, removeState: function(storage) { storage.removeItem(this._stateStorageKey) }, currentIndex: function() { return this.currentStack.currentIndex }, previousItem: function(stackKey) { var stack = this.navigationStacks[stackKey] || this.currentStack; return stack.previousItem() }, getItemByIndex: function(index) { return this.currentStack.items[index] }, clearHistory: function() { this._createNavigationStacks({ keepPositionInStack: this._keepPositionInStack }) }, itemByKey: function(itemKey) { var result; $.each(this.navigationStacks, function(stackKey, stack) { var item = stack.itemByKey(itemKey); if (item) { result = item; return false } }); return result }, currentItem: function(itemOrItemKey) { var item; if (arguments.length > 0) { if ("string" === typeof itemOrItemKey) { item = this.itemByKey(itemOrItemKey) } else { if (isPlainObject(itemOrItemKey)) { item = itemOrItemKey } } this.callBase(item) } else { return this.callBase() } } }); var NavigationStack = Class.inherit({ ctor: function(options) { options = options || {}; this.itemsRemoved = $.Callbacks(); this.clear() }, currentItem: function(item) { if (item) { for (var i = 0; i < this.items.length; i++) { if (item === this.items[i]) { this.currentIndex = i; break } } } else { return this.items[this.currentIndex] } }, previousItem: function() { return this.items.length > 1 ? this.items[this.currentIndex - 1] : void 0 }, canBack: function() { return this.currentIndex > 0 }, clear: function() { this._deleteItems(this.items); this.items = []; this.currentIndex = -1 }, back: function(uri) { this.currentIndex--; if (this.currentIndex < 0) { throw errors.Error("E3008") } var currentItem = this.currentItem(); if (currentItem.uri !== uri) { this._updateItem(this.currentIndex, uri) } }, forward: function() { this.currentIndex++; if (this.currentIndex >= this.items.length) { throw errors.Error("E3009") } }, navigate: function(uri, replaceCurrent) { if (this.currentIndex < this.items.length && this.currentIndex > -1 && this.items[this.currentIndex].uri === uri) { return } if (replaceCurrent && this.currentIndex > -1) { this.currentIndex-- } if (this.currentIndex + 1 < this.items.length && this.items[this.currentIndex + 1].uri === uri) { this.currentIndex++ } else { var toDelete = this.items.splice(this.currentIndex + 1, this.items.length - this.currentIndex - 1); this.items.push({ stack: this }); this.currentIndex++; this._updateItem(this.currentIndex, uri); this._deleteItems(toDelete) } return this.currentItem() }, itemByKey: function(key) { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item.key === key) { return item } } }, _updateItem: function(index, uri) { var item = this.items[index]; item.uri = uri; item.key = this.items[0].uri + "_" + index + "_" + uri }, _deleteItems: function(items) { if (items) { this.itemsRemoved.fire(items) } } }); HistoryBasedNavigationManager.NAVIGATION_TARGETS = NAVIGATION_TARGETS; exports.HistoryBasedNavigationManager = HistoryBasedNavigationManager; exports.StackBasedNavigationManager = StackBasedNavigationManager; exports.NavigationStack = NavigationStack }, /*!********************************************!*\ !*** ./js/framework/navigation_devices.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), noop = __webpack_require__( /*! ../core/utils/common */ 14).noop, Class = __webpack_require__( /*! ../core/class */ 25), browserAdapters = __webpack_require__( /*! ./browser_adapters */ 135), SessionStorage = __webpack_require__( /*! ../core/utils/storage */ 54).sessionStorage, devices = __webpack_require__( /*! ../core/devices */ 53); var SESSION_KEY = "dxPhoneJSApplication"; var HistoryBasedNavigationDevice = Class.inherit({ ctor: function(options) { options = options || {}; this._browserAdapter = options.browserAdapter || this._createBrowserAdapter(options); this.uriChanged = $.Callbacks(); this._browserAdapter.popState.add(this._onPopState.bind(this)) }, init: noop, getUri: function() { return this._browserAdapter.getHash() }, setUri: function(uri, replaceCurrent) { if (replaceCurrent) { return this._browserAdapter.replaceState(uri) } else { if (uri !== this.getUri()) { return this._browserAdapter.pushState(uri) } else { return $.Deferred().resolve().promise() } } }, back: function() { return this._browserAdapter.back() }, _onPopState: function() { this.uriChanged.fire(this.getUri()) }, _isBuggyAndroid2: function() { var realDevice = devices.real(); var version = realDevice.version; return "android" === realDevice.platform && version.length > 1 && (2 === version[0] && version[1] < 4 || version[0] < 2) }, _isBuggyAndroid4: function() { var realDevice = devices.real(); var version = realDevice.version; return "android" === realDevice.platform && version.length > 1 && 4 === version[0] && 0 === version[1] }, _isWindowsPhone8: function() { var realDevice = devices.real(); return "win" === realDevice.platform && realDevice.phone }, _createBrowserAdapter: function(options) { var result, sourceWindow = options.window || window, supportPushReplace = sourceWindow.history.replaceState && sourceWindow.history.pushState; if (this._isWindowsPhone8()) { result = new browserAdapters.BuggyCordovaWP81BrowserAdapter(options) } else { if (sourceWindow !== sourceWindow.top) { result = new browserAdapters.HistorylessBrowserAdapter(options) } else { if (this._isBuggyAndroid4()) { result = new browserAdapters.BuggyAndroidBrowserAdapter(options) } else { if (this._isBuggyAndroid2() || !supportPushReplace) { result = new browserAdapters.OldBrowserAdapter(options) } else { result = new browserAdapters.DefaultBrowserAdapter(options) } } } } return result } }); var StackBasedNavigationDevice = HistoryBasedNavigationDevice.inherit({ ctor: function(options) { this.callBase(options); this.backInitiated = $.Callbacks(); this._rootStateHandler = null; $(window).on("unload", this._saveBrowserState) }, init: function() { var that = this; if (that._browserAdapter.canWorkInPureBrowser) { return that._initRootPage().done(function() { if (that._browserAdapter.isRootPage()) { that._browserAdapter.pushState("") } }) } else { return $.Deferred().resolve().promise() } }, setUri: function(uri) { return this.callBase(uri, !this._browserAdapter.isRootPage()) }, _saveBrowserState: function() { var sessionStorage = SessionStorage(); if (sessionStorage) { sessionStorage.setItem(SESSION_KEY, true) } }, _initRootPage: function() { var hash = this.getUri(), sessionStorage = SessionStorage(); if (!sessionStorage || sessionStorage.getItem(SESSION_KEY)) { return $.Deferred().resolve().promise() } sessionStorage.removeItem(SESSION_KEY); this._browserAdapter.createRootPage(); return this._browserAdapter.pushState(hash) }, _onPopState: function() { if (this._browserAdapter.isRootPage()) { if (this._rootStateHandler) { this._rootStateHandler() } else { this.backInitiated.fire() } } else { if (!this._rootStateHandler) { this._createRootStateHandler() } this.back() } }, _createRootStateHandler: function() { var uri = this.getUri(); this._rootStateHandler = function() { this.uriChanged.fire(uri); this._rootStateHandler = null } } }); exports.HistoryBasedNavigationDevice = HistoryBasedNavigationDevice; exports.StackBasedNavigationDevice = StackBasedNavigationDevice }, /*!******************************************!*\ !*** ./js/framework/browser_adapters.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), queue = __webpack_require__( /*! ../core/utils/queue */ 62); var ROOT_PAGE_URL = "__root__", BUGGY_ANDROID_BUFFER_PAGE_URL = "__buffer__"; var DefaultBrowserAdapter = Class.inherit({ ctor: function(options) { options = options || {}; this._window = options.window || window; this.popState = $.Callbacks(); $(this._window).on("hashchange", this._onHashChange.bind(this)); this._tasks = queue.create(); this.canWorkInPureBrowser = true }, replaceState: function(uri) { var that = this; return this._addTask(function() { uri = that._normalizeUri(uri); that._window.history.replaceState(null, null, "#" + uri); that._currentTask.resolve() }) }, pushState: function(uri) { var that = this; return this._addTask(function() { uri = that._normalizeUri(uri); that._window.history.pushState(null, null, "#" + uri); that._currentTask.resolve() }) }, createRootPage: function() { return this.replaceState(ROOT_PAGE_URL) }, _onHashChange: function() { if (this._currentTask) { this._currentTask.resolve() } this.popState.fire() }, back: function() { var that = this; return this._addTask(function() { that._window.history.back() }) }, getHash: function() { return this._normalizeUri(this._window.location.hash) }, isRootPage: function() { return this.getHash() === ROOT_PAGE_URL }, _normalizeUri: function(uri) { return (uri || "").replace(/^#+/, "") }, _addTask: function(task) { var that = this, d = $.Deferred(); this._tasks.add(function() { that._currentTask = d; task(); return d }); return d.promise() } }); var OldBrowserAdapter = DefaultBrowserAdapter.inherit({ ctor: function() { this._innerEventCount = 0; this.callBase.apply(this, arguments); this._skipNextEvent = false }, replaceState: function(uri) { var that = this; uri = that._normalizeUri(uri); if (that.getHash() !== uri) { that._addTask(function() { that._skipNextEvent = true; that._window.history.back() }); return that._addTask(function() { that._skipNextEvent = true; that._window.location.hash = uri }) } return $.Deferred().resolve().promise() }, pushState: function(uri) { var that = this; uri = this._normalizeUri(uri); if (this.getHash() !== uri) { return that._addTask(function() { that._skipNextEvent = true; that._window.location.hash = uri }) } return $.Deferred().resolve().promise() }, createRootPage: function() { return this.pushState(ROOT_PAGE_URL) }, _onHashChange: function() { var currentTask = this._currentTask; this._currentTask = null; if (this._skipNextEvent) { this._skipNextEvent = false } else { this.popState.fire() } if (currentTask) { currentTask.resolve() } } }); var BuggyAndroidBrowserAdapter = OldBrowserAdapter.inherit({ createRootPage: function() { this.pushState(BUGGY_ANDROID_BUFFER_PAGE_URL); return this.callBase() } }); var HistorylessBrowserAdapter = DefaultBrowserAdapter.inherit({ ctor: function(options) { options = options || {}; this._window = options.window || window; this.popState = $.Callbacks(); $(this._window).on("dxback", this._onHashChange.bind(this)); this._currentHash = this._window.location.hash }, replaceState: function(uri) { this._currentHash = this._normalizeUri(uri); return $.Deferred().resolve().promise() }, pushState: function(uri) { return this.replaceState(uri) }, createRootPage: function() { return this.replaceState(ROOT_PAGE_URL) }, getHash: function() { return this._normalizeUri(this._currentHash) }, back: function() { return this.replaceState(ROOT_PAGE_URL) }, _onHashChange: function() { var promise = this.back(); this.popState.fire(); return promise } }); var BuggyCordovaWP81BrowserAdapter = DefaultBrowserAdapter.inherit({ ctor: function(options) { this.callBase(options); this.canWorkInPureBrowser = false } }); exports.DefaultBrowserAdapter = DefaultBrowserAdapter; exports.OldBrowserAdapter = OldBrowserAdapter; exports.BuggyAndroidBrowserAdapter = BuggyAndroidBrowserAdapter; exports.HistorylessBrowserAdapter = HistorylessBrowserAdapter; exports.BuggyCordovaWP81BrowserAdapter = BuggyCordovaWP81BrowserAdapter }, /*!*****************************************!*\ !*** ./js/framework/command_mapping.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), grep = __webpack_require__( /*! ../core/utils/common */ 14).grep, extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, errors = __webpack_require__( /*! ./errors */ 122); var CommandMapping = Class.inherit({ ctor: function() { this._commandMappings = {}; this._containerDefaults = {} }, setDefaults: function(containerId, defaults) { this._containerDefaults[containerId] = defaults; return this }, mapCommands: function(containerId, commandMappings) { var that = this; $.each(commandMappings, function(index, commandMapping) { if ("string" === typeof commandMapping) { commandMapping = { id: commandMapping } } var commandId = commandMapping.id; var mappings = that._commandMappings[containerId] || {}; mappings[commandId] = extend({ showIcon: true, showText: true }, that._containerDefaults[containerId] || {}, commandMapping); that._commandMappings[containerId] = mappings }); this._initExistingCommands(); return this }, unmapCommands: function(containerId, commandIds) { var that = this; $.each(commandIds, function(index, commandId) { var mappings = that._commandMappings[containerId] || {}; if (mappings) { delete mappings[commandId] } }); this._initExistingCommands() }, getCommandMappingForContainer: function(commandId, containerId) { return (this._commandMappings[containerId] || {})[commandId] }, checkCommandsExist: function(commands) { var that = this, result = grep(commands, function(commandName, index) { return inArray(commandName, that._existingCommands) < 0 && inArray(commandName, commands) === index }); if (0 !== result.length) { throw errors.Error("E3005", result.join("', '"), 1 === result.length ? " is" : "s are") } }, load: function(config) { if (!config) { return } var that = this; $.each(config, function(name, container) { that.setDefaults(name, container.defaults); that.mapCommands(name, container.commands) }); return this }, _initExistingCommands: function() { var that = this; this._existingCommands = []; $.each(that._commandMappings, function(name, _commands) { $.each(_commands, function(index, command) { if (inArray(command.id, that._existingCommands) < 0) { that._existingCommands.push(command.id) } }) }) } }); CommandMapping.defaultMapping = { "global-navigation": { defaults: { showIcon: true, showText: true }, commands: [] }, "ios-header-toolbar": { defaults: { showIcon: false, showText: true, location: "after" }, commands: ["edit", "save", { id: "back", location: "before" }, { id: "cancel", location: "before" }, { id: "create", showIcon: true, showText: false }] }, "ios-action-sheet": { defaults: { showIcon: false, showText: true }, commands: [] }, "ios-view-footer": { defaults: { showIcon: false, showText: true }, commands: [{ id: "delete", type: "danger" }] }, "android-header-toolbar": { defaults: { showIcon: true, showText: false, location: "after" }, commands: [{ id: "back", showIcon: false, location: "before" }, "create", { id: "save", showText: true, showIcon: false, location: "after" }, { id: "edit", showText: false, location: "after" }, { id: "cancel", showText: false, location: "before" }, { id: "delete", showText: false, location: "after" }] }, "android-simple-toolbar": { defaults: { showIcon: true, showText: false, location: "after" }, commands: [{ id: "back", showIcon: false, location: "before" }, { id: "create" }, { id: "save", showText: true, showIcon: false, location: "after" }, { id: "edit", showText: false, location: "after" }, { id: "cancel", showText: false, location: "before" }, { id: "delete", showText: false, location: "after" }] }, "android-footer-toolbar": { defaults: { location: "after" }, commands: [{ id: "create", showText: false, location: "center" }, { id: "edit", showText: false, location: "before" }, { id: "delete", locateInMenu: "always" }, { id: "save", showIcon: false, location: "before" }] }, "generic-header-toolbar": { defaults: { showIcon: false, showText: true, location: "after" }, commands: ["edit", "save", { id: "back", location: "before" }, { id: "cancel", location: "before" }, { id: "create", showIcon: true, showText: false }] }, "generic-view-footer": { defaults: { showIcon: false, showText: true }, commands: [{ id: "delete", type: "danger" }] }, "win8-appbar": { defaults: { location: "after" }, commands: ["edit", "cancel", "save", "delete", { id: "create", location: "before" }, { id: "refresh", location: "before" }] }, "win8-toolbar": { defaults: { showText: false, location: "before" }, commands: [{ id: "previousPage" }] }, "win8-phone-appbar": { defaults: { location: "center" }, commands: ["create", "edit", "cancel", "save", "refresh", { id: "delete", locateInMenu: "always" }] }, "win8-split-toolbar": { defaults: { showIcon: true, showText: false, location: "after" }, commands: [{ id: "back", showIcon: false, location: "before" }, { id: "create" }, { id: "save", showText: true, location: "before" }, { id: "edit", showText: true, locateInMenu: "always" }, { id: "cancel", showText: true, locateInMenu: "always" }, { id: "delete", showText: true, locateInMenu: "always" }] }, "win8-master-detail-toolbar": { defaults: { showText: false, location: "before" }, commands: ["back"] }, "win10-appbar": { defaults: { showText: false, location: "after" }, commands: [{ id: "back", location: "before" }, "edit", "cancel", "save", "delete", "create", "refresh"] }, "win10-phone-appbar": { defaults: { location: "after" }, commands: ["create", "edit", "cancel", "save", "refresh", { id: "delete", locateInMenu: "always" }] }, "desktop-toolbar": { defaults: { showIcon: false, showText: true, location: "after" }, commands: ["cancel", "create", "edit", "save", { id: "delete", type: "danger" }] } }; module.exports = CommandMapping }, /*!**************************!*\ !*** ./js/data/utils.js ***! \**************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), isFunction = __webpack_require__( /*! ../core/utils/common */ 14).isFunction, toComparable = __webpack_require__( /*! ../core/utils/data */ 50).toComparable; var normalizeBinaryCriterion = function(crit) { return [crit[0], crit.length < 3 ? "=" : String(crit[1]).toLowerCase(), crit.length < 2 ? true : crit[crit.length - 1]] }; var normalizeSortingInfo = function(info) { if (!Array.isArray(info)) { info = [info] } return $.map(info, function(i) { return { selector: isFunction(i) || "string" === typeof i ? i : i.getter || i.field || i.selector, desc: !!(i.desc || "d" === String(i.dir).charAt(0).toLowerCase()) } }) }; var errorMessageFromXhr = function() { var textStatusMessages = { timeout: "Network connection timeout", error: "Unspecified network error", parsererror: "Unexpected server response" }; var textStatusDetails = { timeout: "possible causes: the remote host is not accessible, overloaded or is not included into the domain white-list when being run in the native container", error: "if the remote host is located on another domain, make sure it properly supports cross-origin resource sharing (CORS), or use the JSONP approach instead", parsererror: "the remote host did not respond with valid JSON data" }; var explainTextStatus = function(textStatus) { var result = textStatusMessages[textStatus]; if (!result) { return textStatus } result += " (" + textStatusDetails[textStatus] + ")"; return result }; return function(xhr, textStatus) { if (xhr.status < 400) { return explainTextStatus(textStatus) } return xhr.statusText } }(); var aggregators = { count: { seed: 0, step: function(count) { return 1 + count } }, sum: { seed: 0, step: function(sum, item) { return sum + item } }, min: { step: function(min, item) { return item < min ? item : min } }, max: { step: function(max, item) { return item > max ? item : max } }, avg: { seed: [0, 0], step: function(pair, value) { return [pair[0] + value, pair[1] + 1] }, finalize: function(pair) { return pair[1] ? pair[0] / pair[1] : NaN } } }; var processRequestResultLock = function() { var lockDeferred, lockCount = 0; var obtain = function() { if (0 === lockCount) { lockDeferred = $.Deferred() } lockCount++ }; var release = function() { lockCount--; if (lockCount < 1) { lockDeferred.resolve() } }; var promise = function() { var deferred = 0 === lockCount ? $.Deferred().resolve() : lockDeferred; return deferred.promise() }; var reset = function() { lockCount = 0; if (lockDeferred) { lockDeferred.resolve() } }; return { obtain: obtain, release: release, promise: promise, reset: reset } }(); function isDisjunctiveOperator(condition) { return /^(or|\|\||\|)$/i.test(condition) } function isConjunctiveOperator(condition) { return /^(and|\&\&|\&)$/i.test(condition) } var keysEqual = function(keyExpr, key1, key2) { if (Array.isArray(keyExpr)) { var name, names = $.map(key1, function(v, k) { return k }); for (var i = 0; i < names.length; i++) { name = names[i]; if (toComparable(key1[name], true) != toComparable(key2[name], true)) { return false } } return true } return toComparable(key1, true) == toComparable(key2, true) }; var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var base64_encode = function(input) { if (!Array.isArray(input)) { input = stringToByteArray(String(input)) } var result = ""; function getBase64Char(index) { return BASE64_CHARS.charAt(index) } for (var i = 0; i < input.length; i += 3) { var octet1 = input[i], octet2 = input[i + 1], octet3 = input[i + 2]; result += $.map([octet1 >> 2, (3 & octet1) << 4 | octet2 >> 4, isNaN(octet2) ? 64 : (15 & octet2) << 2 | octet3 >> 6, isNaN(octet3) ? 64 : 63 & octet3], getBase64Char).join("") } return result }; var stringToByteArray = function(str) { var code, i, bytes = []; for (i = 0; i < str.length; i++) { code = str.charCodeAt(i); if (code < 128) { bytes.push(code) } else { if (code < 2048) { bytes.push(192 + (code >> 6), 128 + (63 & code)) } else { if (code < 65536) { bytes.push(224 + (code >> 12), 128 + (code >> 6 & 63), 128 + (63 & code)) } else { if (code < 2097152) { bytes.push(240 + (code >> 18), 128 + (code >> 12 & 63), 128 + (code >> 6 & 63), 128 + (63 & code)) } } } } } return bytes }; var isUnaryOperation = function(crit) { return "!" === crit[0] && Array.isArray(crit[1]) }; var utils = { normalizeBinaryCriterion: normalizeBinaryCriterion, normalizeSortingInfo: normalizeSortingInfo, errorMessageFromXhr: errorMessageFromXhr, aggregators: aggregators, keysEqual: keysEqual, isDisjunctiveOperator: isDisjunctiveOperator, isConjunctiveOperator: isConjunctiveOperator, processRequestResultLock: processRequestResultLock, isUnaryOperation: isUnaryOperation, base64_encode: base64_encode }; module.exports = utils }, /*!**************************************!*\ !*** ./js/framework/html/presets.js ***! \**************************************/ function(module, exports) { exports.layoutSets = {}; exports.animationSets = { "native": { "view-content-change": [{ animation: "slide" }, { animation: "ios7-slide", device: { platform: "ios" } }, { animation: "none", device: { deviceType: "desktop", platform: "generic" } }, { animation: "none", device: { grade: "C" } }], "view-header-toolbar": [{ animation: "ios7-toolbar" }, { animation: "slide", device: { grade: "B" } }, { animation: "none", device: { grade: "C" } }] }, "default": { "layout-change": [{ animation: "none" }, { animation: "ios7-slide", device: { platform: "ios" } }, { animation: "pop", device: { platform: "android" } }, { animation: "openDoor", device: { deviceType: "phone", platform: "win", version: [8] } }, { animation: "win-pop", device: { deviceType: "phone", platform: "win" } }], "view-content-change": [{ animation: "slide" }, { animation: "ios7-slide", device: { platform: "ios" } }, { animation: "fade", device: { deviceType: "desktop", platform: "generic" } }, { animation: "none", device: { grade: "C" } }], "view-content-rendered": [{ animation: "fade" }, { animation: "none", device: { grade: "C" } }], "view-header-toolbar": [{ animation: "ios7-toolbar" }, { animation: "slide", device: { grade: "B" } }, { animation: "none", device: { grade: "C" } }], "command-rendered-top": [{ animation: "stagger-fade-drop" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }, { animation: "none", device: { platform: "win", version: [10] } }], "command-rendered-bottom": [{ animation: "stagger-fade-rise" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }, { animation: "none", device: { platform: "win", version: [10] } }], "list-item-rendered": [{ animation: "stagger-3d-drop", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "detail-item-rendered": [{ animation: "stagger-3d-drop", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "edit-item-rendered": [{ animation: "stagger-3d-drop", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }] }, slide: { "view-content-change": [{ animation: "slide" }, { animation: "ios7-slide", device: { platform: "ios" } }, { animation: "fade", device: { deviceType: "desktop", platform: "generic" } }, { animation: "none", device: { grade: "C" } }], "view-content-rendered": [{ animation: "fade" }, { animation: "none", device: { grade: "C" } }], "view-header-toolbar": [{ animation: "ios7-toolbar" }, { animation: "slide", device: { grade: "B" } }, { animation: "none", device: { grade: "C" } }], "command-rendered-top": [{ animation: "stagger-fade-drop" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "command-rendered-bottom": [{ animation: "stagger-fade-rise" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "list-item-rendered": [{ animation: "stagger-fade-slide", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "detail-item-rendered": [{ animation: "stagger-fade-slide", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "edit-item-rendered": [{ animation: "stagger-fade-slide", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }] }, zoom: { "view-content-change": [{ animation: "slide" }, { animation: "ios7-slide", device: { platform: "ios" } }, { animation: "fade", device: { deviceType: "desktop", platform: "generic" } }, { animation: "none", device: { grade: "C" } }], "view-content-rendered": [{ animation: "fade" }, { animation: "none", device: { grade: "C" } }], "view-header-toolbar": [{ animation: "ios7-toolbar" }, { animation: "slide", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "command-rendered-top": [{ animation: "stagger-fade-zoom" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "command-rendered-bottom": [{ animation: "stagger-fade-zoom" }, { animation: "fade", device: { grade: "B" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "list-item-rendered": [{ animation: "stagger-fade-zoom", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "detail-item-rendered": [{ animation: "stagger-fade-zoom", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }], "edit-item-rendered": [{ animation: "stagger-fade-zoom", device: { grade: "A" } }, { animation: "fade", device: { deviceType: "desktop" } }, { animation: "none", device: { grade: "C" } }] } } }, /*!**********************************************!*\ !*** ./js/framework/html/command_manager.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, errors = __webpack_require__( /*! ../errors */ 122), CommandMapping = __webpack_require__( /*! ../command_mapping */ 136), commandToDXWidgetAdapters = __webpack_require__( /*! ./widget_command_adapters */ 140), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; __webpack_require__( /*! ../command */ 121); __webpack_require__( /*! ./command_container */ 126); var CommandManager = Class.inherit({ ctor: function(options) { options = options || {}; this.defaultWidgetAdapter = options.defaultWidgetAdapter || this._getDefaultWidgetAdapter(); this.commandMapping = options.commandMapping || new CommandMapping }, _getDefaultWidgetAdapter: function() { return { addCommand: noop, clearContainer: noop } }, _getContainerAdapter: function($container) { var componentNames = $container.data("dxComponents"), adapters = commandToDXWidgetAdapters; if (componentNames) { for (var index in componentNames) { var widgetName = componentNames[index]; if (widgetName in adapters) { return adapters[widgetName] } } } return this.defaultWidgetAdapter }, findCommands: function($items) { var items = $items.find(".dx-command").add($items.filter(".dx-command")); var result = $.map(items, function(element) { return $(element).dxCommand("instance") }); return result }, findCommandContainers: function($markup) { var result = $.map($markup.find(".dx-command-container"), function(element) { return $(element).dxCommandContainer("instance") }); return result }, _checkCommandId: function(id, command) { if (null === id) { throw errors.Error("E3010", command.element().get(0).outerHTML) } }, renderCommandsToContainers: function(commands, containers) { var that = this, commandHash = {}, commandIds = [], deferreds = []; $.each(commands, function(i, command) { var id = command.option("id"); that._checkCommandId(id, command); commandIds.push(id); commandHash[id] = command }); that.commandMapping.checkCommandsExist(commandIds); $.each(containers, function(k, container) { var commandInfos = []; $.each(commandHash, function(id, command) { var commandId = id; var commandOptions = that.commandMapping.getCommandMappingForContainer(commandId, container.option("id")); if (commandOptions) { commandInfos.push({ command: command, options: commandOptions }) } }); if (commandInfos.length) { var deferred = that._attachCommandsToContainer(container.element(), commandInfos); if (deferred) { deferreds.push(deferred) } } }); return when.apply($, deferreds) }, clearContainer: function(container) { var $container = container.element(), adapter = this._getContainerAdapter($container); adapter.clearContainer($container) }, _arrangeCommandsToContainers: function(commands, containers) { errors.log("W0002", "CommandManager", "_arrangeCommandsToContainers", "14.1", "Use the 'renderCommandsToContainers' method instead."); this.renderCommandsToContainers(commands, containers) }, _attachCommandsToContainer: function($container, commandInfos) { var result, adapter = this._getContainerAdapter($container); if (adapter.beginUpdate) { adapter.beginUpdate($container) } $.each(commandInfos, function(index, commandInfo) { adapter.addCommand($container, commandInfo.command, commandInfo.options) }); if (adapter.endUpdate) { result = adapter.endUpdate($container) } return result } }); module.exports = CommandManager }, /*!******************************************************!*\ !*** ./js/framework/html/widget_command_adapters.js ***! \******************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, commandToContainer = __webpack_require__( /*! ../utils */ 131).utils.commandToContainer, fx = __webpack_require__( /*! ../../animation/fx */ 68), TransitionExecutorModule = __webpack_require__( /*! ../../animation/transition_executor/transition_executor */ 74), DX_COMMAND_TO_WIDGET_ADAPTER = "dxCommandToWidgetAdapter"; var WidgetItemWrapperBase = Class.inherit({ ctor: function(command, containerOptions) { this.command = command; this.widgetItem = this._createWidgetItem(command, containerOptions) }, _createWidgetItem: function(command, containerOptions) { var result, itemOptions = extend({}, containerOptions, command.option()), executeCommandCallback = function(e) { command.execute(e) }; itemOptions.text = commandToContainer.resolveTextValue(command, containerOptions); itemOptions.icon = commandToContainer.resolveIconValue(command, containerOptions); itemOptions.type = commandToContainer.resolvePropertyValue(command, containerOptions, "type"); itemOptions.location = commandToContainer.resolvePropertyValue(command, containerOptions, "location"); itemOptions.locateInMenu = commandToContainer.resolvePropertyValue(command, containerOptions, "locateInMenu"); itemOptions.showText = commandToContainer.resolvePropertyValue(command, containerOptions, "showText"); result = this._createWidgetItemCore(itemOptions, executeCommandCallback); result.command = command; return result }, _createWidgetItemCore: function(itemOptions, executeCommandCallback) { return itemOptions }, dispose: function() { delete this.command; delete this.widgetItem } }); var WidgetAdapterBase = Class.inherit({ ctor: function($widgetElement) { this._commandToWidgetItemOptionNames = {}; this.$widgetElement = $widgetElement; this.$widgetElement.data(DX_COMMAND_TO_WIDGET_ADAPTER, this); this.widget = this._getWidgetByElement($widgetElement); this._widgetWidgetContentReadyHandler = this._onWidgetContentReady.bind(this); this._widgetWidgetItemRenderedHandler = this._onWidgetItemRendered.bind(this); this._widgetDisposingHandler = this._onWidgetDisposing.bind(this); this.widget.on("itemRendered", this._widgetWidgetItemRenderedHandler); this.widget.on("contentReady", this._widgetWidgetContentReadyHandler); this.widget.on("disposing", this._widgetDisposingHandler); this.itemWrappers = []; this._transitionExecutor = new TransitionExecutorModule.TransitionExecutor }, addCommand: function(command, containerOptions) { var itemWrapper = this._createItemWrapper(command, containerOptions); this.itemWrappers.push(itemWrapper); this._addItemToWidget(itemWrapper); this._commandChangedHandler = this._onCommandChanged.bind(this); itemWrapper.command.on("optionChanged", this._commandChangedHandler) }, beginUpdate: function() { this.widget.beginUpdate() }, endUpdate: function() { this.widget.endUpdate(); return this.animationDeferred }, _onWidgetItemRendered: function(e) { if (e.itemData.isJustAdded && e.itemData.command && e.itemData.command.option("visible") && this._commandRenderedAnimation) { this._transitionExecutor.enter(e.itemElement, this._commandRenderedAnimation); delete e.itemData.isJustAdded } }, _onWidgetContentReady: function(e) { this.animationDeferred = this._transitionExecutor.start() }, _onWidgetDisposing: function() { this.dispose(true) }, _setWidgetItemOption: function(optionName, optionValue, itemCommand) { var items = this.widget.option("items"), itemIndex = inArray(itemCommand, $.map(items, function(item) { return item.command || {} })); if (itemIndex > -1) { var optionPath = "items[" + itemIndex + "]."; if (!this._requireWidgetRefresh(optionName) && this.widget.option("items[" + itemIndex + "]").options) { optionPath += "options." } optionPath += this._commandToWidgetItemOptionNames[optionName] || optionName; this.widget.option(optionPath, optionValue) } }, _requireWidgetRefresh: function(optionName) { return "visible" === optionName || "locateInMenu" === optionName || "location" === optionName }, _onCommandChanged: function(args) { if ("highlighted" === args.name || args.component.isOptionDeprecated(args.name)) { return } this._setWidgetItemOption(args.name, args.value, args.component) }, _addItemToWidget: function(itemWrapper) { var items = this.widget.option("items"); items.push(itemWrapper.widgetItem); if (this.widget.element().is(":visible")) { itemWrapper.widgetItem.isJustAdded = true } this.widget.option("items", items) }, refresh: function() { var items = this.widget.option("items"); this.widget.option("items", items) }, clear: function(widgetDisposing) { var that = this; $.each(that.itemWrappers, function(index, itemWrapper) { itemWrapper.command.off("optionChanged", that._commandChangedHandler); itemWrapper.dispose() }); this.itemWrappers.length = 0; if (!widgetDisposing) { this._clearWidgetItems() } }, _clearWidgetItems: function() { this.widget.option("items", []) }, dispose: function(widgetDisposing) { this.clear(widgetDisposing); if (this.widget) { this.widget.off("itemRendered", this._widgetWidgetItemRenderedHandler); this.widget.off("contentReady", this._widgetContentReadyHandler); this.widget.off("disposing", this._widgetDisposingHandler); this.$widgetElement.removeData(DX_COMMAND_TO_WIDGET_ADAPTER); delete this.widget; delete this.$widgetElement } } }); var CommandToWidgetAdapter = Class.inherit({ ctor: function(createAdapter) { this.createAdapter = createAdapter }, _getWidgetAdapter: function($container) { var widgetAdapter = $container.data(DX_COMMAND_TO_WIDGET_ADAPTER); if (!widgetAdapter) { widgetAdapter = this.createAdapter($container) } return widgetAdapter }, addCommand: function($container, command, containerOptions) { var widgetAdapter = this._getWidgetAdapter($container); widgetAdapter.addCommand(command, containerOptions) }, clearContainer: function($container) { var widgetAdapter = this._getWidgetAdapter($container); widgetAdapter.clear() }, beginUpdate: function($container) { var widgetAdapter = this._getWidgetAdapter($container); widgetAdapter.beginUpdate() }, endUpdate: function($container) { var widgetAdapter = this._getWidgetAdapter($container); return widgetAdapter.endUpdate() } }); var dxToolbarItemWrapper = WidgetItemWrapperBase.inherit({ _createWidgetItemCore: function(itemOptions, executeCommandCallback) { var widgetItem; itemOptions.onClick = executeCommandCallback; if ("menu" === itemOptions.location || "always" === itemOptions.locateInMenu) { widgetItem = itemOptions; widgetItem.isAction = true } else { widgetItem = { locateInMenu: itemOptions.locateInMenu, location: itemOptions.location, visible: itemOptions.visible, options: itemOptions, widget: "dxButton" }; if ("inMenu" === itemOptions.showText) { widgetItem.showText = itemOptions.showText } itemOptions.visible = true; delete itemOptions.location } return widgetItem } }); var dxToolbarAdapter = WidgetAdapterBase.inherit({ ctor: function($widgetElement) { this.callBase($widgetElement); this._commandToWidgetItemOptionNames = { title: "text" }; if ("topToolbar" === this.widget.option("renderAs")) { this._commandRenderedAnimation = "command-rendered-top" } else { this._commandRenderedAnimation = "command-rendered-bottom" } }, _getWidgetByElement: function($element) { return $element.dxToolbar("instance") }, _createItemWrapper: function(command, containerOptions) { return new dxToolbarItemWrapper(command, containerOptions) }, addCommand: function(command, containerOptions) { this.widget.option("visible", true); this.callBase(command, containerOptions) } }); var dxListItemWrapper = WidgetItemWrapperBase.inherit({ _createWidgetItemCore: function(itemOptions, executeCommandCallback) { itemOptions.title = itemOptions.text; itemOptions.onClick = executeCommandCallback; return itemOptions } }); var dxListAdapter = WidgetAdapterBase.inherit({ _createItemWrapper: function(command, containerOptions) { return new dxListItemWrapper(command, containerOptions) }, _getWidgetByElement: function($element) { return $element.dxList("instance") } }); var dxNavBarItemWrapper = WidgetItemWrapperBase.inherit({}); var dxNavBarAdapter = WidgetAdapterBase.inherit({ ctor: function($widgetElement) { this.callBase($widgetElement); this._commandToWidgetItemOptionNames = { title: "text" }; this.widget.option("onItemClick", this._onNavBarItemClick.bind(this)) }, _onNavBarItemClick: function(e) { var items = this.widget.option("items"); for (var i = items.length; --i;) { items[i].command.option("highlighted", false) } e.itemData.command.execute(e) }, _getWidgetByElement: function($element) { return $element.dxNavBar("instance") }, _createItemWrapper: function(command, containerOptions) { return new dxNavBarItemWrapper(command, containerOptions) }, addCommand: function(command, containerOptions) { this.callBase(command, containerOptions); this._updateSelectedIndex() }, _onCommandChanged: function(args) { var optionName = args.name, newValue = args.value; if ("highlighted" === optionName && newValue) { this._updateSelectedIndex() } this.callBase(args) }, _updateSelectedIndex: function() { var items = this.widget.option("items"); for (var i = 0, itemsCount = items.length; i < itemsCount; i++) { var command = items[i].command; if (command && command.option("highlighted")) { this.widget.option("selectedIndex", i); break } } } }); var dxPivotItemWrapper = WidgetItemWrapperBase.inherit({ _createWidgetItemCore: function(itemOptions, executeCommandCallback) { itemOptions.title = itemOptions.text; return itemOptions } }); var dxPivotAdapter = WidgetAdapterBase.inherit({ ctor: function($widgetElement) { this.callBase($widgetElement); this.widget.option("onSelectionChanged", this._onPivotSelectionChange.bind(this)) }, _onPivotSelectionChange: function(e) { if (e.addedItems.length && e.removedItems.length && e.addedItems[0] && e.addedItems[0].command) { e.addedItems[0].command.execute(e) } }, _getWidgetByElement: function($element) { return $element.dxPivot("instance") }, _createItemWrapper: function(command, containerOptions) { return new dxPivotItemWrapper(command, containerOptions) }, addCommand: function(command, containerOptions) { this.callBase(command, containerOptions); this._updateSelectedIndex() }, _onCommandChanged: function(args) { var optionName = args.name, newValue = args.value; if ("visible" === optionName) { this._reRenderPivot() } else { if ("highlighted" === optionName && newValue) { this._updateSelectedIndex() } } this.callBase(args) }, _addItemToWidget: function(itemWrapper) { if (itemWrapper.command.option("visible")) { this.callBase(itemWrapper) } }, _updateSelectedIndex: function() { var pivot = this.widget, items = pivot.option("items") || []; fx.off = true; for (var i = 0, itemsCount = items.length; i < itemsCount; i++) { var command = items[i].command; if (command && command.option("highlighted")) { pivot.option("selectedIndex", i); break } } fx.off = false }, _reRenderPivot: function() { var that = this; that.widget.option("items", []); $.each(that.itemWrappers, function(index, itemWrapper) { if (itemWrapper.command.option("visible")) { that._addItemToWidget(itemWrapper) } }); that.refresh(); that._updateSelectedIndex() } }); var dxSlideOutItemWrapper = WidgetItemWrapperBase.inherit({}); var dxSlideOutAdapter = WidgetAdapterBase.inherit({ ctor: function($widgetElement) { this.callBase($widgetElement); this._commandToWidgetItemOptionNames = { title: "text" }; this.widget.option("onItemClick", this._onSlideOutItemClick.bind(this)) }, _onSlideOutItemClick: function(e) { e.itemData.command.execute(e) }, _getWidgetByElement: function($element) { return $element.dxSlideOut("instance") }, _createItemWrapper: function(command, containerOptions) { return new dxSlideOutItemWrapper(command, containerOptions) }, _updateSelectedIndex: function() { var items = this.widget.option("items") || []; for (var i = 0, itemsCount = items.length; i < itemsCount; i++) { var command = items[i].command; if (command && command.option("highlighted")) { this.widget.option("selectedIndex", i); break } } }, addCommand: function(command, containerOptions) { this.callBase(command, containerOptions); this._updateSelectedIndex() }, _onCommandChanged: function(args) { var optionName = args.name, newValue = args.value; if ("highlighted" === optionName && newValue) { this._updateSelectedIndex() } this.callBase(args) } }); exports.dxToolbar = new CommandToWidgetAdapter(function($widgetElement) { return new dxToolbarAdapter($widgetElement) }); exports.dxList = new CommandToWidgetAdapter(function($widgetElement) { return new dxListAdapter($widgetElement) }); exports.dxNavBar = new CommandToWidgetAdapter(function($widgetElement) { return new dxNavBarAdapter($widgetElement) }); exports.dxPivot = new CommandToWidgetAdapter(function($widgetElement) { return new dxPivotAdapter($widgetElement) }); exports.dxSlideOut = new CommandToWidgetAdapter(function($widgetElement) { return new dxSlideOutAdapter($widgetElement) }); exports.WidgetItemWrapperBase = WidgetItemWrapperBase; exports.WidgetAdapterBase = WidgetAdapterBase }, /*!******************************************!*\ !*** ./js/framework/html/view_engine.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), version = __webpack_require__( /*! ../../core/version */ 19), Class = __webpack_require__( /*! ../../core/class */ 25), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, errors = __webpack_require__( /*! ../errors */ 122), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when, _VIEW_ROLE = "dxView", _LAYOUT_ROLE = "dxLayout", MARKUP_TEMPLATE_MARKER = "MarkupTemplate:"; __webpack_require__( /*! ./view_engine_components */ 128); var ViewEngine = Class.inherit({ ctor: function(options) { options = options || {}; this.$root = options.$root; this.device = options.device || {}; this.dataOptionsAttributeName = options.dataOptionsAttributeName || "data-options"; this._templateMap = {}; this._pendingViewContainer = null; this.markupLoaded = $.Callbacks(); this._templateContext = options.templateContext; this._$skippedMarkup = $(); if (void 0 !== options.templatesVersion && options.templateCacheStorage && this._isReleaseVersion()) { this._templateCacheEnabled = true; this._templatesVersion = "v_" + options.templatesVersion; this._templateCacheStorage = options.templateCacheStorage; this._templateCacheKey = "dxTemplateCache_" + version + "_" + JSON.stringify(this.device) } }, _isReleaseVersion: function() { return !/http:\/\/localhost/.test(location.href) }, _enumerateTemplates: function(processFn) { var that = this; $.each(that._templateMap, function(name, templatesByRoleMap) { $.each(templatesByRoleMap, function(role, templates) { $.each(templates, function(index, template) { processFn(template) }) }) }) }, _findComponent: function(name, role) { var components = (this._templateMap[name] || {})[role] || [], filter = this._templateContext && this._templateContext.option() || {}; components = this._filterTemplates(filter, components); this._checkMatchedTemplates(components); return components[0] }, _findTemplate: function(name, role) { var component = this._findComponent(name, role); if (!component) { this._clearCache(); throw errors.Error("E3013", role, name) } var $result, $template = component.element(); if (!component._isStaticComponentsCreated) { domUtils.createComponents($template, ["dxContent", "dxContentPlaceholder", "dxTransition"]); component._isStaticComponentsCreated = true } $result = $template.clone().removeClass("dx-hidden"); return $result }, _clearCache: function() { if (this._templateCacheEnabled) { this._templateCacheStorage.removeItem(this._templateCacheKey) } }, _loadTemplatesFromMarkupCore: function($markup) { var that = this; if ($markup.find("[data-dx-role]").length) { throw errors.Error("E3019") } that.markupLoaded.fire({ markup: $markup }); var components = domUtils.createComponents($markup, [_VIEW_ROLE, _LAYOUT_ROLE]); $.each(components, function(index, component) { var $element = component.element(); $element.addClass("dx-hidden"); that._registerTemplateComponent(component); component.element().detach() }); var $skipped = $markup.filter("script"); $skipped.appendTo(that.$root); that._$skippedMarkup = that._$skippedMarkup.add($skipped) }, _registerTemplateComponent: function(component) { var role = component.NAME, options = component.option(), templateName = options.name, componentsByRoleMap = this._templateMap[templateName] || {}; componentsByRoleMap[role] = componentsByRoleMap[role] || []; componentsByRoleMap[role].push(component); this._templateMap[templateName] = componentsByRoleMap }, _applyPartialViews: function($render) { var that = this; domUtils.createComponents($render, ["dxViewPlaceholder"]); $.each($render.find(".dx-view-placeholder"), function() { var $partialPlaceholder = $(this); if ($partialPlaceholder.children().length) { return } var viewName = $partialPlaceholder.data("dxViewPlaceholder").option("viewName"), $view = that._findTemplate(viewName, _VIEW_ROLE); that._applyPartialViews($view); $partialPlaceholder.append($view); $view.removeClass("dx-hidden") }) }, _ajaxImpl: function() { return $.ajax.apply($, arguments) }, _loadTemplatesFromURL: function(url) { var that = this, options = this._getLoadOptions(), deferred = $.Deferred(); url = options.winPhonePrefix + url; this._ajaxImpl({ url: url, isLocal: options.isLocal, dataType: "html" }).done(function(data) { that._loadTemplatesFromMarkupCore(domUtils.createMarkupFromString(data)); deferred.resolve() }).fail(function(jqXHR, textStatus, errorThrown) { var error = errors.Error("E3021", url, errorThrown); deferred.reject(error) }); return deferred.promise() }, _getLoadOptions: function() { if (location.protocol.indexOf("wmapp") >= 0) { return { winPhonePrefix: location.protocol + "www/", isLocal: true } } return { winPhonePrefix: "", isLocal: void 0 } }, _loadExternalTemplates: function() { var tasks = [], that = this; $("head").find("link[rel='dx-template']").each(function(index, link) { var task = that._loadTemplatesFromURL($(link).attr("href")); tasks.push(task) }); return when.apply($, tasks) }, _processTemplates: function() { var that = this; $.each(that._templateMap, function(name, templatesByRoleMap) { $.each(templatesByRoleMap, function(role, templates) { that._filterTemplatesByDevice(templates) }) }); that._enumerateTemplates(function(template) { that._applyPartialViews(template.element()) }) }, _filterTemplatesByDevice: function(components) { var filteredComponents = this._filterTemplates(this.device, components); $.each(components, function(index, component) { if (inArray(component, filteredComponents) < 0) { component.element().remove() } }); components.length = 0; components.push.apply(components, filteredComponents) }, _filterTemplates: function(filter, components) { return commonUtils.findBestMatches(filter, components, function(component) { return component.option() }) }, _checkMatchedTemplates: function(bestMatches) { if (bestMatches.length > 1) { var message = ""; $.each(bestMatches, function(index, match) { message += match.element().attr("data-options") + "\r\n" }); throw errors.Error("E3020", message, JSON.stringify(this.device)) } }, _wrapViewDefaultContent: function($viewTemplate) { $viewTemplate.wrapInner('<div class="dx-full-height"></div>'); $viewTemplate.children().eq(0).dxContent({ targetPlaceholder: "content" }) }, _initDefaultLayout: function() { this._$defaultLayoutTemplate = $('<div class="dx-full-height" data-options="dxLayout : { name: \'default\' } "> \n <div class="dx-full-height" data-options="dxContentPlaceholder : { name: \'content\' } " ></div> \n</div>'); domUtils.createComponents(this._$defaultLayoutTemplate) }, _getDefaultLayoutTemplate: function() { return this._$defaultLayoutTemplate.clone() }, applyLayout: function($view, $layout) { if (void 0 === $layout || 0 === $layout.length) { $layout = this._getDefaultLayoutTemplate() } if (0 === $view.children(".dx-content").length) { this._wrapViewDefaultContent($view) } var $toMerge = $().add($layout).add($view); var $placeholderContents = $toMerge.find(".dx-content"); $.each($placeholderContents, function() { var $placeholderContent = $(this); var placeholderId = $placeholderContent.attr("data-dx-target-placeholder-id"); var $placeholder = $toMerge.find(".dx-content-placeholder-" + placeholderId); $placeholder.empty(); $placeholder.append($placeholderContent) }); for (var i = $placeholderContents.length; i >= 0; i--) { var $item = $placeholderContents.eq(i); if (!$item.is(".dx-content-placeholder .dx-content")) { $item.remove() } } return $layout }, _loadTemplatesFromCache: function() { if (!this._templateCacheEnabled) { return } var cache; var fromJSONInterceptor = function(key, value) { if ("string" === typeof value && 0 === value.indexOf(MARKUP_TEMPLATE_MARKER)) { var data = JSON.parse(value.substr(MARKUP_TEMPLATE_MARKER.length)), type = data.type, options = data.options, $markup = domUtils.createMarkupFromString(data.markup); options.fromCache = true; return $markup[type](options)[type]("instance") } else { if ("skippedMarkup" === key) { return $("<div>").append(domUtils.createMarkupFromString(value)).contents() } } return value }; var toParse = this._templateCacheStorage.getItem(this._templateCacheKey); if (toParse) { try { var cacheContainer = JSON.parse(toParse, fromJSONInterceptor); cache = cacheContainer[this._templatesVersion] } catch (e) { this._clearCache() } } if (!cache) { return } this._templateMap = cache.templates; this.$root.append(cache.skippedMarkup); return true }, _putTemplatesToCache: function() { if (!this._templateCacheEnabled) { return } var toJSONInterceptor = function(key, value) { if (value && value.element) { return MARKUP_TEMPLATE_MARKER + JSON.stringify({ markup: value.element().prop("outerHTML"), options: value.option(), type: value.NAME }) } else { if ("skippedMarkup" === key) { return $("<div>").append(value.clone()).html() } } return value }; var cacheContainer = {}; cacheContainer[this._templatesVersion] = { templates: this._templateMap, skippedMarkup: this._$skippedMarkup }; this._templateCacheStorage.setItem(this._templateCacheKey, JSON.stringify(cacheContainer, toJSONInterceptor, 4)) }, init: function() { var that = this; this._initDefaultLayout(); if (!this._loadTemplatesFromCache()) { that._loadTemplatesFromMarkupCore(that.$root.children()); return this._loadExternalTemplates().done(function() { that._processTemplates(); that._putTemplatesToCache() }) } else { return $.Deferred().resolve().promise() } }, getViewTemplate: function(viewName) { return this._findTemplate(viewName, _VIEW_ROLE) }, getViewTemplateInfo: function(name) { return this._findComponent(name, _VIEW_ROLE) }, getLayoutTemplate: function(layoutName) { if (!layoutName) { return this._getDefaultLayoutTemplate() } return this._findTemplate(layoutName, _LAYOUT_ROLE) }, getLayoutTemplateInfo: function(name) { return this._findComponent(name, _LAYOUT_ROLE) }, loadTemplates: function(source) { var result; if ("string" === typeof source) { result = this._loadTemplatesFromURL(source) } else { this._loadTemplatesFromMarkupCore(source); result = $.Deferred().resolve().promise() } return result.done(this._processTemplates.bind(this)) } }); exports.ViewEngine = ViewEngine }, /*!************************************************!*\ !*** ./js/framework/html/layout_controller.js ***! \************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), frameworkUtils = __webpack_require__( /*! ../utils */ 131), layoutSets = __webpack_require__( /*! ./presets */ 138).layoutSets, EventsMixin = __webpack_require__( /*! ../../core/events_mixin */ 51), errors = __webpack_require__( /*! ../errors */ 122), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when, HIDDEN_BAG_ID = "__hidden-bag", TRANSITION_SELECTOR = ".dx-transition", CONTENT_SELECTOR = ".dx-content", DEFAULT_COMMAND_RENDER_STAGE = "onViewShown", CONTENT_RENDERED_EVENT_NAME = "dxcontentrendered.layoutController", PENDING_RENDERING_SELECTOR = ".dx-pending-rendering", PENDING_RENDERING_MANUAL_SELECTOR = ".dx-pending-rendering-manual", TransitionExecutorModule = __webpack_require__( /*! ../../animation/transition_executor/transition_executor */ 74); __webpack_require__( /*! ./command_container */ 126); __webpack_require__( /*! ./view_engine_components */ 128); var transitionSelector = function(transitionName) { return ".dx-transition-" + transitionName }; var DefaultLayoutController = Class.inherit({ ctor: function(options) { options = options || {}; this.name = options.name || ""; this._layoutModel = options.layoutModel || {}; this._defaultPaneName = options.defaultPaneName || "content"; this._transitionDuration = void 0 === options.transitionDuration ? 400 : options.transitionDuration; this._showViewFired = false }, init: function(options) { options = options || {}; this._visibleViews = {}; this._$viewPort = options.$viewPort || $("body"); this._commandManager = options.commandManager; this._viewEngine = options.viewEngine; this.transitionExecutor = new TransitionExecutorModule.TransitionExecutor; this._prepareTemplates(); this._$viewPort.append(this.element()); this._hideElements(this.element()); if (options.templateContext) { this._templateContext = options.templateContext; this._proxiedTemplateContextChangedHandler = this._templateContextChangedHandler.bind(this) } }, ensureActive: function(targetNode) { if (this._disabledState) { return this.enable() } else { return this.activate(targetNode) } }, activate: function() { this._showViewFired = false; var $rootElement = this.element(); this._showElements($rootElement); this._attachRefreshViewRequiredHandler(); return $.Deferred().resolve().promise() }, deactivate: function() { this._disabledState = false; this._showViewFired = false; this._releaseVisibleViews(); this._hideElements(this.element()); this._detachRefreshViewRequiredHandler(); return $.Deferred().resolve().promise() }, enable: function() { this._disabledState = false; if (!this._showViewFired) { this._notifyShowing() } this._showViewFired = false; return $.Deferred().resolve().promise() }, disable: function() { this._disabledState = true; this._showViewFired = false; this._notifyHidden() }, activeViewInfo: function() { return this._visibleViews[this._defaultPaneName] }, _fireViewEvents: function(eventName, views) { var that = this; views = views || this._visibleViews; $.each(views, function(index, viewInfo) { that.fireEvent(eventName, [viewInfo]) }) }, _notifyShowing: function(views) { this._fireViewEvents("viewShowing", views) }, _notifyShown: function(views) { this._fireViewEvents("viewShown", views) }, _notifyHidden: function(views) { this._fireViewEvents("viewHidden", views) }, _applyTemplate: function($elements, model) { $elements.each(function(i, element) { frameworkUtils.templateProvider.applyTemplate(element, model) }) }, _releaseVisibleViews: function() { var that = this; $.each(this._visibleViews, function(index, viewInfo) { that._hideView(viewInfo); that._releaseView(viewInfo) }); this._visibleViews = {} }, _templateContextChangedHandler: function() { var that = this, viewsToShow = []; $.each(that._visibleViews, function(index, viewInfo) { if (viewInfo.currentViewTemplateId !== that._getViewTemplateId(viewInfo)) { viewsToShow.push(viewInfo) } }); when.apply($, $.map(viewsToShow, function(viewInfo) { return that.showView(viewInfo) })).done(function() { that._notifyShown(viewsToShow) }) }, _attachRefreshViewRequiredHandler: function() { if (this._templateContext) { this._templateContext.on("optionChanged", this._proxiedTemplateContextChangedHandler) } }, _detachRefreshViewRequiredHandler: function() { if (this._templateContextChanged) { this._templateContext.off("optionChanged", this._proxiedTemplateContextChangedHandler) } }, _getPreviousViewInfo: function(viewInfo) { return this._visibleViews[this._getViewPaneName(viewInfo.viewTemplateInfo)] }, _prepareTemplates: function() { var that = this; var $layoutTemplate = that._viewEngine.getLayoutTemplate(this._getLayoutTemplateName()); that._$layoutTemplate = $layoutTemplate; that._$mainLayout = that._createEmptyLayout(); that._showElements(that._$mainLayout); that._applyTemplate(that._$mainLayout, that._layoutModel); that._$navigationWidget = that._createNavigationWidget() }, renderNavigation: function(navigationCommands) { this._clearNavigationWidget(); this._renderNavigationImpl(navigationCommands) }, _renderNavigationImpl: function(navigationCommands) { this._renderCommands(this._$mainLayout, navigationCommands) }, _createNavigationWidget: function() { var result, containers = this._findCommandContainers(this._$mainLayout); $.each(containers, function(k, container) { if ("global-navigation" === container.option("id")) { result = container.element(); return false } }); return result }, _clearNavigationWidget: function() { if (this._$navigationWidget) { this._commandManager.clearContainer(this._$navigationWidget.dxCommandContainer("instance")) } }, element: function() { return this._$mainLayout }, _getViewFrame: function(viewInfo) { return this._$mainLayout }, _getLayoutTemplateName: function() { return this.name }, _applyModelToTransitionElements: function($markup, model) { var that = this; this._getTransitionElements($markup).each(function(i, item) { that._applyTemplate($(item).children(), model) }) }, _createViewLayoutTemplate: function() { var that = this; var $viewLayoutTemplate = that._$layoutTemplate.clone(); this._hideElements($viewLayoutTemplate); return $viewLayoutTemplate }, _createEmptyLayout: function() { var that = this; var $result = that._$layoutTemplate.clone(); this._hideElements($result); this._getTransitionElements($result).empty(); $result.children(CONTENT_SELECTOR).remove(); return $result }, _getTransitionElements: function($markup) { var $items = $markup.find(TRANSITION_SELECTOR).add($markup.filter(TRANSITION_SELECTOR)), result = []; for (var i = 0; i < $items.length; i++) { var $item = $items.eq(i); if (0 === $item.parents(TRANSITION_SELECTOR).length) { result.push($item.get(0)) } } return $(result) }, showView: function(viewInfo, direction) { direction = direction || "forward"; var result, that = this, previousViewInfo = that._getPreviousViewInfo(viewInfo), previousViewTemplateId = previousViewInfo === viewInfo ? previousViewInfo.currentViewTemplateId : void 0; this._showViewFired = true; this._updateCurrentViewTemplateId(viewInfo); if (previousViewTemplateId && previousViewTemplateId === viewInfo.currentViewTemplateId && viewInfo === previousViewInfo) { that.fireEvent("viewShowing", [viewInfo, direction]); result = $.Deferred().resolve().promise() } else { that._ensureViewRendered(viewInfo); that.fireEvent("viewShowing", [viewInfo, direction]); result = this._showViewImpl(viewInfo, direction, previousViewTemplateId).done(function() { that._onViewShown(viewInfo) }) } return result }, disposeView: function(viewInfo) { this._clearRenderResult(viewInfo) }, _clearRenderResult: function(viewInfo) { if (viewInfo.renderResult) { viewInfo.renderResult.$markup.remove(); viewInfo.renderResult.$viewItems.remove(); delete viewInfo.renderResult } }, _renderViewImpl: function($viewTemplate, viewInfo) { var $viewItems, that = this, allowedChildrenSelector = ".dx-command,.dx-content,script", $layout = this._createViewLayoutTemplate(), isSimplifiedMarkup = true, outOfContentItems = $(); if (0 === $viewTemplate.children(allowedChildrenSelector).length) { this._viewEngine._wrapViewDefaultContent($viewTemplate) } $viewItems = $viewTemplate.children(); this._applyModelToTransitionElements($layout, viewInfo.model); this._viewEngine.applyLayout($viewTemplate, $layout); $viewItems.each(function(i, item) { var $item = $(item); that._applyTemplate($item, viewInfo.model); if ($item.is(allowedChildrenSelector)) { isSimplifiedMarkup = false } else { outOfContentItems = outOfContentItems.add($item) } }); if (outOfContentItems.length && !isSimplifiedMarkup) { throw errors.Error("E3014", outOfContentItems[0].outerHTML) } viewInfo.renderResult = viewInfo.renderResult || {}; viewInfo.renderResult.$viewItems = $viewItems; viewInfo.renderResult.$markup = $layout }, _renderCommands: function($markup, commands) { var commandContainers = this._findCommandContainers($markup); return this._commandManager.renderCommandsToContainers(commands, commandContainers) }, _prepareViewCommands: function(viewInfo) { var $viewItems = viewInfo.renderResult.$viewItems, viewCommands = this._commandManager.findCommands($viewItems), commandsToRenderMap = {}; viewInfo.commands = frameworkUtils.utils.mergeCommands(viewInfo.commands || [], viewCommands); viewInfo.commandsToRenderMap = commandsToRenderMap; $.each(viewInfo.commands, function(index, command) { var renderStage = command.option("renderStage") || DEFAULT_COMMAND_RENDER_STAGE, targetArray = commandsToRenderMap[renderStage] = commandsToRenderMap[renderStage] || []; targetArray.push(command) }) }, _applyViewCommands: function(viewInfo, renderStage) { renderStage = renderStage || DEFAULT_COMMAND_RENDER_STAGE; var result, commandsToRender = viewInfo.commandsToRenderMap[renderStage], $markup = viewInfo.renderResult.$markup; if (commandsToRender) { result = this._renderCommands($markup, commandsToRender); delete viewInfo.commandsToRenderMap[renderStage] } else { result = $.Deferred().resolve().promise() } return result }, _findCommandContainers: function($markup) { return domUtils.createComponents($markup, ["dxCommandContainer"]) }, _getViewTemplateId: function(viewInfo) { var viewTemplateInstance = viewInfo.$viewTemplate ? viewInfo.$viewTemplate.dxView("instance") : this._viewEngine.getViewTemplateInfo(viewInfo.viewName); return viewTemplateInstance.getId() }, _updateCurrentViewTemplateId: function(viewInfo) { viewInfo.currentViewTemplateId = this._getViewTemplateId(viewInfo) }, _ensureViewRendered: function(viewInfo) { var $cachedMarkup = viewInfo.renderResult && viewInfo.renderResult.markupCache[viewInfo.currentViewTemplateId]; if ($cachedMarkup) { viewInfo.renderResult.$markup = $cachedMarkup } else { this._renderView(viewInfo); viewInfo.renderResult.markupCache = viewInfo.renderResult.markupCache || {}; viewInfo.renderResult.markupCache[viewInfo.currentViewTemplateId] = viewInfo.renderResult.$markup } }, _renderView: function(viewInfo) { var $viewTemplate = viewInfo.$viewTemplate || this._viewEngine.getViewTemplate(viewInfo.viewName); this._renderViewImpl($viewTemplate, viewInfo); this._prepareViewCommands(viewInfo); this._applyViewCommands(viewInfo, "onViewRendering"); this._appendViewToLayout(viewInfo); $viewTemplate.remove(); this._onRenderComplete(viewInfo); this.fireEvent("viewRendered", [viewInfo]) }, _prepareTransition: function($element, targetPlaceholderName) { if (0 === $element.children(".dx-content").length) { $element.wrapInner("<div>"); $element.children().dxContent({ targetPlaceholder: targetPlaceholderName }) } }, _appendViewToLayout: function(viewInfo) { var that = this, $viewFrame = that._getViewFrame(viewInfo), $markup = viewInfo.renderResult.$markup, $transitionContentElements = $(), animationItems = []; $.each($markup.find(".dx-content-placeholder"), function(index, el) { that._prepareTransition($(el), $(el).attr("data-dx-content-placeholder-name")) }); $.each(that._getTransitionElements($viewFrame), function(index, transitionElement) { var $transition = $(transitionElement), $viewElement = $markup.find(transitionSelector($transition.attr("data-dx-transition-name"))).children(), animationItem = { $element: $viewElement, animation: $transition.attr("data-dx-transition-type") }; animationItems.push(animationItem); $transition.append($viewElement); that._showViewElements($viewElement); domUtils.triggerShownEvent($viewElement); $transitionContentElements = $transitionContentElements.add($viewElement) }); that._$mainLayout.append(viewInfo.renderResult.$viewItems.filter(".dx-command")); $markup.remove(); viewInfo.renderResult.$markup = $transitionContentElements; viewInfo.renderResult.animationItems = animationItems }, _onRenderComplete: function(viewInfo) {}, _onViewShown: function(viewInfo) { $(document).trigger("dx.viewchanged") }, _enter: function(animationItems, animationModifier) { var transitionExecutor = this.transitionExecutor; $.each(animationItems, function(index, item) { transitionExecutor.enter(item.$element, item.animation, animationModifier) }) }, _leave: function(animationItems, animationModifier) { var transitionExecutor = this.transitionExecutor; $.each(animationItems, function(index, item) { transitionExecutor.leave(item.$element, item.animation, animationModifier) }) }, _doTransition: function(oldViewInfo, newViewInfo, animationModifier) { if (oldViewInfo) { this._leave(oldViewInfo.renderResult.animationItems, animationModifier) } this._enter(newViewInfo.renderResult.animationItems, animationModifier); this._showView(newViewInfo); return this.transitionExecutor.start() }, _showViewImpl: function(viewInfo, direction, previousViewTemplateId) { var that = this, previousViewInfo = this._getPreviousViewInfo(viewInfo), animationModifier = { direction: direction }; if (previousViewInfo === viewInfo) { previousViewInfo = void 0 } if (!previousViewInfo) { animationModifier.duration = 0; animationModifier.delay = 0 } var d = $.Deferred(); that._doTransition(previousViewInfo, viewInfo, animationModifier).done(function() { that._changeView(viewInfo, previousViewTemplateId).done(function(result) { d.resolve(result) }) }); return d.promise() }, _releaseView: function(viewInfo) { this.fireEvent("viewReleased", [viewInfo]) }, _getReadyForRenderDeferredItems: function(viewInfo) { return $.Deferred().resolve().promise() }, _changeView: function(viewInfo, previousViewTemplateId) { var that = this; if (previousViewTemplateId) { that._hideView(viewInfo, previousViewTemplateId) } else { var previousViewInfo = that._getPreviousViewInfo(viewInfo); if (previousViewInfo && previousViewInfo !== viewInfo) { that._hideView(previousViewInfo); that._releaseView(previousViewInfo) } this._visibleViews[this._getViewPaneName(viewInfo.viewTemplateInfo)] = viewInfo } this._subscribeToDeferredItems(viewInfo); var d = $.Deferred(); this._getReadyForRenderDeferredItems(viewInfo).done(function() { that._applyViewCommands(viewInfo).done(function() { that._renderDeferredItems(viewInfo.renderResult.$markup).done(function() { d.resolve() }) }) }); return d.promise() }, _subscribeToDeferredItems: function(viewInfo) { var that = this, $markup = viewInfo.renderResult.$markup; $markup.find(PENDING_RENDERING_SELECTOR).add($markup.filter(PENDING_RENDERING_SELECTOR)).each(function() { var eventData = { viewInfo: viewInfo, context: that }; $(this).on(CONTENT_RENDERED_EVENT_NAME, eventData, that._onDeferredContentRendered) }) }, _onDeferredContentRendered: function(event) { var $element = $(event.target), viewInfo = event.data.viewInfo, that = event.data.context; $element.off(CONTENT_RENDERED_EVENT_NAME, that._onDeferredContentRendered); that._renderCommands($element, viewInfo.commands) }, _renderDeferredItems: function($items) { var that = this, result = $.Deferred(); var $pendingItem = $items.find(PENDING_RENDERING_MANUAL_SELECTOR).add($items.filter(PENDING_RENDERING_MANUAL_SELECTOR)).first(); if ($pendingItem.length) { var render = $pendingItem.data("dx-render-delegate"); commonUtils.executeAsync(function() { render().done(function() { that._renderDeferredItems($items).done(function() { result.resolve() }) }) }) } else { result.resolve() } return result.promise() }, _getViewPaneName: function(viewTemplateInfo) { return this._defaultPaneName }, _hideElements: function($elements) { $elements.addClass("dx-fast-hidden") }, _showElements: function($elements) { $elements.removeClass("dx-fast-hidden") }, _hideViewElements: function($elements) { this._patchIds($elements); this._disableInputs($elements); $elements.removeClass("dx-active-view").addClass("dx-inactive-view") }, _hideView: function(viewInfo, templateId) { if (viewInfo.renderResult) { var $markupToHide = void 0 === templateId ? viewInfo.renderResult.$markup : viewInfo.renderResult.markupCache[templateId]; this._hideViewElements($markupToHide); this.fireEvent("viewHidden", [viewInfo]) } }, _showViewElements: function($elements) { this._unPatchIds($elements); this._enableInputs($elements); $elements.removeClass("dx-inactive-view").addClass("dx-active-view"); this._skipAnimation($elements) }, _showView: function(viewInfo) { if (viewInfo.renderResult) { this._showViewElements(viewInfo.renderResult.$markup) } }, _skipAnimation: function($elements) { $elements.addClass("dx-skip-animation"); for (var i = 0; i < $elements.length; i++) { $elements.eq(i).css("transform") } $elements.removeClass("dx-skip-animation") }, _patchIds: function($markup) { this._processIds($markup, function(id) { var result = id; if (id.indexOf(HIDDEN_BAG_ID) === -1) { result = HIDDEN_BAG_ID + "-" + id } return result }) }, _unPatchIds: function($markup) { this._processIds($markup, function(id) { var result = id; if (0 === id.indexOf(HIDDEN_BAG_ID)) { result = id.substr(HIDDEN_BAG_ID.length + 1) } return result }) }, _processIds: function($markup, process) { var elementsWithIds = $markup.find("[id]"); $.each(elementsWithIds, function(index, element) { var $el = $(element), id = $el.attr("id"); $el.attr("id", process(id)) }) }, _enableInputs: function($markup) { var $inputs = this._getInputs($markup).filter("[data-disabled='true']"); $.each($inputs, function(index, input) { $(input).removeAttr("disabled").removeAttr("data-disabled") }) }, _disableInputs: function($markup) { var $inputs = this._getInputs($markup); $inputs = $inputs.filter(":not([disabled])").add($inputs.filter("[disabled=true]")); $.each($inputs, function(index, input) { $(input).attr({ disabled: true, "data-disabled": true }) }) }, _getInputs: function($markup) { return $markup.find("input, button, select, textarea") } }).include(EventsMixin); layoutSets.default = layoutSets.default || []; layoutSets.default.push({ controller: new DefaultLayoutController }); exports.DefaultLayoutController = DefaultLayoutController; exports.layoutSets = layoutSets }, /*!*************************!*\ !*** ./js/ui/themes.js ***! \*************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ./widget/ui.errors */ 22), domUtils = __webpack_require__( /*! ../core/utils/dom */ 56), devices = __webpack_require__( /*! ../core/devices */ 53), viewPortUtils = __webpack_require__( /*! ../core/utils/view_port */ 55), viewPort = viewPortUtils.value, viewPortChanged = viewPortUtils.changeCallback, holdReady = $.holdReady || $.fn.holdReady; var DX_LINK_SELECTOR = "link[rel=dx-theme]", THEME_ATTR = "data-theme", ACTIVE_ATTR = "data-active", DX_HAIRLINES_CLASS = "dx-hairlines"; var context, $activeThemeLink, knownThemes, currentThemeName, pendingThemeName; var THEME_MARKER_PREFIX = "dx."; function readThemeMarker() { var result, element = $("<div></div>", context).addClass("dx-theme-marker").appendTo(context.documentElement); try { result = element.css("font-family"); if (!result) { return null } result = result.replace(/["']/g, ""); if (result.substr(0, THEME_MARKER_PREFIX.length) !== THEME_MARKER_PREFIX) { return null } return result.substr(THEME_MARKER_PREFIX.length) } finally { element.remove() } } function waitForThemeLoad(themeName, callback) { var timerId, waitStartTime; pendingThemeName = themeName; function handleLoaded() { pendingThemeName = null; callback() } if (isPendingThemeLoaded()) { handleLoaded() } else { waitStartTime = $.now(); timerId = setInterval(function() { var isLoaded = isPendingThemeLoaded(), isTimeout = !isLoaded && $.now() - waitStartTime > 15e3; if (isTimeout) { errors.log("W0004", pendingThemeName) } if (isLoaded || isTimeout) { clearInterval(timerId); handleLoaded() } }, 10) } } function isPendingThemeLoaded() { return !pendingThemeName || readThemeMarker() === pendingThemeName } function processMarkup() { var $allThemeLinks = $(DX_LINK_SELECTOR, context); if (!$allThemeLinks.length) { return } knownThemes = {}; $activeThemeLink = $(domUtils.createMarkupFromString("<link rel=stylesheet>"), context); $allThemeLinks.each(function() { var link = $(this, context), fullThemeName = link.attr(THEME_ATTR), url = link.attr("href"), isActive = "true" === link.attr(ACTIVE_ATTR); knownThemes[fullThemeName] = { url: url, isActive: isActive } }); $allThemeLinks.last().after($activeThemeLink); $allThemeLinks.remove() } function resolveFullThemeName(desiredThemeName) { var desiredThemeParts = desiredThemeName.split("."), result = null; if (knownThemes) { if (desiredThemeName in knownThemes) { return desiredThemeName } $.each(knownThemes, function(knownThemeName, themeData) { var knownThemeParts = knownThemeName.split("."); if (knownThemeParts[0] !== desiredThemeParts[0]) { return } if (desiredThemeParts[1] && desiredThemeParts[1] !== knownThemeParts[1]) { return } if (desiredThemeParts[2] && desiredThemeParts[2] !== knownThemeParts[2]) { return } if (!result || themeData.isActive) { result = knownThemeName } if (themeData.isActive) { return false } }) } return result } function initContext(newContext) { try { if (newContext !== context) { knownThemes = null } } catch (x) { knownThemes = null } context = newContext } function init(options) { options = options || {}; initContext(options.context || document); processMarkup(); currentThemeName = void 0; current(options) } function current(options) { if (!arguments.length) { currentThemeName = currentThemeName || readThemeMarker(); return currentThemeName } detachCssClasses(viewPort()); options = options || {}; if ("string" === typeof options) { options = { theme: options } } var currentThemeData, isAutoInit = options._autoInit, loadCallback = options.loadCallback; currentThemeName = options.theme || currentThemeName; if (isAutoInit && !currentThemeName) { currentThemeName = themeNameFromDevice(devices.current()) } currentThemeName = resolveFullThemeName(currentThemeName); if (currentThemeName) { currentThemeData = knownThemes[currentThemeName] } if (currentThemeData) { $activeThemeLink.attr("href", knownThemes[currentThemeName].url); if (loadCallback) { waitForThemeLoad(currentThemeName, loadCallback) } else { if (pendingThemeName) { pendingThemeName = currentThemeName } } } else { if (isAutoInit) { if (loadCallback) { loadCallback() } } else { throw errors.Error("E0021", currentThemeName) } } attachCssClasses(viewPortUtils.originalViewPort(), currentThemeName) } function themeNameFromDevice(device) { var themeName = device.platform; var majorVersion = device.version && device.version[0]; switch (themeName) { case "ios": themeName += "7"; break; case "android": themeName += "5"; break; case "win": themeName += majorVersion && 8 === majorVersion ? "8" : "10" } return themeName } function getCssClasses(themeName) { themeName = themeName || current(); var result = [], themeNameParts = themeName && themeName.split("."); if (themeNameParts) { result.push("dx-theme-" + themeNameParts[0], "dx-theme-" + themeNameParts[0] + "-typography"); if (themeNameParts.length > 1) { result.push("dx-color-scheme-" + themeNameParts[1]) } } return result } var themeClasses; function attachCssClasses(element, themeName) { themeClasses = getCssClasses(themeName).join(" "); $(element).addClass(themeClasses); var activateHairlines = function() { var pixelRatio = window.devicePixelRatio; if (!pixelRatio || pixelRatio < 2) { return } var $tester = $("<div>"); $tester.css("border", ".5px solid transparent"); $("body").append($tester); if (1 === $tester.outerHeight()) { $(element).addClass(DX_HAIRLINES_CLASS); themeClasses += " " + DX_HAIRLINES_CLASS } $tester.remove() }; activateHairlines() } function detachCssClasses(element) { $(element).removeClass(themeClasses) } holdReady(true); init({ _autoInit: true, loadCallback: function() { holdReady(false) } }); domUtils.ready(function() { if ($(DX_LINK_SELECTOR, context).length) { throw errors.Error("E0022") } }); viewPortChanged.add(function(viewPort, prevViewPort) { detachCssClasses(prevViewPort); attachCssClasses(viewPort) }); devices.changed.add(function() { init({ _autoInit: true }) }); exports.current = current; exports.init = init; exports.attachCssClasses = attachCssClasses; exports.detachCssClasses = detachCssClasses; exports.themeNameFromDevice = themeNameFromDevice; exports.waitForThemeLoad = waitForThemeLoad; exports.resetTheme = function() { $activeThemeLink && $activeThemeLink.attr("href", "about:blank"); currentThemeName = null; pendingThemeName = null } }, /*!***********************************!*\ !*** ./js/integration/angular.js ***! \***********************************/ function(module, exports, __webpack_require__) { var angular = __webpack_require__( /*! angular */ 145); if (angular) { __webpack_require__( /*! ./angular/component_registrator */ 146); __webpack_require__( /*! ./angular/event_registrator */ 173); __webpack_require__( /*! ./angular/components */ 174); __webpack_require__( /*! ./angular/action_executors */ 175) } }, /*!*********************************!*\ !*** external "window.angular" ***! \*********************************/ function(module, exports) { module.exports = window.angular }, /*!*********************************************************!*\ !*** ./js/integration/angular/component_registrator.js ***! \*********************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Config = __webpack_require__( /*! ../../core/config */ 15), registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), Class = __webpack_require__( /*! ../../core/class */ 25), type = __webpack_require__( /*! ../../core/utils/common */ 14).type, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, Locker = __webpack_require__( /*! ../../core/utils/locker */ 112), Widget = __webpack_require__( /*! ../../ui/widget/ui.widget */ 95), Editor = __webpack_require__( /*! ../../ui/editor/editor */ 106), NgTemplate = __webpack_require__( /*! ./template */ 147), ngModule = __webpack_require__( /*! ./module */ 148), CollectionWidget = __webpack_require__( /*! ../../ui/collection/ui.collection_widget.edit */ 149), compileSetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileSetter, compileGetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileGetter, extendFromObject = __webpack_require__( /*! ../../core/utils/extend */ 11).extendFromObject, isNumeric = __webpack_require__( /*! ../../core/utils/common */ 14).isNumeric, inflector = __webpack_require__( /*! ../../core/utils/inflector */ 39), errors = __webpack_require__( /*! ../../core/errors */ 7); var ITEM_ALIAS_ATTRIBUTE_NAME = "dxItemAlias", SKIP_APPLY_ACTION_CATEGORIES = ["rendering"]; var safeApply = function(func, scope) { if (scope.$root.$$phase) { return func(scope) } else { return scope.$apply(function() { return func(scope) }) } }; var ComponentBuilder = Class.inherit({ ctor: function(options) { this._componentDisposing = $.Callbacks(); this._optionChangedCallbacks = $.Callbacks(); this._ngLocker = new Locker; this._scope = options.scope; this._$element = options.$element; this._$templates = options.$templates; this._componentClass = options.componentClass; this._parse = options.parse; this._compile = options.compile; this._itemAlias = options.itemAlias; this._transcludeFn = options.transcludeFn; this._digestCallbacks = options.dxDigestCallbacks; this._normalizeOptions(options.ngOptions); this._initComponentBindings(); this._initComponent(this._scope); if (!options.ngOptions) { this._addOptionsStringWatcher(options.ngOptionsString) } }, _addOptionsStringWatcher: function(optionsString) { var that = this; var clearOptionsStringWatcher = that._scope.$watch(optionsString, function(newOptions) { if (!newOptions) { return } clearOptionsStringWatcher(); that._normalizeOptions(newOptions); that._initComponentBindings(); that._component.option(that._evalOptions(that._scope)) }); that._componentDisposing.add(clearOptionsStringWatcher) }, _normalizeOptions: function(options) { var that = this; that._ngOptions = extendFromObject({}, options); if (!options) { return } if (!options.hasOwnProperty("bindingOptions") && options.bindingOptions) { that._ngOptions.bindingOptions = options.bindingOptions } if (options.bindingOptions) { $.each(options.bindingOptions, function(key, value) { if ("string" === type(value)) { that._ngOptions.bindingOptions[key] = { dataPath: value } } }) } }, _initComponent: function(scope) { this._component = new this._componentClass(this._$element, this._evalOptions(scope)); this._component._isHidden = true; this._handleDigestPhase() }, _handleDigestPhase: function() { var that = this, beginUpdate = function() { that._component.beginUpdate() }, endUpdate = function() { that._component.endUpdate() }; that._digestCallbacks.begin.add(beginUpdate); that._digestCallbacks.end.add(endUpdate); that._componentDisposing.add(function() { that._digestCallbacks.begin.remove(beginUpdate); that._digestCallbacks.end.remove(endUpdate) }) }, _initComponentBindings: function() { var that = this, optionDependencies = {}; if (!that._ngOptions.bindingOptions) { return } $.each(that._ngOptions.bindingOptions, function(optionPath, value) { var prevWatchMethod, clearWatcher, separatorIndex = optionPath.search(/\[|\./), optionForSubscribe = separatorIndex > -1 ? optionPath.substring(0, separatorIndex) : optionPath, valuePath = value.dataPath, deepWatch = true, forcePlainWatchMethod = false; if (void 0 !== value.deep) { forcePlainWatchMethod = deepWatch = !!value.deep } if (!optionDependencies[optionForSubscribe]) { optionDependencies[optionForSubscribe] = {} } optionDependencies[optionForSubscribe][optionPath] = valuePath; var watchCallback = function(newValue, oldValue) { if (that._ngLocker.locked(optionPath)) { return } that._ngLocker.obtain(optionPath); that._component.option(optionPath, newValue); updateWatcher(); if (that._component._optionValuesEqual(optionPath, oldValue, newValue) && that._ngLocker.locked(optionPath)) { that._ngLocker.release(optionPath) } }; var updateWatcher = function() { var watchMethod = Array.isArray(that._scope.$eval(valuePath)) && !forcePlainWatchMethod ? "$watchCollection" : "$watch"; if (prevWatchMethod !== watchMethod) { if (clearWatcher) { clearWatcher() } clearWatcher = that._scope[watchMethod](valuePath, watchCallback, deepWatch); prevWatchMethod = watchMethod } }; updateWatcher(); that._componentDisposing.add(clearWatcher) }); that._optionChangedCallbacks.add(function(args) { var optionName = args.name, fullName = args.fullName, component = args.component; if (that._ngLocker.locked(fullName)) { that._ngLocker.release(fullName); return } if (!optionDependencies || !optionDependencies[optionName]) { return } that._ngLocker.obtain(fullName); safeApply(function() { $.each(optionDependencies[optionName], function(optionPath, valuePath) { if (!that._optionsAreLinked(fullName, optionPath)) { return } var value = component.option(optionPath); that._parse(valuePath).assign(that._scope, value); var scopeValue = that._parse(valuePath)(that._scope); if (scopeValue !== value) { args.component.option(optionPath, scopeValue) } }) }, that._scope); var releaseOption = function() { if (that._ngLocker.locked(fullName)) { that._ngLocker.release(fullName) } that._digestCallbacks.end.remove(releaseOption) }; releaseOption(); that._digestCallbacks.end.add(releaseOption) }) }, _optionsAreNested: function(optionPath1, optionPath2) { var parentSeparator = optionPath1[optionPath2.length]; return 0 === optionPath1.indexOf(optionPath2) && ("." === parentSeparator || "[" === parentSeparator) }, _optionsAreLinked: function(optionPath1, optionPath2) { if (optionPath1 === optionPath2) { return true } return optionPath1.length > optionPath2.length ? this._optionsAreNested(optionPath1, optionPath2) : this._optionsAreNested(optionPath2, optionPath1) }, _compilerByTemplate: function(template) { var that = this, scopeItemsPath = this._getScopeItemsPath(); return function(options) { var $resultMarkup = $(template).clone(), dataIsScope = options.model && options.model.constructor === that._scope.$root.constructor, templateScope = dataIsScope ? options.model : options.noModel ? that._scope : that._createScopeWithData(options.model); if (scopeItemsPath) { that._synchronizeScopes(templateScope, scopeItemsPath, options.index) } $resultMarkup.appendTo(options.container); if (!options.noModel) { $resultMarkup.on("$destroy", function() { var destroyAlreadyCalled = !templateScope.$parent; if (destroyAlreadyCalled) { return } templateScope.$destroy() }) } that._applyAsync(that._compile($resultMarkup, that._transcludeFn), templateScope); return $resultMarkup } }, _applyAsync: function(func, scope) { var that = this; func(scope); if (!scope.$root.$$phase) { if (!that._renderingTimer) { that._renderingTimer = setTimeout(function() { scope.$apply(); that._renderingTimer = null }) } that._componentDisposing.add(function() { clearTimeout(that._renderingTimer) }) } }, _getScopeItemsPath: function() { if (this._componentClass.subclassOf(CollectionWidget) && this._ngOptions.bindingOptions && this._ngOptions.bindingOptions.items) { return this._ngOptions.bindingOptions.items.dataPath } }, _createScopeWithData: function(data) { var newScope = this._scope.$new(); if (this._itemAlias) { newScope[this._itemAlias] = data } return newScope }, _synchronizeScopes: function(itemScope, parentPrefix, itemIndex) { if (this._itemAlias && "object" !== typeof itemScope[this._itemAlias]) { this._synchronizeScopeField({ parentScope: this._scope, childScope: itemScope, fieldPath: this._itemAlias, parentPrefix: parentPrefix, itemIndex: itemIndex }) } }, _synchronizeScopeField: function(args) { var parentScope = args.parentScope, childScope = args.childScope, fieldPath = args.fieldPath, parentPrefix = args.parentPrefix, itemIndex = args.itemIndex; var optionOuterPath, innerPathSuffix = fieldPath === this._itemAlias ? "" : "." + fieldPath, collectionField = void 0 !== itemIndex, optionOuterBag = [parentPrefix]; if (collectionField) { if (!isNumeric(itemIndex)) { return } optionOuterBag.push("[", itemIndex, "]") } optionOuterBag.push(innerPathSuffix); optionOuterPath = optionOuterBag.join(""); var clearParentWatcher = parentScope.$watch(optionOuterPath, function(newValue, oldValue) { if (newValue !== oldValue) { compileSetter(fieldPath)(childScope, newValue) } }); var clearItemWatcher = childScope.$watch(fieldPath, function(newValue, oldValue) { if (newValue !== oldValue) { if (collectionField && !compileGetter(parentPrefix)(parentScope)[itemIndex]) { clearItemWatcher(); return } compileSetter(optionOuterPath)(parentScope, newValue) } }); this._componentDisposing.add([clearParentWatcher, clearItemWatcher]) }, _evalOptions: function(scope) { var result = extendFromObject({}, this._ngOptions); delete result.bindingOptions; if (this._ngOptions.bindingOptions) { $.each(this._ngOptions.bindingOptions, function(key, value) { result[key] = scope.$eval(value.dataPath) }) } result._optionChangedCallbacks = this._optionChangedCallbacks; result._disposingCallbacks = this._componentDisposing; result.onActionCreated = function(component, action, config) { if (config && inArray(config.category, SKIP_APPLY_ACTION_CATEGORIES) > -1) { return action } var wrappedAction = function() { var that = this, args = arguments; if (!scope || !scope.$root || scope.$root.$$phase) { return action.apply(that, args) } return safeApply(function() { return action.apply(that, args) }, scope) }; return wrappedAction }; result.beforeActionExecute = result.onActionCreated; result.nestedComponentOptions = function(component) { return { templatesRenderAsynchronously: component.option("templatesRenderAsynchronously"), forceApplyBindings: component.option("forceApplyBindings"), modelByElement: component.option("modelByElement"), onActionCreated: component.option("onActionCreated"), beforeActionExecute: component.option("beforeActionExecute"), nestedComponentOptions: component.option("nestedComponentOptions") } }; result.templatesRenderAsynchronously = true; if (Config().wrapActionsBeforeExecute) { result.forceApplyBindings = function() { safeApply(function() {}, scope) } } result.integrationOptions = { createTemplate: function(element) { return new NgTemplate(element, this._compilerByTemplate.bind(this)) }.bind(this), watchMethod: function(fn, callback, options) { options = options || {}; var immediateValue; var skipCallback = options.skipImmediate; var disposeWatcher = scope.$watch(function() { var value = fn(); if (value instanceof Date) { value = value.valueOf() } return value }, function(newValue) { var isSameValue = immediateValue === newValue; if (!skipCallback && (!isSameValue || isSameValue && options.deep)) { callback(newValue) } skipCallback = false }, options.deep); if (!skipCallback) { immediateValue = fn(); callback(immediateValue) } if (Config().wrapActionsBeforeExecute) { safeApply(function() {}, scope) } return disposeWatcher }, templates: { "dx-polymorph-widget": { render: function(options) { var widgetName = options.model.widget; if (!widgetName) { return } if ("button" === widgetName || "tabs" === widgetName || "dropDownMenu" === widgetName) { var deprecatedName = widgetName; widgetName = inflector.camelize("dx-" + widgetName); errors.log("W0001", "dxToolbar - 'widget' item field", deprecatedName, "16.1", "Use: '" + widgetName + "' instead") } var markup = $("<div " + inflector.dasherize(widgetName) + '="options">').get(0); var newScope = this._scope.$new(); newScope.options = options.model.options; options.container.append(markup); this._compile(markup)(newScope) }.bind(this) } } }; result.modelByElement = function() { return scope }; return result } }); ComponentBuilder = ComponentBuilder.inherit({ ctor: function(options) { this._componentName = options.componentName; this._ngModel = options.ngModel; this._ngModelController = options.ngModelController; this.callBase.apply(this, arguments) }, _isNgModelRequired: function() { return this._componentClass.subclassOf(Editor) && this._ngModel }, _initComponentBindings: function() { this.callBase.apply(this, arguments); this._initNgModelBinding() }, _initNgModelBinding: function() { if (!this._isNgModelRequired()) { return } var that = this; var clearNgModelWatcher = this._scope.$watch(this._ngModel, function(newValue, oldValue) { if (that._ngLocker.locked(that._ngModelOption())) { return } if (newValue === oldValue) { return } that._component.option(that._ngModelOption(), newValue) }); that._optionChangedCallbacks.add(function(args) { that._ngLocker.obtain(that._ngModelOption()); try { if (args.name !== that._ngModelOption()) { return } that._ngModelController.$setViewValue(args.value) } finally { that._ngLocker.release(that._ngModelOption()) } }); this._componentDisposing.add(clearNgModelWatcher) }, _ngModelOption: function() { if (inArray(this._componentName, ["dxFileUploader", "dxTagBox"]) > -1) { return "values" } return "value" }, _evalOptions: function() { if (!this._isNgModelRequired()) { return this.callBase.apply(this, arguments) } var result = this.callBase.apply(this, arguments); result[this._ngModelOption()] = this._parse(this._ngModel)(this._scope); return result } }); var registeredComponents = {}; var registerComponentDirective = function(name) { var priority = "dxValidator" !== name ? 1 : 10; ngModule.directive(name, ["$compile", "$parse", "dxDigestCallbacks", function($compile, $parse, dxDigestCallbacks) { return { restrict: "A", require: "^?ngModel", priority: priority, compile: function($element) { var componentClass = registeredComponents[name], $content = componentClass.subclassOf(Widget) ? $element.contents().detach() : null; return function(scope, $element, attrs, ngModelController, transcludeFn) { $element.append($content); safeApply(function() { new ComponentBuilder({ componentClass: componentClass, componentName: name, compile: $compile, parse: $parse, $element: $element, scope: scope, ngOptionsString: attrs[name], ngOptions: attrs[name] ? scope.$eval(attrs[name]) : {}, ngModel: attrs.ngModel, ngModelController: ngModelController, transcludeFn: transcludeFn, itemAlias: attrs[ITEM_ALIAS_ATTRIBUTE_NAME], dxDigestCallbacks: dxDigestCallbacks }) }, scope) } } } }]) }; registerComponent.callbacks.add(function(name, componentClass) { if (!registeredComponents[name]) { registerComponentDirective(name) } registeredComponents[name] = componentClass }) }, /*!********************************************!*\ !*** ./js/integration/angular/template.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), TemplateBase = __webpack_require__( /*! ../../ui/widget/ui.template_base */ 97), isFunction = __webpack_require__( /*! ../../core/utils/common */ 14).isFunction, domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56); var NgTemplate = TemplateBase.inherit({ ctor: function(element, templateCompiler) { this._element = element; this._compiledTemplate = templateCompiler(domUtils.normalizeTemplateElement(this._element)) }, _renderCore: function(options) { var compiledTemplate = this._compiledTemplate, result = isFunction(compiledTemplate) ? compiledTemplate(options) : compiledTemplate; return result }, source: function() { return $(this._element).clone() } }); module.exports = NgTemplate }, /*!******************************************!*\ !*** ./js/integration/angular/module.js ***! \******************************************/ function(module, exports, __webpack_require__) { var angular = __webpack_require__( /*! angular */ 145); module.exports = angular.module("dx", []) }, /*!*******************************************************!*\ !*** ./js/ui/collection/ui.collection_widget.edit.js ***! \*******************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), BaseCollectionWidget = __webpack_require__( /*! ./ui.collection_widget.base */ 150), errors = __webpack_require__( /*! ../widget/ui.errors */ 22), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), PlainEditStrategy = __webpack_require__( /*! ./ui.collection_widget.edit.strategy.plain */ 167), compileGetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileGetter, DataSource = __webpack_require__( /*! ../../data/data_source/data_source */ 153).DataSource, Selection = __webpack_require__( /*! ../selection/selection */ 169), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; var ITEM_DELETING_DATA_KEY = "dxItemDeleting", NOT_EXISTING_INDEX = -1; var indexExists = function(index) { return index !== NOT_EXISTING_INDEX }; var CollectionWidget = BaseCollectionWidget.inherit({ _setOptionsByReference: function() { this.callBase(); extend(this._optionsByReference, { selectedItem: true }) }, _getDefaultOptions: function() { return extend(this.callBase(), { selectionMode: "none", selectionRequired: false, selectionByClick: true, selectedItems: [], selectedItemKeys: [], maxFilterLengthInRequest: 1500, keyExpr: null, selectedIndex: NOT_EXISTING_INDEX, selectedItem: null, onSelectionChanged: null, onItemReordered: null, onItemDeleting: null, onItemDeleted: null }) }, ctor: function(element, options) { this._userOptions = options || {}; this.callBase(element, options) }, _init: function() { this._initEditStrategy(); this.callBase(); this._initKeyGetter(); this._initSelectionModule(); if ("multi" === this.option("selectionMode")) { this._showDeprecatedSelectionMode() } }, _initKeyGetter: function() { this._keyGetter = compileGetter(this.option("keyExpr")) }, _getKeysByItems: function(selectedItems) { return this._editStrategy.getKeysByItems(selectedItems) }, _getItemsByKeys: function(selectedItemKeys, selectedItems) { return this._editStrategy.getItemsByKeys(selectedItemKeys, selectedItems) }, _getKeyByIndex: function(index) { return this._editStrategy.getKeyByIndex(index) }, _getIndexByKey: function(key) { return this._editStrategy.getIndexByKey(key) }, _getIndexByItemData: function(itemData) { return this._editStrategy.getIndexByItemData(itemData) }, _isKeySpecified: function() { return !!(this._dataSource && this._dataSource.key()) }, keyOf: function(item) { var key = item, store = this._dataSource && this._dataSource.store(); if (this.option("keyExpr")) { key = this._keyGetter(item) } else { if (store) { key = store.keyOf(item) } } return key }, _initSelectionModule: function() { var that = this, itemsGetter = that._editStrategy.itemsGetter; this._selection = new Selection({ mode: this.option("selectionMode"), maxFilterLengthInRequest: this.option("maxFilterLengthInRequest"), equalByReference: !this._isKeySpecified(), onSelectionChanged: function(args) { if (args.addedItemKeys.length || args.removedItemKeys.length) { that.option("selectedItems", that._getItemsByKeys(args.selectedItemKeys, args.selectedItems)); that._updateSelectedItems(args.addedItems, args.removedItems) } }, filter: function() { return that._dataSource && that._dataSource.filter() }, totalCount: function() { var items = that.option("items"); var dataSource = that._dataSource; return dataSource && dataSource.totalCount() >= 0 ? dataSource.totalCount() : items.length }, key: function() { if (that.option("keyExpr")) { return that.option("keyExpr") } return that._dataSource && that._dataSource.key() }, keyOf: that.keyOf.bind(that), load: function(options) { if (that._dataSource) { var loadOptions = that._dataSource.loadOptions(); options.customQueryParams = loadOptions.customQueryParams; options.userData = that._dataSource._userData } var store = that._dataSource && that._dataSource.store(); return store ? store.load(options) : $.Deferred().resolve([]) }, dataFields: function() { return that._dataSource && that._dataSource.select() }, plainItems: itemsGetter.bind(that._editStrategy) }) }, _initEditStrategy: function() { var Strategy = PlainEditStrategy; this._editStrategy = new Strategy(this) }, _forgetNextPageLoading: function() { this.callBase() }, _getSelectedItemIndices: function(keys) { var that = this, indices = []; keys = keys || this._selection.getSelectedItemKeys(); $.each(keys, function(_, key) { var selectedIndex = that._getIndexByKey(key); if (indexExists(selectedIndex)) { indices.push(selectedIndex) } }); return indices }, _render: function() { this._rendering = true; if (!this._dataSource || !this._dataSource.isLoading()) { this._syncSelectionOptions(); this._normalizeSelectedItems() } this.callBase(); var selectedItemIndices = this._getSelectedItemIndices(); this._renderSelection(selectedItemIndices, []); this._rendering = false }, _fireContentReadyAction: function() { this._rendering = false; this._rendered = true; this.callBase.apply(this, arguments) }, _syncSelectionOptions: function(byOption) { byOption = byOption || this._chooseSelectOption(); var selectedItem, selectedItems, selectedIndex; switch (byOption) { case "selectedIndex": selectedItem = this._editStrategy.getItemDataByIndex(this.option("selectedIndex")); if (commonUtils.isDefined(selectedItem)) { this._setOptionSilent("selectedItems", [selectedItem]); this._setOptionSilent("selectedItem", selectedItem); this._setOptionSilent("selectedItemKeys", this._editStrategy.getKeysByItems([selectedItem])) } else { this._setOptionSilent("selectedItems", []); this._setOptionSilent("selectedItemKeys", []); this._setOptionSilent("selectedItem", null) } break; case "selectedItems": selectedItems = this.option("selectedItems") || []; selectedIndex = this._editStrategy.getIndexByItemData(selectedItems[0]); if (this.option("selectionRequired") && !indexExists(selectedIndex)) { this._syncSelectionOptions("selectedIndex"); return } this._setOptionSilent("selectedItem", selectedItems[0]); this._setOptionSilent("selectedIndex", selectedIndex); this._setOptionSilent("selectedItemKeys", this._editStrategy.getKeysByItems(selectedItems)); break; case "selectedItem": selectedItem = this.option("selectedItem"); selectedIndex = this._editStrategy.getIndexByItemData(selectedItem); if (this.option("selectionRequired") && !indexExists(selectedIndex)) { this._syncSelectionOptions("selectedIndex"); return } if (commonUtils.isDefined(selectedItem)) { this._setOptionSilent("selectedItems", [selectedItem]); this._setOptionSilent("selectedIndex", selectedIndex); this._setOptionSilent("selectedItemKeys", this._editStrategy.getKeysByItems([selectedItem])) } else { this._setOptionSilent("selectedItems", []); this._setOptionSilent("selectedItemKeys", []); this._setOptionSilent("selectedIndex", NOT_EXISTING_INDEX) } break; case "selectedItemKeys": var selectedItemKeys = this.option("selectedItemKeys"); if (this.option("selectionRequired") && !indexExists(this._getIndexByKey(selectedItemKeys[0]))) { this._syncSelectionOptions("selectedIndex"); return } this._selection.setSelection(selectedItemKeys) } }, _chooseSelectOption: function() { var optionName = "selectedIndex"; var arrayOptionsDefined = function(optionName) { var length = this.option(optionName).length; return length || !length && optionName in this._userOptions }.bind(this); if (arrayOptionsDefined("selectedItems")) { optionName = "selectedItems" } else { if (commonUtils.isDefined(this.option("selectedItem"))) { optionName = "selectedItem" } else { if (arrayOptionsDefined("selectedItemKeys")) { optionName = "selectedItemKeys" } } } return optionName }, _compareKeys: function(oldKeys, newKeys) { if (oldKeys.length !== newKeys.length) { return false } for (var i = 0; i < newKeys.length; i++) { if (oldKeys[i] !== newKeys[i]) { return false } } return true }, _normalizeSelectedItems: function() { if ("none" === this.option("selectionMode")) { this._setOptionSilent("selectedItems", []); this._syncSelectionOptions("selectedItems") } else { if ("single" === this.option("selectionMode")) { var newSelection = this.option("selectedItems"); if (newSelection.length > 1 || !newSelection.length && this.option("selectionRequired") && this.option("items") && this.option("items").length) { var currentSelection = this._selection.getSelectedItems(); var normalizedSelection = void 0 === newSelection[0] ? currentSelection[0] : newSelection[0]; if (void 0 === normalizedSelection) { normalizedSelection = this._editStrategy.itemsGetter()[0] } if (this.option("grouped") && normalizedSelection && normalizedSelection.items) { normalizedSelection.items = [normalizedSelection.items[0]] } this._selection.setSelection(this._getKeysByItems([normalizedSelection])); this._setOptionSilent("selectedItems", [normalizedSelection]); this._syncSelectionOptions("selectedItems") } else { this._selection.setSelection(this._getKeysByItems(newSelection)) } } else { var newKeys = this._getKeysByItems(this.option("selectedItems")); var oldKeys = this._selection.getSelectedItemKeys(); if (!this._compareKeys(oldKeys, newKeys)) { this._selection.setSelection(newKeys) } } } }, _renderSelection: commonUtils.noop, _itemClickHandler: function(e) { this._createAction(function(e) { this._itemSelectHandler(e.jQueryEvent) }.bind(this), { validatingTargetName: "itemElement" })({ itemElement: $(e.currentTarget), jQueryEvent: e }); this.callBase.apply(this, arguments) }, _itemSelectHandler: function(e) { if (!this.option("selectionByClick")) { return } var $itemElement = e.currentTarget; if (this.isItemSelected($itemElement)) { this.unselectItem(e.currentTarget) } else { this.selectItem(e.currentTarget) } }, _selectedItemElement: function(index) { return this._itemElements().eq(index) }, _postprocessRenderItem: function(args) { if ("none" === this.option("selectionMode")) { return } var $itemElement = $(args.itemElement); if (this._isItemSelected(this._editStrategy.getNormalizedIndex($itemElement))) { $itemElement.addClass(this._selectedItemClass()); this._setAriaSelected($itemElement, "true") } else { this._setAriaSelected($itemElement, "false") } }, _updateSelectedItems: function(addedItems, removedItems) { var that = this; if (that._rendered && (addedItems.length || removedItems.length)) { var selectionChangePromise = that._selectionChangePromise; if (!that._rendering) { var normalizedIndex, i, addedSelection = [], removedSelection = []; for (i = 0; i < addedItems.length; i++) { normalizedIndex = that._getIndexByItemData(addedItems[i]); addedSelection.push(normalizedIndex); that._addSelection(normalizedIndex) } for (i = 0; i < removedItems.length; i++) { normalizedIndex = that._getIndexByItemData(removedItems[i]); removedSelection.push(normalizedIndex); that._removeSelection(normalizedIndex) } that._updateSelection(addedSelection, removedSelection) } when(selectionChangePromise).done(function() { that._fireSelectionChangeEvent(addedItems, removedItems) }) } }, _fireSelectionChangeEvent: function(addedItems, removedItems) { this._createActionByOption("onSelectionChanged", { excludeValidators: ["disabled", "readOnly"] })({ addedItems: addedItems, removedItems: removedItems }) }, _updateSelection: function() { this._renderSelection.apply(this, arguments) }, _setAriaSelected: function($target, value) { this.setAria("selected", value, $target) }, _removeSelection: function(normalizedIndex) { var $itemElement = this._editStrategy.getItemElement(normalizedIndex); if (indexExists(normalizedIndex)) { $itemElement.removeClass(this._selectedItemClass()); this._setAriaSelected($itemElement, "false"); $itemElement.triggerHandler("stateChanged", false) } }, _showDeprecatedSelectionMode: function() { errors.log("W0001", this.NAME, "selectionMode: 'multi'", "16.1", "Use selectionMode: 'multiple' instead"); this.option("selectionMode", "multiple") }, _addSelection: function(normalizedIndex) { var $itemElement = this._editStrategy.getItemElement(normalizedIndex); if (indexExists(normalizedIndex)) { $itemElement.addClass(this._selectedItemClass()); this._setAriaSelected($itemElement, "true"); $itemElement.triggerHandler("stateChanged", true) } }, _isItemSelected: function(index) { var key = this._getKeyByIndex(index); return this._selection.isItemSelected(key) }, _optionChanged: function(args) { if (this._cancelOptionChange === args.name) { return } switch (args.name) { case "selectionMode": if ("multi" === args.value) { this._showDeprecatedSelectionMode() } else { this._invalidate() } break; case "selectedIndex": case "selectedItem": case "selectedItems": case "selectedItemKeys": this._syncSelectionOptions(args.name); this._normalizeSelectedItems(); break; case "keyExpr": this._initKeyGetter(); break; case "selectionRequired": this._normalizeSelectedItems(); break; case "selectionByClick": case "onSelectionChanged": case "onItemDeleting": case "onItemDeleted": case "onItemReordered": case "maxFilterLengthInRequest": break; default: this.callBase(args) } }, _clearSelectedItems: function() { this._setOptionSilent("selectedItems", []); this._syncSelectionOptions("selectedItems") }, _setOptionSilent: function(name, value) { this._cancelOptionChange = name; this.option(name, value); this._cancelOptionChange = false }, _waitDeletingPrepare: function($itemElement) { if ($itemElement.data(ITEM_DELETING_DATA_KEY)) { return $.Deferred().resolve().promise() } $itemElement.data(ITEM_DELETING_DATA_KEY, true); var deferred = $.Deferred(), deletingActionArgs = { cancel: false }, deletePromise = this._itemEventHandler($itemElement, "onItemDeleting", deletingActionArgs, { excludeValidators: ["disabled", "readOnly"] }); when(deletePromise).always(function(value) { var deletePromiseExists = !deletePromise, deletePromiseResolved = !deletePromiseExists && "resolved" === deletePromise.state(), argumentsSpecified = !!arguments.length, shouldDelete = deletePromiseExists || deletePromiseResolved && !argumentsSpecified || deletePromiseResolved && value; when(deletingActionArgs.cancel).always(function() { $itemElement.data(ITEM_DELETING_DATA_KEY, false) }).done(function(cancel) { shouldDelete && !cancel ? deferred.resolve() : deferred.reject() }).fail(deferred.reject) }.bind(this)); return deferred.promise() }, _deleteItemFromDS: function($item) { if (!this._dataSource) { return $.Deferred().resolve().promise() } var deferred = $.Deferred(), disabledState = this.option("disabled"), dataStore = this._dataSource.store(); this.option("disabled", true); if (!dataStore.remove) { throw errors.Error("E1011") } dataStore.remove(dataStore.keyOf(this._getItemData($item))).done(function(key) { if (void 0 !== key) { deferred.resolve() } else { deferred.reject() } }).fail(function() { deferred.reject() }); deferred.always(function() { this.option("disabled", disabledState) }.bind(this)); return deferred }, _tryRefreshLastPage: function() { var deferred = $.Deferred(); if (this._isLastPage() || this.option("grouped")) { deferred.resolve() } else { this._refreshLastPage().done(function() { deferred.resolve() }) } return deferred.promise() }, _refreshLastPage: function() { this._expectLastItemLoading(); return this._dataSource.load() }, _updateSelectionAfterDelete: function(index) { var key = this._getKeyByIndex(index); this._selection.deselect([key]) }, _simulateOptionChange: function(optionName) { var optionValue = this.option(optionName); if (optionValue instanceof DataSource) { return } this._optionChangedAction({ name: optionName, fullName: optionName, value: optionValue }) }, isItemSelected: function(itemElement) { return this._isItemSelected(this._editStrategy.getNormalizedIndex(itemElement)) }, selectItem: function(itemElement) { if ("none" === this.option("selectionMode")) { return } var itemIndex = this._editStrategy.getNormalizedIndex(itemElement); if (!indexExists(itemIndex)) { return } var key = this._getKeyByIndex(itemIndex); if (this._selection.isItemSelected(key)) { return } if ("single" === this.option("selectionMode")) { this._selection.setSelection([key]) } else { var selectedItemKeys = this.option("selectedItemKeys"); selectedItemKeys.push(key); this._selection.setSelection(selectedItemKeys) } }, unselectItem: function(itemElement) { var itemIndex = this._editStrategy.getNormalizedIndex(itemElement); if (!indexExists(itemIndex)) { return } var selectedItemKeys = this._selection.getSelectedItemKeys(); if (this.option("selectionRequired") && selectedItemKeys.length <= 1) { return } var key = this._getKeyByIndex(itemIndex); this._selection.deselect([key]) }, deleteItem: function(itemElement) { var that = this, deferred = $.Deferred(), $item = this._editStrategy.getItemElement(itemElement), index = this._editStrategy.getNormalizedIndex(itemElement), changingOption = this._dataSource ? "dataSource" : "items", itemResponseWaitClass = this._itemResponseWaitClass(); if (indexExists(index)) { this._waitDeletingPrepare($item).done(function() { $item.addClass(itemResponseWaitClass); var deletedActionArgs = that._extendActionArgs($item); that._deleteItemFromDS($item).done(function() { that._updateSelectionAfterDelete(index); that._editStrategy.deleteItemAtIndex(index); that._simulateOptionChange(changingOption); that._itemEventHandler($item, "onItemDeleted", deletedActionArgs, { beforeExecute: function() { $item.detach() }, excludeValidators: ["disabled", "readOnly"] }); that._renderEmptyMessage(); that._tryRefreshLastPage().done(function() { deferred.resolveWith(that) }) }).fail(function() { $item.removeClass(itemResponseWaitClass); deferred.rejectWith(that) }) }).fail(function() { deferred.rejectWith(that) }) } else { deferred.rejectWith(that) } return deferred.promise() }, reorderItem: function(itemElement, toItemElement) { var deferred = $.Deferred(), that = this, strategy = this._editStrategy, $movingItem = strategy.getItemElement(itemElement), $destinationItem = strategy.getItemElement(toItemElement), movingIndex = strategy.getNormalizedIndex(itemElement), destinationIndex = strategy.getNormalizedIndex(toItemElement), changingOption = this._dataSource ? "dataSource" : "items"; var canMoveItems = indexExists(movingIndex) && indexExists(destinationIndex) && movingIndex !== destinationIndex; if (canMoveItems) { deferred.resolveWith(this) } else { deferred.rejectWith(this) } return deferred.promise().done(function() { $destinationItem[strategy.itemPlacementFunc(movingIndex, destinationIndex)]($movingItem); strategy.moveItemAtIndexToIndex(movingIndex, destinationIndex); that.option("selectedItems", that._getItemsByKeys(that._selection.getSelectedItemKeys(), that._selection.getSelectedItems())); if ("items" === changingOption) { that._simulateOptionChange(changingOption) } that._itemEventHandler($movingItem, "onItemReordered", { fromIndex: strategy.getIndex(movingIndex), toIndex: strategy.getIndex(destinationIndex) }, { excludeValidators: ["disabled", "readOnly"] }) }) } }); module.exports = CollectionWidget }, /*!*******************************************************!*\ !*** ./js/ui/collection/ui.collection_widget.base.js ***! \*******************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), isPlainObject = __webpack_require__( /*! ../../core/utils/type */ 12).isPlainObject, when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, Action = __webpack_require__( /*! ../../core/action */ 49), Guid = __webpack_require__( /*! ../../core/guid */ 151), domUtils = __webpack_require__( /*! ../../core/utils/dom */ 56), dataUtils = __webpack_require__( /*! ../../core/utils/data */ 50), Widget = __webpack_require__( /*! ../widget/ui.widget */ 95), eventUtils = __webpack_require__( /*! ../../events/utils */ 71), pointerEvents = __webpack_require__( /*! ../../events/pointer */ 76), DataHelperMixin = __webpack_require__( /*! ../../data_helper */ 152), CollectionWidgetItem = __webpack_require__( /*! ./item */ 163), selectors = __webpack_require__( /*! ../widget/jquery.selectors */ 102), messageLocalization = __webpack_require__( /*! ../../localization/message */ 89), holdEvent = __webpack_require__( /*! ../../events/hold */ 164), clickEvent = __webpack_require__( /*! ../../events/click */ 75), contextMenuEvent = __webpack_require__( /*! ../../events/contextmenu */ 165), BindableTemplate = __webpack_require__( /*! ../widget/bindable_template */ 166); var COLLECTION_CLASS = "dx-collection", ITEM_CLASS = "dx-item", CONTENT_CLASS_POSTFIX = "-content", ITEM_CONTENT_PLACEHOLDER_CLASS = "dx-item-content-placeholder", ITEM_DATA_KEY = "dxItemData", ITEM_INDEX_KEY = "dxItemIndex", ITEM_TEMPLATE_ID_PREFIX = "tmpl-", ITEMS_SELECTOR = "[data-options*='dxItem']", SELECTED_ITEM_CLASS = "dx-item-selected", ITEM_RESPONSE_WAIT_CLASS = "dx-item-response-wait", EMPTY_COLLECTION = "dx-empty-collection", TEMPLATE_WRAPPER_CLASS = "dx-template-wrapper", ITEM_PATH_REGEX = /^([^.]+\[\d+\]\.)+([\w\.]+)$/; var FOCUS_UP = "up", FOCUS_DOWN = "down", FOCUS_LEFT = "left", FOCUS_RIGHT = "right", FOCUS_PAGE_UP = "pageup", FOCUS_PAGE_DOWN = "pagedown", FOCUS_LAST = "last", FOCUS_FIRST = "first"; var CollectionWidget = Widget.inherit({ _activeStateUnit: "." + ITEM_CLASS, _supportedKeys: function() { var enter = function(e) { var $itemElement = this.option("focusedElement"); if (!$itemElement) { return } e.target = $itemElement; e.currentTarget = $itemElement; this._itemClickHandler(e) }, space = function(e) { e.preventDefault(); enter.call(this, e) }, move = function(location, e) { e.preventDefault(); e.stopPropagation(); this._moveFocus(location, e) }; return extend(this.callBase(), { space: space, enter: enter, leftArrow: move.bind(this, FOCUS_LEFT), rightArrow: move.bind(this, FOCUS_RIGHT), upArrow: move.bind(this, FOCUS_UP), downArrow: move.bind(this, FOCUS_DOWN), pageUp: move.bind(this, FOCUS_UP), pageDown: move.bind(this, FOCUS_DOWN), home: move.bind(this, FOCUS_FIRST), end: move.bind(this, FOCUS_LAST) }) }, _getDefaultOptions: function() { return extend(this.callBase(), { selectOnFocus: false, loopItemFocus: true, items: [], itemTemplate: "item", onItemRendered: null, onItemClick: null, onItemHold: null, itemHoldTimeout: 750, onItemContextMenu: null, onFocusedItemChanged: null, noDataText: messageLocalization.format("dxCollectionWidget-noDataText"), dataSource: null, _itemAttributes: {}, itemTemplateProperty: "template", focusOnSelectedItem: true, focusedElement: null, disabledExpr: function(data) { return data ? data.disabled : void 0 }, visibleExpr: function(data) { return data ? data.visible : void 0 } }) }, _getAnonymousTemplateName: function() { return "item" }, _init: function() { this.callBase(); this._cleanRenderedItems(); this._refreshDataSource() }, _initTemplates: function() { this._initItemsFromMarkup(); this.callBase(); this._defaultTemplates.item = new BindableTemplate(function($container, data) { if (isPlainObject(data)) { if (data.text) { $container.text(data.text) } if (data.html) { $container.html(data.html) } } else { $container.text(String(data)) } }, ["text", "html"], this.option("integrationOptions.watchMethod")) }, _initItemsFromMarkup: function() { var $items = this.element().contents().filter(ITEMS_SELECTOR); if (!$items.length || this.option("items").length) { return } var items = $.map($items, function(item) { var $item = $(item); var result = domUtils.getElementOptions(item).dxItem; var isTemplateRequired = $.trim($item.html()) && !result.template; if (isTemplateRequired) { result.template = this._prepareItemTemplate($item) } else { $item.remove() } return result }.bind(this)); this.option("items", items) }, _prepareItemTemplate: function($item) { var templateId = ITEM_TEMPLATE_ID_PREFIX + new Guid; var templateOptions = 'dxTemplate: { name: "' + templateId + '" }'; $item.detach().clone().attr("data-options", templateOptions).data("options", templateOptions).appendTo(this.element()); return templateId }, _dataSourceOptions: function() { return { paginate: false } }, _cleanRenderedItems: function() { this._renderedItemsCount = 0 }, _focusTarget: function() { return this.element() }, _focusInHandler: function(e) { this.callBase.apply(this, arguments); if (inArray(e.target, this._focusTarget()) === -1) { return } var $focusedElement = this.option("focusedElement"); if ($focusedElement && $focusedElement.length) { this._setFocusedItem($focusedElement) } else { var $activeItem = this._getActiveItem(); if ($activeItem.length) { this.option("focusedElement", $activeItem) } } }, _focusOutHandler: function() { this.callBase.apply(this, arguments); var $target = this.option("focusedElement"); if ($target) { this._toggleFocusClass(false, $target) } }, _getActiveItem: function(last) { var $focusedElement = this.option("focusedElement"); if ($focusedElement && $focusedElement.length) { return $focusedElement } var index = this.option("focusOnSelectedItem") ? this.option("selectedIndex") : 0, activeElements = this._getActiveElement(), lastIndex = activeElements.length - 1; if (index < 0) { index = last ? lastIndex : 0 } return activeElements.eq(index) }, _renderFocusTarget: function() { this.callBase.apply(this, arguments); this._refreshActiveDescendant() }, _moveFocus: function(location) { var $newTarget, $items = this._getAvailableItems(); switch (location) { case FOCUS_PAGE_UP: case FOCUS_UP: $newTarget = this._prevItem($items); break; case FOCUS_PAGE_DOWN: case FOCUS_DOWN: $newTarget = this._nextItem($items); break; case FOCUS_RIGHT: $newTarget = this.option("rtlEnabled") ? this._prevItem($items) : this._nextItem($items); break; case FOCUS_LEFT: $newTarget = this.option("rtlEnabled") ? this._nextItem($items) : this._prevItem($items); break; case FOCUS_FIRST: $newTarget = $items.first(); break; case FOCUS_LAST: $newTarget = $items.last(); break; default: return false } if (0 !== $newTarget.length) { this.option("focusedElement", $newTarget) } }, _getAvailableItems: function($itemElements) { $itemElements = $itemElements || this._itemElements(); return $itemElements.filter(":visible").not(".dx-state-disabled") }, _prevItem: function($items) { var $target = this._getActiveItem(), targetIndex = $items.index($target), $last = $items.last(), $item = $($items[targetIndex - 1]), loop = this.option("loopItemFocus"); if (0 === $item.length && loop) { $item = $last } return $item }, _nextItem: function($items) { var $target = this._getActiveItem(true), targetIndex = $items.index($target), $first = $items.first(), $item = $($items[targetIndex + 1]), loop = this.option("loopItemFocus"); if (0 === $item.length && loop) { $item = $first } return $item }, _selectFocusedItem: function($target) { this.selectItem($target) }, _removeFocusedItem: function($target) { if ($target && $target.length) { this._toggleFocusClass(false, $target); $target.removeAttr("id") } }, _refreshActiveDescendant: function() { this.setAria("activedescendant", ""); this.setAria("activedescendant", this.getFocusedItemId()) }, _setFocusedItem: function($target) { if (!$target || !$target.length) { return } $target.attr("id", this.getFocusedItemId()); this._toggleFocusClass(true, $target); this.onFocusedItemChanged(this.getFocusedItemId()); this._refreshActiveDescendant(); if (this.option("selectOnFocus")) { this._selectFocusedItem($target) } }, _findItemElementByItem: function(item) { var result = $(), that = this; this.itemElements().each(function() { var $item = $(this); if ($item.data(that._itemDataKey()) === item) { result = $item; return false } }); return result }, _getIndexByItem: function(item) { return this.option("items").indexOf(item) }, _itemOptionChanged: function(item, property, value, oldValue) { var $item = this._findItemElementByItem(item); if (!$item.length) { return } if (!this.constructor.ItemClass.getInstance($item).setDataField(property, value)) { var itemData = this._getItemData($item), index = $item.data(this._itemIndexKey()); this._renderItem(index, itemData, null, $item) } }, _optionChanged: function(args) { if ("items" === args.name) { var matches = args.fullName.match(ITEM_PATH_REGEX); if (matches && matches.length) { var property = matches[matches.length - 1], itemPath = args.fullName.replace("." + property, ""), item = this.option(itemPath); this._itemOptionChanged(item, property, args.value, args.previousValue); return } } switch (args.name) { case "items": case "_itemAttributes": case "itemTemplateProperty": this._cleanRenderedItems(); this._invalidate(); break; case "dataSource": this.option("items", []); this._refreshDataSource(); this._renderEmptyMessage(); break; case "noDataText": this._renderEmptyMessage(); break; case "itemTemplate": this._invalidate(); break; case "onItemRendered": this._createItemRenderAction(); break; case "onItemClick": break; case "onItemHold": case "itemHoldTimeout": this._attachHoldEvent(); break; case "onItemContextMenu": this._attachContextMenuEvent(); break; case "onFocusedItemChanged": this.onFocusedItemChanged = this._createActionByOption("onFocusedItemChanged"); break; case "selectOnFocus": case "loopItemFocus": case "focusOnSelectedItem": break; case "focusedElement": this._removeFocusedItem(args.previousValue); this._setFocusedItem(args.value); break; case "visibleExpr": case "disabledExpr": this._invalidate(); break; default: this.callBase(args) } }, _loadNextPage: function() { var dataSource = this._dataSource; this._expectNextPageLoading(); dataSource.pageIndex(1 + dataSource.pageIndex()); return dataSource.load() }, _expectNextPageLoading: function() { this._startIndexForAppendedItems = 0 }, _expectLastItemLoading: function() { this._startIndexForAppendedItems = -1 }, _forgetNextPageLoading: function() { this._startIndexForAppendedItems = null }, _dataSourceChangedHandler: function(newItems) { var items = this.option("items"); if (this._initialized && items && this._shouldAppendItems()) { this._renderedItemsCount = items.length; if (!this._isLastPage() || this._startIndexForAppendedItems !== -1) { this.option().items = items.concat(newItems.slice(this._startIndexForAppendedItems)) } this._forgetNextPageLoading(); this._renderContent(); this._renderFocusTarget() } else { this.option("items", newItems) } }, _dataSourceLoadErrorHandler: function() { this._forgetNextPageLoading(); this.option("items", this.option("items")) }, _shouldAppendItems: function() { return null != this._startIndexForAppendedItems && this._allowDynamicItemsAppend() }, _allowDynamicItemsAppend: function() { return false }, _clean: function() { this._cleanFocusState(); this._cleanItemContainer() }, _cleanItemContainer: function() { this._itemContainer().empty() }, _dispose: function() { this.callBase(); clearTimeout(this._itemFocusTimeout) }, _refresh: function() { this._cleanRenderedItems(); this.callBase.apply(this, arguments) }, _itemContainer: function() { return this.element() }, _itemClass: function() { return ITEM_CLASS }, _itemContentClass: function() { return this._itemClass() + CONTENT_CLASS_POSTFIX }, _selectedItemClass: function() { return SELECTED_ITEM_CLASS }, _itemResponseWaitClass: function() { return ITEM_RESPONSE_WAIT_CLASS }, _itemSelector: function() { return "." + this._itemClass() }, _itemDataKey: function() { return ITEM_DATA_KEY }, _itemIndexKey: function() { return ITEM_INDEX_KEY }, _itemElements: function() { return this._itemContainer().find(this._itemSelector()) }, _render: function() { this.onFocusedItemChanged = this._createActionByOption("onFocusedItemChanged"); this.callBase(); this.element().addClass(COLLECTION_CLASS); this._attachClickEvent(); this._attachHoldEvent(); this._attachContextMenuEvent() }, _attachClickEvent: function() { var itemSelector = this._itemSelector(), clickEventNamespace = eventUtils.addNamespace(clickEvent.name, this.NAME), pointerDownEventNamespace = eventUtils.addNamespace(pointerEvents.down, this.NAME), that = this; var pointerDownAction = new Action(function(args) { var event = args.event; that._itemPointerDownHandler(event) }); this._itemContainer().off(clickEventNamespace, itemSelector).off(pointerDownEventNamespace, itemSelector).on(clickEventNamespace, itemSelector, function(e) { this._itemClickHandler(e) }.bind(this)).on(pointerDownEventNamespace, itemSelector, function(e) { pointerDownAction.execute({ element: $(e.target), event: e }) }) }, _itemClickHandler: function(e, args, config) { this._itemJQueryEventHandler(e, "onItemClick", args, config) }, _itemPointerDownHandler: function(e) { if (!this.option("focusStateEnabled")) { return } this._itemFocusHandler = function() { clearTimeout(this._itemFocusTimeout); this._itemFocusHandler = null; if (e.isDefaultPrevented()) { return } var $target = $(e.target), $closestItem = $target.closest(this._itemElements()), $closestFocusable = this._closestFocusable($target); if ($closestItem.length && inArray($closestFocusable.get(0), this._focusTarget()) !== -1) { this.option("focusedElement", $closestItem) } }.bind(this); this._itemFocusTimeout = setTimeout(this._forcePointerDownFocus.bind(this)) }, _closestFocusable: function($target) { if ($target.is(selectors.focusable)) { return $target } else { $target = $target.parent(); while ($target.length) { if ($target.is(selectors.focusable)) { return $target } $target = $target.parent() } } }, _forcePointerDownFocus: function() { this._itemFocusHandler && this._itemFocusHandler() }, _updateFocusState: function() { this.callBase.apply(this, arguments); this._forcePointerDownFocus() }, _attachHoldEvent: function() { var $itemContainer = this._itemContainer(), itemSelector = this._itemSelector(), eventName = eventUtils.addNamespace(holdEvent.name, this.NAME); $itemContainer.off(eventName, itemSelector); $itemContainer.on(eventName, itemSelector, { timeout: this._getHoldTimeout() }, this._itemHoldHandler.bind(this)) }, _getHoldTimeout: function() { return this.option("itemHoldTimeout") }, _shouldFireHoldEvent: function() { return this.hasActionSubscription("onItemHold") }, _itemHoldHandler: function(e) { if (this._shouldFireHoldEvent()) { this._itemJQueryEventHandler(e, "onItemHold") } else { e.cancel = true } }, _attachContextMenuEvent: function() { var $itemContainer = this._itemContainer(), itemSelector = this._itemSelector(), eventName = eventUtils.addNamespace(contextMenuEvent.name, this.NAME); $itemContainer.off(eventName, itemSelector); $itemContainer.on(eventName, itemSelector, this._itemContextMenuHandler.bind(this)) }, _shouldFireContextMenuEvent: function() { return this.hasActionSubscription("onItemContextMenu") }, _itemContextMenuHandler: function(e) { if (this._shouldFireContextMenuEvent()) { this._itemJQueryEventHandler(e, "onItemContextMenu") } else { e.cancel = true } }, _renderContentImpl: function() { var items = this.option("items") || []; if (this._renderedItemsCount) { this._renderItems(items.slice(this._renderedItemsCount)) } else { this._renderItems(items) } }, _renderItems: function(items) { if (items.length) { $.each(items, this._renderItem.bind(this)) } this._renderEmptyMessage() }, _renderItem: function(index, itemData, $container, $itemToReplace) { $container = $container || this._itemContainer(); var $itemFrame = this._renderItemFrame(index, itemData, $container, $itemToReplace); this._setElementData($itemFrame, itemData, index); $itemFrame.attr(this.option("_itemAttributes")); this._attachItemClickEvent(itemData, $itemFrame); var $itemContent = $itemFrame.find("." + ITEM_CONTENT_PLACEHOLDER_CLASS); $itemContent.removeClass(ITEM_CONTENT_PLACEHOLDER_CLASS); var renderContentPromise = this._renderItemContent({ index: index, itemData: itemData, container: $itemContent, contentClass: this._itemContentClass(), defaultTemplateName: this.option("itemTemplate") }); var that = this; when(renderContentPromise).done(function($itemContent) { that._postprocessRenderItem({ itemElement: $itemFrame, itemContent: $itemContent, itemData: itemData, itemIndex: index }); that._executeItemRenderAction(index, itemData, $itemFrame) }); return $itemFrame }, _attachItemClickEvent: function(itemData, $itemElement) { if (!itemData || !itemData.onClick) { return } $itemElement.on(clickEvent.name, function(e) { this._itemEventHandlerByHandler($itemElement, itemData.onClick, { jQueryEvent: e }) }.bind(this)) }, _renderItemContent: function(args) { var itemTemplateName = this._getItemTemplateName(args); var itemTemplate = this._getTemplate(itemTemplateName); this._addItemContentClasses(args); var $templateResult = this._createItemByTemplate(itemTemplate, args); if (!$templateResult.hasClass(TEMPLATE_WRAPPER_CLASS)) { return args.container } return this._renderItemContentByNode(args, $templateResult) }, _renderItemContentByNode: function(args, $node) { args.container.replaceWith($node); args.container = $node; this._addItemContentClasses(args); return $node }, _addItemContentClasses: function(args) { var classes = [ITEM_CLASS + CONTENT_CLASS_POSTFIX, args.contentClass]; args.container.addClass(classes.join(" ")) }, _renderItemFrame: function(index, itemData, $container, $itemToReplace) { var $itemFrame = $("<div>"); new this.constructor.ItemClass($itemFrame, this._itemOptions(), itemData || {}); if ($itemToReplace && $itemToReplace.length) { $itemToReplace.replaceWith($itemFrame) } else { $itemFrame.appendTo($container) } return $itemFrame }, _itemOptions: function() { var that = this; return { watchMethod: function() { return that.option("integrationOptions.watchMethod") }, fieldGetter: function(field) { var expr = that.option(field + "Expr"), getter = dataUtils.compileGetter(expr); return getter } } }, _postprocessRenderItem: commonUtils.noop, _executeItemRenderAction: function(index, itemData, itemElement) { this._getItemRenderAction()({ itemElement: itemElement, itemIndex: index, itemData: itemData }) }, _setElementData: function(element, data, index) { element.addClass([ITEM_CLASS, this._itemClass()].join(" ")).data(this._itemDataKey(), data).data(this._itemIndexKey(), index) }, _createItemRenderAction: function() { return this._itemRenderAction = this._createActionByOption("onItemRendered", { element: this.element(), excludeValidators: ["designMode", "disabled", "readOnly"], category: "rendering" }) }, _getItemRenderAction: function() { return this._itemRenderAction || this._createItemRenderAction() }, _getItemTemplateName: function(args) { var data = args.itemData, templateProperty = args.templateProperty || this.option("itemTemplateProperty"), template = data && data[templateProperty]; return template || args.defaultTemplateName }, _createItemByTemplate: function(itemTemplate, renderArgs) { return itemTemplate.render({ model: renderArgs.itemData, container: renderArgs.container, index: renderArgs.index }) }, _emptyMessageContainer: function() { return this._itemContainer() }, _renderEmptyMessage: function() { var noDataText = this.option("noDataText"), items = this.option("items"), hideNoData = !noDataText || items && items.length || this._isDataSourceLoading(); if (hideNoData && this._$noData) { this._$noData.remove(); this._$noData = null; this.setAria("label", void 0) } if (!hideNoData) { this._$noData = this._$noData || $("<div>").addClass("dx-empty-message"); this._$noData.appendTo(this._emptyMessageContainer()).html(noDataText); this.setAria("label", noDataText) } this.element().toggleClass(EMPTY_COLLECTION, !hideNoData) }, _itemJQueryEventHandler: function(jQueryEvent, handlerOptionName, actionArgs, actionConfig) { this._itemEventHandler(jQueryEvent.target, handlerOptionName, extend(actionArgs, { jQueryEvent: jQueryEvent }), actionConfig) }, _itemEventHandler: function(initiator, handlerOptionName, actionArgs, actionConfig) { var action = this._createActionByOption(handlerOptionName, extend({ validatingTargetName: "itemElement" }, actionConfig)); return this._itemEventHandlerImpl(initiator, action, actionArgs) }, _itemEventHandlerByHandler: function(initiator, handler, actionArgs, actionConfig) { var action = this._createAction(handler, extend({ validatingTargetName: "itemElement" }, actionConfig)); return this._itemEventHandlerImpl(initiator, action, actionArgs) }, _itemEventHandlerImpl: function(initiator, action, actionArgs) { var $itemElement = this._closestItemElement($(initiator)), args = extend({}, actionArgs); return action(extend(actionArgs, this._extendActionArgs($itemElement), args)) }, _extendActionArgs: function($itemElement) { return { itemElement: $itemElement, itemIndex: this._itemElements().index($itemElement), itemData: this._getItemData($itemElement) } }, _closestItemElement: function($element) { return $($element).closest(this._itemSelector()) }, _getItemData: function(itemElement) { return $(itemElement).data(this._itemDataKey()) }, getFocusedItemId: function() { if (!this._focusedItemId) { this._focusedItemId = "dx-" + new Guid } return this._focusedItemId }, itemElements: function() { return this._itemElements() }, itemsContainer: function() { return this._itemContainer() } }).include(DataHelperMixin); CollectionWidget.ItemClass = CollectionWidgetItem; module.exports = CollectionWidget }, /*!*************************!*\ !*** ./js/core/guid.js ***! \*************************/ function(module, exports, __webpack_require__) { var Class = __webpack_require__( /*! ./class */ 25); var Guid = Class.inherit({ ctor: function(value) { if (value) { value = String(value) } this._value = this._normalize(value || this._generate()) }, _normalize: function(value) { value = value.replace(/[^a-f0-9]/gi, "").toLowerCase(); while (value.length < 32) { value += "0" } return [value.substr(0, 8), value.substr(8, 4), value.substr(12, 4), value.substr(16, 4), value.substr(20, 12)].join("-") }, _generate: function() { var value = ""; for (var i = 0; i < 32; i++) { value += Math.round(15 * Math.random()).toString(16) } return value }, toString: function() { return this._value }, valueOf: function() { return this._value }, toJSON: function() { return this._value } }); module.exports = Guid }, /*!***************************!*\ !*** ./js/data_helper.js ***! \***************************/ function(module, exports, __webpack_require__) { var DataSource = __webpack_require__( /*! ./data/data_source/data_source */ 153).DataSource, extend = __webpack_require__( /*! ./core/utils/extend */ 11).extend, normalizeDataSourceOptions = __webpack_require__( /*! ./data/data_source/data_source */ 153).normalizeDataSourceOptions; var DATA_SOURCE_OPTIONS_METHOD = "_dataSourceOptions", DATA_SOURCE_CHANGED_METHOD = "_dataSourceChangedHandler", DATA_SOURCE_LOAD_ERROR_METHOD = "_dataSourceLoadErrorHandler", DATA_SOURCE_LOADING_CHANGED_METHOD = "_dataSourceLoadingChangedHandler", DATA_SOURCE_FROM_URL_LOAD_MODE_METHOD = "_dataSourceFromUrlLoadMode", SPECIFIC_DATA_SOURCE_OPTION = "_getSpecificDataSourceOption"; var DataHelperMixin = { postCtor: function() { this.on("disposing", function() { this._disposeDataSource() }.bind(this)) }, _refreshDataSource: function() { this._initDataSource(); this._loadDataSource() }, _initDataSource: function() { var widgetDataSourceOptions, dataSourceType, dataSourceOptions = SPECIFIC_DATA_SOURCE_OPTION in this ? this[SPECIFIC_DATA_SOURCE_OPTION]() : this.option("dataSource"); this._disposeDataSource(); if (dataSourceOptions) { if (dataSourceOptions instanceof DataSource) { this._isSharedDataSource = true; this._dataSource = dataSourceOptions } else { widgetDataSourceOptions = DATA_SOURCE_OPTIONS_METHOD in this ? this[DATA_SOURCE_OPTIONS_METHOD]() : {}; dataSourceType = this._dataSourceType ? this._dataSourceType() : DataSource; dataSourceOptions = normalizeDataSourceOptions(dataSourceOptions, { fromUrlLoadMode: DATA_SOURCE_FROM_URL_LOAD_MODE_METHOD in this && this[DATA_SOURCE_FROM_URL_LOAD_MODE_METHOD]() }); this._dataSource = new dataSourceType(extend(true, {}, widgetDataSourceOptions, dataSourceOptions)) } this._addDataSourceHandlers() } }, _addDataSourceHandlers: function() { if (DATA_SOURCE_CHANGED_METHOD in this) { this._addDataSourceChangeHandler() } if (DATA_SOURCE_LOAD_ERROR_METHOD in this) { this._addDataSourceLoadErrorHandler() } if (DATA_SOURCE_LOADING_CHANGED_METHOD in this) { this._addDataSourceLoadingChangedHandler() } this._addReadyWatcher() }, _addReadyWatcher: function() { this._dataSource.on("loadingChanged", function(isLoading) { this._ready && this._ready(!isLoading) }.bind(this)) }, _addDataSourceChangeHandler: function() { var dataSource = this._dataSource; this._proxiedDataSourceChangedHandler = function() { this[DATA_SOURCE_CHANGED_METHOD](dataSource.items()) }.bind(this); dataSource.on("changed", this._proxiedDataSourceChangedHandler) }, _addDataSourceLoadErrorHandler: function() { this._proxiedDataSourceLoadErrorHandler = this[DATA_SOURCE_LOAD_ERROR_METHOD].bind(this); this._dataSource.on("loadError", this._proxiedDataSourceLoadErrorHandler) }, _addDataSourceLoadingChangedHandler: function() { this._proxiedDataSourceLoadingChangedHandler = this[DATA_SOURCE_LOADING_CHANGED_METHOD].bind(this); this._dataSource.on("loadingChanged", this._proxiedDataSourceLoadingChangedHandler) }, _loadDataSource: function() { if (this._dataSource) { var dataSource = this._dataSource; if (dataSource.isLoaded()) { this._proxiedDataSourceChangedHandler && this._proxiedDataSourceChangedHandler() } else { dataSource.load() } } }, _loadSingle: function(key, value) { key = "this" === key ? this._dataSource.key() || "this" : key; return this._dataSource.loadSingle(key, value) }, _isLastPage: function() { return !this._dataSource || this._dataSource.isLastPage() || !this._dataSource._pageSize }, _isDataSourceLoading: function() { return this._dataSource && this._dataSource.isLoading() }, _disposeDataSource: function() { if (this._dataSource) { if (this._isSharedDataSource) { delete this._isSharedDataSource; this._proxiedDataSourceChangedHandler && this._dataSource.off("changed", this._proxiedDataSourceChangedHandler); this._proxiedDataSourceLoadErrorHandler && this._dataSource.off("loadError", this._proxiedDataSourceLoadErrorHandler); this._proxiedDataSourceLoadingChangedHandler && this._dataSource.off("loadingChanged", this._proxiedDataSourceLoadingChangedHandler) } else { this._dataSource.dispose() } delete this._dataSource; delete this._proxiedDataSourceChangedHandler; delete this._proxiedDataSourceLoadErrorHandler; delete this._proxiedDataSourceLoadingChangedHandler } }, getDataSource: function() { return this._dataSource || null } }; module.exports = DataHelperMixin }, /*!********************************************!*\ !*** ./js/data/data_source/data_source.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), dataUtils = __webpack_require__( /*! ../utils */ 137), Store = __webpack_require__( /*! ../abstract_store */ 154), ArrayStore = __webpack_require__( /*! ../array_store */ 158), CustomStore = __webpack_require__( /*! ../custom_store */ 162), EventsMixin = __webpack_require__( /*! ../../core/events_mixin */ 51), errors = __webpack_require__( /*! ../errors */ 155).errors, array = __webpack_require__( /*! ../../core/utils/array */ 26), queue = __webpack_require__( /*! ../../core/utils/queue */ 62), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when, __isString = commonUtils.isString, __isNumber = commonUtils.isNumeric, __isBoolean = commonUtils.isBoolean, __isDefined = commonUtils.isDefined; var CANCELED_TOKEN = "canceled"; function OperationManager() { this._counter = -1; this._deferreds = {} } OperationManager.prototype.constructor = OperationManager; OperationManager.prototype.add = function(deferred) { this._counter += 1; this._deferreds[this._counter] = deferred; return this._counter }; OperationManager.prototype.remove = function(operationId) { return delete this._deferreds[operationId] }; OperationManager.prototype.cancel = function(operationId) { if (operationId in this._deferreds) { this._deferreds[operationId].reject(CANCELED_TOKEN); return true } return false }; var operationManager = new OperationManager; function isPending(deferred) { return "pending" === deferred.state() } function normalizeDataSourceOptions(options, normalizationOptions) { var store; function createCustomStoreFromLoadFunc() { var storeConfig = {}; $.each(["useDefaultSearch", "key", "load", "loadMode", "cacheRawData", "byKey", "lookup", "totalCount", "insert", "update", "remove"], function() { storeConfig[this] = options[this]; delete options[this] }); return new CustomStore(storeConfig) } function createStoreFromConfig(storeConfig) { var alias = storeConfig.type; delete storeConfig.type; return Store.create(alias, storeConfig) } function createCustomStoreFromUrl(url) { return new CustomStore({ load: function() { return $.getJSON(url) }, loadMode: normalizationOptions && normalizationOptions.fromUrlLoadMode }) } if ("string" === typeof options) { options = { paginate: false, store: createCustomStoreFromUrl(options) } } if (void 0 === options) { options = [] } if (Array.isArray(options) || options instanceof Store) { options = { store: options } } else { options = extend({}, options) } if (void 0 === options.store) { options.store = [] } store = options.store; if ("load" in options) { store = createCustomStoreFromLoadFunc() } else { if (Array.isArray(store)) { store = new ArrayStore(store) } else { if (typeUtils.isPlainObject(store)) { store = createStoreFromConfig(extend({}, store)) } } } options.store = store; return options } function normalizeStoreLoadOptionAccessorArguments(originalArguments) { switch (originalArguments.length) { case 0: return; case 1: return originalArguments[0] } return $.makeArray(originalArguments) } function generateStoreLoadOptionAccessor(optionName) { return function() { var args = normalizeStoreLoadOptionAccessorArguments(arguments); if (void 0 === args) { return this._storeLoadOptions[optionName] } this._storeLoadOptions[optionName] = args } } function mapDataRespectingGrouping(items, mapper, groupInfo) { function mapRecursive(items, level) { if (!Array.isArray(items)) { return items } return level ? mapGroup(items, level) : $.map(items, mapper) } function mapGroup(group, level) { return $.map(group, function(item) { var result = { key: item.key, items: mapRecursive(item.items, level - 1) }; if ("aggregates" in item) { result.aggregates = item.aggregates } return result }) } return mapRecursive(items, groupInfo ? dataUtils.normalizeSortingInfo(groupInfo).length : 0) } var DataSource = Class.inherit({ ctor: function(options) { var that = this; options = normalizeDataSourceOptions(options); this._store = options.store; this._storeLoadOptions = this._extractLoadOptions(options); this._mapFunc = options.map; this._postProcessFunc = options.postProcess; this._pageIndex = void 0 !== options.pageIndex ? options.pageIndex : 0; this._pageSize = void 0 !== options.pageSize ? options.pageSize : 20; this._loadingCount = 0; this._loadQueue = this._createLoadQueue(); this._searchValue = "searchValue" in options ? options.searchValue : null; this._searchOperation = options.searchOperation || "contains"; this._searchExpr = options.searchExpr; this._paginate = options.paginate; $.each(["onChanged", "onLoadError", "onLoadingChanged", "onCustomizeLoadResult", "onCustomizeStoreLoadOptions"], function(_, optionName) { if (optionName in options) { that.on(optionName.substr(2, 1).toLowerCase() + optionName.substr(3), options[optionName]) } }); this._init() }, _init: function() { this._items = []; this._userData = {}; this._totalCount = -1; this._isLoaded = false; if (!__isDefined(this._paginate)) { this._paginate = !this.group() } this._isLastPage = !this._paginate }, dispose: function() { this._disposeEvents(); delete this._store; if (this._delayedLoadTask) { this._delayedLoadTask.abort() } this._disposed = true }, _extractLoadOptions: function(options) { var result = {}, names = ["sort", "filter", "select", "group", "requireTotalCount"], customNames = this._store._customLoadOptions(); if (customNames) { names = names.concat(customNames) } $.each(names, function() { result[this] = options[this] }); return result }, loadOptions: function() { return this._storeLoadOptions }, items: function() { return this._items }, pageIndex: function(newIndex) { if (!__isNumber(newIndex)) { return this._pageIndex } this._pageIndex = newIndex; this._isLastPage = !this._paginate }, paginate: function(value) { if (!__isBoolean(value)) { return this._paginate } if (this._paginate !== value) { this._paginate = value; this.pageIndex(0) } }, pageSize: function(value) { if (!__isNumber(value)) { return this._pageSize } this._pageSize = value }, isLastPage: function() { return this._isLastPage }, sort: generateStoreLoadOptionAccessor("sort"), filter: function() { var newFilter = normalizeStoreLoadOptionAccessorArguments(arguments); if (void 0 === newFilter) { return this._storeLoadOptions.filter } this._storeLoadOptions.filter = newFilter; this.pageIndex(0) }, group: generateStoreLoadOptionAccessor("group"), select: generateStoreLoadOptionAccessor("select"), requireTotalCount: function(value) { if (!__isBoolean(value)) { return this._storeLoadOptions.requireTotalCount } this._storeLoadOptions.requireTotalCount = value }, searchValue: function(value) { if (arguments.length < 1) { return this._searchValue } this._searchValue = value; this.pageIndex(0) }, searchOperation: function(op) { if (!__isString(op)) { return this._searchOperation } this._searchOperation = op; this.pageIndex(0) }, searchExpr: function(expr) { var argc = arguments.length; if (0 === argc) { return this._searchExpr } if (argc > 1) { expr = $.makeArray(arguments) } this._searchExpr = expr; this.pageIndex(0) }, store: function() { return this._store }, key: function() { return this._store && this._store.key() }, totalCount: function() { return this._totalCount }, isLoaded: function() { return this._isLoaded }, isLoading: function() { return this._loadingCount > 0 }, _createLoadQueue: function() { return queue.create() }, _changeLoadingCount: function(increment) { var newLoading, oldLoading = this.isLoading(); this._loadingCount += increment; newLoading = this.isLoading(); if (oldLoading ^ newLoading) { this.fireEvent("loadingChanged", [newLoading]) } }, _scheduleLoadCallbacks: function(deferred) { var that = this; that._changeLoadingCount(1); deferred.always(function() { that._changeLoadingCount(-1) }) }, _scheduleFailCallbacks: function(deferred) { var that = this; deferred.fail(function() { if (arguments[0] === CANCELED_TOKEN) { return } that.fireEvent("loadError", arguments) }) }, _scheduleChangedCallbacks: function(deferred) { var that = this; deferred.done(function() { that.fireEvent("changed") }) }, loadSingle: function(propName, propValue) { var that = this; var d = $.Deferred(), key = this.key(), store = this._store, options = this._createStoreLoadOptions(), handleDone = function(data) { if (!__isDefined(data) || array.isEmpty(data)) { d.reject(new errors.Error("E4009")) } else { d.resolve(that._applyMapFunction($.makeArray(data))[0]) } }; this._scheduleFailCallbacks(d); if (arguments.length < 2) { propValue = propName; propName = key } delete options.skip; delete options.group; delete options.refresh; delete options.pageIndex; delete options.searchString; function shouldForceByKey() { return store instanceof CustomStore && !store._byKeyViaLoad() }(function() { if (propName === key || shouldForceByKey()) { return store.byKey(propValue, options) } options.take = 1; options.filter = options.filter ? [options.filter, [propName, propValue]] : [propName, propValue]; return store.load(options) })().fail(d.reject).done(handleDone); return d.promise() }, load: function() { var loadOperation, that = this, d = $.Deferred(); function loadTask() { if (that._disposed) { return } if (!isPending(d)) { return } return that._loadFromStore(loadOperation, d) } this._scheduleLoadCallbacks(d); this._scheduleFailCallbacks(d); this._scheduleChangedCallbacks(d); loadOperation = this._createLoadOperation(d); this.fireEvent("customizeStoreLoadOptions", [loadOperation]); this._loadQueue.add(function() { if ("number" === typeof loadOperation.delay) { that._delayedLoadTask = commonUtils.executeAsync(loadTask, loadOperation.delay) } else { loadTask() } return d.promise() }); return d.promise({ operationId: loadOperation.operationId }) }, _createLoadOperation: function(deferred) { var id = operationManager.add(deferred), options = this._createStoreLoadOptions(); deferred.always(function() { operationManager.remove(id) }); return { operationId: id, storeLoadOptions: options } }, reload: function() { var store = this.store(); if (store instanceof CustomStore) { store.clearRawDataCache() } this._init(); return this.load() }, cancel: function(operationId) { return operationManager.cancel(operationId) }, _addSearchOptions: function(storeLoadOptions) { if (this._disposed) { return } if (this.store()._useDefaultSearch) { this._addSearchFilter(storeLoadOptions) } else { storeLoadOptions.searchOperation = this._searchOperation; storeLoadOptions.searchValue = this._searchValue; storeLoadOptions.searchExpr = this._searchExpr } }, _createStoreLoadOptions: function() { var result = extend({}, this._storeLoadOptions); this._addSearchOptions(result); if (this._paginate) { if (this._pageSize) { result.skip = this._pageIndex * this._pageSize; result.take = this._pageSize } } result.userData = this._userData; return result }, _addSearchFilter: function(storeLoadOptions) { var value = this._searchValue, op = this._searchOperation, selector = this._searchExpr, searchFilter = []; if (!value) { return } if (!selector) { selector = "this" } if (!Array.isArray(selector)) { selector = [selector] } $.each(selector, function(i, item) { if (searchFilter.length) { searchFilter.push("or") } searchFilter.push([item, op, value]) }); if (storeLoadOptions.filter) { storeLoadOptions.filter = [searchFilter, storeLoadOptions.filter] } else { storeLoadOptions.filter = searchFilter } }, _loadFromStore: function(loadOptions, pendingDeferred) { var that = this; function handleSuccess(data, extra) { function processResult() { var loadResult; if (data && !Array.isArray(data) && data.data) { extra = data; data = data.data } if (!Array.isArray(data)) { data = $.makeArray(data) } loadResult = extend({ data: data, extra: extra }, loadOptions); that.fireEvent("customizeLoadResult", [loadResult]); when(loadResult.data).done(function(data) { loadResult.data = data; that._processStoreLoadResult(loadResult, pendingDeferred) }).fail(pendingDeferred.reject) } if (that._disposed) { return } if (!isPending(pendingDeferred)) { return } processResult() } if (loadOptions.data) { return $.Deferred().resolve(loadOptions.data).done(handleSuccess) } return this.store().load(loadOptions.storeLoadOptions).done(handleSuccess).fail(pendingDeferred.reject) }, _processStoreLoadResult: function(loadResult, pendingDeferred) { var that = this, data = loadResult.data, extra = loadResult.extra, storeLoadOptions = loadResult.storeLoadOptions; function resolvePendingDeferred() { that._isLoaded = true; that._totalCount = isFinite(extra.totalCount) ? extra.totalCount : -1; return pendingDeferred.resolve(data, extra) } function proceedLoadingTotalCount() { that.store().totalCount(storeLoadOptions).done(function(count) { extra.totalCount = count; resolvePendingDeferred() }).fail(pendingDeferred.reject) } if (that._disposed) { return } data = that._applyPostProcessFunction(that._applyMapFunction(data)); if (!typeUtils.isPlainObject(extra)) { extra = {} } that._items = data; if (!data.length || !that._paginate || that._pageSize && data.length < that._pageSize) { that._isLastPage = true } if (storeLoadOptions.requireTotalCount && !isFinite(extra.totalCount)) { proceedLoadingTotalCount() } else { resolvePendingDeferred() } }, _applyMapFunction: function(data) { if (this._mapFunc) { return mapDataRespectingGrouping(data, this._mapFunc, this.group()) } return data }, _applyPostProcessFunction: function(data) { if (this._postProcessFunc) { return this._postProcessFunc(data) } return data } }).include(EventsMixin); exports.DataSource = DataSource; exports.normalizeDataSourceOptions = normalizeDataSourceOptions }, /*!***********************************!*\ !*** ./js/data/abstract_store.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), abstract = Class.abstract, EventsMixin = __webpack_require__( /*! ../core/events_mixin */ 51), errorsModule = __webpack_require__( /*! ./errors */ 155), dataUtils = __webpack_require__( /*! ./utils */ 137), compileGetter = __webpack_require__( /*! ../core/utils/data */ 50).compileGetter, storeHelper = __webpack_require__( /*! ./store_helper */ 156), queryByOptions = storeHelper.queryByOptions, storeImpl = {}; var Store = Class.inherit({ ctor: function(options) { var that = this; options = options || {}; $.each(["onLoaded", "onLoading", "onInserted", "onInserting", "onUpdated", "onUpdating", "onRemoved", "onRemoving", "onModified", "onModifying"], function(_, optionName) { if (optionName in options) { that.on(optionName.slice(2).toLowerCase(), options[optionName]) } }); this._key = options.key; this._errorHandler = options.errorHandler; this._useDefaultSearch = true }, _customLoadOptions: function() { return null }, key: function() { return this._key }, keyOf: function(obj) { if (!this._keyGetter) { this._keyGetter = compileGetter(this.key()) } return this._keyGetter(obj) }, _requireKey: function() { if (!this.key()) { throw errorsModule.errors.Error("E4005") } }, load: function(options) { var that = this; options = options || {}; this.fireEvent("loading", [options]); return this._withLock(this._loadImpl(options)).done(function(result) { that.fireEvent("loaded", [result, options]) }) }, _loadImpl: function(options) { return queryByOptions(this.createQuery(options), options).enumerate() }, _withLock: function(task) { var result = $.Deferred(); task.done(function() { var that = this, args = arguments; dataUtils.processRequestResultLock.promise().done(function() { result.resolveWith(that, args) }) }).fail(function() { result.rejectWith(this, arguments) }); return result }, createQuery: abstract, totalCount: function(options) { return this._totalCountImpl(options) }, _totalCountImpl: function(options) { return queryByOptions(this.createQuery(options), options, true).count() }, byKey: function(key, extraOptions) { return this._addFailHandlers(this._withLock(this._byKeyImpl(key, extraOptions))) }, _byKeyImpl: abstract, insert: function(values) { var that = this; that.fireEvent("modifying"); that.fireEvent("inserting", [values]); return that._addFailHandlers(that._insertImpl(values).done(function(callbackValues, callbackKey) { that.fireEvent("inserted", [callbackValues, callbackKey]); that.fireEvent("modified") })) }, _insertImpl: abstract, update: function(key, values) { var that = this; that.fireEvent("modifying"); that.fireEvent("updating", [key, values]); return that._addFailHandlers(that._updateImpl(key, values).done(function(callbackKey, callbackValues) { that.fireEvent("updated", [callbackKey, callbackValues]); that.fireEvent("modified") })) }, _updateImpl: abstract, remove: function(key) { var that = this; that.fireEvent("modifying"); that.fireEvent("removing", [key]); return that._addFailHandlers(that._removeImpl(key).done(function(callbackKey) { that.fireEvent("removed", [callbackKey]); that.fireEvent("modified") })) }, _removeImpl: abstract, _addFailHandlers: function(deferred) { return deferred.fail(this._errorHandler, errorsModule._errorHandler) } }).include(EventsMixin); Store.create = function(alias, options) { if (!(alias in storeImpl)) { throw errorsModule.errors.Error("E4020", alias) } return new storeImpl[alias](options) }; Store.inherit = function(inheritor) { return function(members, alias) { var type = inheritor.apply(this, [members]); if (alias) { storeImpl[alias] = type } return type } }(Store.inherit); module.exports = Store }, /*!***************************!*\ !*** ./js/data/errors.js ***! \***************************/ function(module, exports, __webpack_require__) { var errorUtils = __webpack_require__( /*! ../core/utils/error */ 8), coreErrors = __webpack_require__( /*! ../core/errors */ 7), handlers = {}; var errors = errorUtils(coreErrors.ERROR_MESSAGES, { E4000: "[DevExpress.data]: {0}", E4001: "Unknown aggregating function is detected: '{0}'", E4002: "Unsupported OData protocol version is used", E4003: "Unknown filter operation is used: {0}", E4004: "The thenby() method is called before the sortby() method", E4005: "Store requires a key expression for this operation", E4006: "ArrayStore 'data' option must be an array", E4007: "Compound keys cannot be auto-generated", E4008: "Attempt to insert an item with the a duplicated key", E4009: "Data item cannot be found", E4010: "CustomStore does not support creating queries", E4011: "Custom Store method is not implemented or is not a function: {0}", E4012: "Custom Store method returns an invalid value: {0}", E4013: "Local Store requires the 'name' configuration option is specified", E4014: "Unknown data type is specified for ODataStore: {0}", E4015: "Unknown entity name or alias is used: {0}", E4017: "Keys cannot be modified", E4018: "The server has returned a non-numeric value in a response to an item count request", E4019: "Mixing of group operators inside a single group of filter expression is not allowed", E4020: "Unknown store type is detected: {0}", E4021: "The server response does not provide the totalCount value", E4022: "The server response does not provide the groupCount value", W4000: "Data returned from the server has an incorrect structure", W4001: 'The {0} field is listed in both "keyType" and "fieldTypes". The value of "fieldTypes" is used.', W4002: "Data loading has failed for some cells due to the following error: {0}" }); function handleError(error) { var id = "E4000"; if (error && "__id" in error) { id = error.__id } errors.log(id, error) } var errorHandler = null; var _errorHandler = function(error) { handleError(error); if (handlers.errorHandler) { handlers.errorHandler(error) } }; handlers = { errors: errors, errorHandler: errorHandler, _errorHandler: _errorHandler }; module.exports = handlers }, /*!*********************************!*\ !*** ./js/data/store_helper.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), grep = __webpack_require__( /*! ../core/utils/common */ 14).grep, extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, arrayQuery = __webpack_require__( /*! ./array_query */ 157), normalizeSortingInfo = __webpack_require__( /*! ./utils */ 137).normalizeSortingInfo; function multiLevelGroup(query, groupInfo) { query = query.groupBy(groupInfo[0].selector); if (groupInfo.length > 1) { query = query.select(function(g) { return extend({}, g, { items: multiLevelGroup(arrayQuery(g.items), groupInfo.slice(1)).toArray() }) }) } return query } function arrangeSortingInfo(groupInfo, sortInfo) { var filteredGroup = []; $.each(groupInfo, function(_, group) { var collision = grep(sortInfo, function(sort) { return group.selector === sort.selector }); if (collision.length < 1) { filteredGroup.push(group) } }); return filteredGroup.concat(sortInfo) } function queryByOptions(query, options, isCountQuery) { options = options || {}; var filter = options.filter, sort = options.sort, select = options.select, group = options.group, skip = options.skip, take = options.take; if (filter) { query = query.filter(filter) } if (group) { group = normalizeSortingInfo(group) } if (!isCountQuery) { if (sort || group) { sort = normalizeSortingInfo(sort || []); if (group) { sort = arrangeSortingInfo(group, sort) } $.each(sort, function(index) { query = query[index ? "thenBy" : "sortBy"](this.selector, this.desc) }) } if (select) { query = query.select(select) } } if (group) { query = multiLevelGroup(query, group) } if (!isCountQuery) { if (take || skip) { query = query.slice(skip || 0, take) } } return query } module.exports = { multiLevelGroup: multiLevelGroup, arrangeSortingInfo: arrangeSortingInfo, queryByOptions: queryByOptions } }, /*!********************************!*\ !*** ./js/data/array_query.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), compileGetter = __webpack_require__( /*! ../core/utils/data */ 50).compileGetter, toComparable = __webpack_require__( /*! ../core/utils/data */ 50).toComparable, errorsModule = __webpack_require__( /*! ./errors */ 155), dataUtils = __webpack_require__( /*! ./utils */ 137); var Iterator = Class.inherit({ toArray: function() { var result = []; this.reset(); while (this.next()) { result.push(this.current()) } return result }, countable: function() { return false } }); var ArrayIterator = Iterator.inherit({ ctor: function(array) { this.array = array; this.index = -1 }, next: function() { if (this.index + 1 < this.array.length) { this.index++; return true } return false }, current: function() { return this.array[this.index] }, reset: function() { this.index = -1 }, toArray: function() { return this.array.slice(0) }, countable: function() { return true }, count: function() { return this.array.length } }); var WrappedIterator = Iterator.inherit({ ctor: function(iter) { this.iter = iter }, next: function() { return this.iter.next() }, current: function() { return this.iter.current() }, reset: function() { return this.iter.reset() } }); var MapIterator = WrappedIterator.inherit({ ctor: function(iter, mapper) { this.callBase(iter); this.index = -1; this.mapper = mapper }, current: function() { return this.mapper(this.callBase(), this.index) }, next: function() { var hasNext = this.callBase(); if (hasNext) { this.index++ } return hasNext } }); var SortIterator = Iterator.inherit({ ctor: function(iter, getter, desc) { if (!(iter instanceof MapIterator)) { iter = new MapIterator(iter, this._wrap) } this.iter = iter; this.rules = [{ getter: getter, desc: desc }] }, thenBy: function(getter, desc) { var result = new SortIterator(this.sortedIter || this.iter, getter, desc); if (!this.sortedIter) { result.rules = this.rules.concat(result.rules) } return result }, next: function() { this._ensureSorted(); return this.sortedIter.next() }, current: function() { this._ensureSorted(); return this.sortedIter.current() }, reset: function() { delete this.sortedIter }, countable: function() { return this.sortedIter || this.iter.countable() }, count: function() { if (this.sortedIter) { return this.sortedIter.count() } return this.iter.count() }, _ensureSorted: function() { var that = this; if (that.sortedIter) { return } $.each(that.rules, function() { this.getter = compileGetter(this.getter) }); that.sortedIter = new MapIterator(new ArrayIterator(this.iter.toArray().sort(function(x, y) { return that._compare(x, y) })), that._unwrap) }, _wrap: function(record, index) { return { index: index, value: record } }, _unwrap: function(wrappedItem) { return wrappedItem.value }, _compare: function(x, y) { var xIndex = x.index, yIndex = y.index; x = x.value; y = y.value; if (x === y) { return xIndex - yIndex } for (var i = 0, rulesCount = this.rules.length; i < rulesCount; i++) { var rule = this.rules[i], xValue = toComparable(rule.getter(x)), yValue = toComparable(rule.getter(y)), factor = rule.desc ? -1 : 1; if (null === xValue && null !== yValue) { return -factor } if (null !== xValue && null === yValue) { return factor } if (void 0 === xValue && void 0 !== yValue) { return factor } if (void 0 !== xValue && void 0 === yValue) { return -factor } if (xValue < yValue) { return -factor } if (xValue > yValue) { return factor } } return xIndex - yIndex } }); var compileCriteria = function() { var compileGroup = function(crit) { var groupOperator, nextGroupOperator, idx = 0, bag = [], ops = []; $.each(crit, function() { if (Array.isArray(this) || commonUtils.isFunction(this)) { if (bag.length > 1 && groupOperator !== nextGroupOperator) { throw new errorsModule.errors.Error("E4019") } ops.push(compileCriteria(this)); bag.push("op[" + idx + "](d)"); idx++; groupOperator = nextGroupOperator; nextGroupOperator = "&&" } else { nextGroupOperator = dataUtils.isConjunctiveOperator(this) ? "&&" : "||" } }); return new Function("op", "return function(d) { return " + bag.join(" " + groupOperator + " ") + " }")(ops) }; var toString = function(value) { return commonUtils.isDefined(value) ? value.toString() : "" }; var compileBinary = function(crit) { crit = dataUtils.normalizeBinaryCriterion(crit); var getter = compileGetter(crit[0]), op = crit[1], value = crit[2]; value = toComparable(value); switch (op.toLowerCase()) { case "=": return compileEquals(getter, value); case "<>": return compileEquals(getter, value, true); case ">": return function(obj) { return toComparable(getter(obj)) > value }; case "<": return function(obj) { return toComparable(getter(obj)) < value }; case ">=": return function(obj) { return toComparable(getter(obj)) >= value }; case "<=": return function(obj) { return toComparable(getter(obj)) <= value }; case "startswith": return function(obj) { return 0 === toComparable(toString(getter(obj))).indexOf(value) }; case "endswith": return function(obj) { var getterValue = toComparable(toString(getter(obj))), searchValue = toString(value); if (getterValue.length < searchValue.length) { return false } return getterValue.lastIndexOf(value) === getterValue.length - value.length }; case "contains": return function(obj) { return toComparable(toString(getter(obj))).indexOf(value) > -1 }; case "notcontains": return function(obj) { return toComparable(toString(getter(obj))).indexOf(value) === -1 } } throw errorsModule.errors.Error("E4003", op) }; function compileEquals(getter, value, negate) { return function(obj) { obj = toComparable(getter(obj)); var result = useStrictComparison(value) ? obj === value : obj == value; if (negate) { result = !result } return result } } function useStrictComparison(value) { return "" === value || 0 === value || false === value } function compileUnary(crit) { var op = crit[0], criteria = compileCriteria(crit[1]); if ("!" === op) { return function(obj) { return !criteria(obj) } } throw errorsModule.errors.Error("E4003", op) } return function(crit) { if (commonUtils.isFunction(crit)) { return crit } if (Array.isArray(crit[0])) { return compileGroup(crit) } if (dataUtils.isUnaryOperation(crit)) { return compileUnary(crit) } return compileBinary(crit) } }(); var FilterIterator = WrappedIterator.inherit({ ctor: function(iter, criteria) { this.callBase(iter); this.criteria = compileCriteria(criteria) }, next: function() { while (this.iter.next()) { if (this.criteria(this.current())) { return true } } return false } }); var GroupIterator = Iterator.inherit({ ctor: function(iter, getter) { this.iter = iter; this.getter = getter }, next: function() { this._ensureGrouped(); return this.groupedIter.next() }, current: function() { this._ensureGrouped(); return this.groupedIter.current() }, reset: function() { delete this.groupedIter }, countable: function() { return !!this.groupedIter }, count: function() { return this.groupedIter.count() }, _ensureGrouped: function() { if (this.groupedIter) { return } var hash = {}, keys = [], iter = this.iter, getter = compileGetter(this.getter); iter.reset(); while (iter.next()) { var current = iter.current(), key = getter(current); if (key in hash) { hash[key].push(current) } else { hash[key] = [current]; keys.push(key) } } this.groupedIter = new ArrayIterator($.map(keys, function(key) { return { key: key, items: hash[key] } })) } }); var SelectIterator = WrappedIterator.inherit({ ctor: function(iter, getter) { this.callBase(iter); this.getter = compileGetter(getter) }, current: function() { return this.getter(this.callBase()) }, countable: function() { return this.iter.countable() }, count: function() { return this.iter.count() } }); var SliceIterator = WrappedIterator.inherit({ ctor: function(iter, skip, take) { this.callBase(iter); this.skip = Math.max(0, skip); this.take = Math.max(0, take); this.pos = 0 }, next: function() { if (this.pos >= this.skip + this.take) { return false } while (this.pos < this.skip && this.iter.next()) { this.pos++ } this.pos++; return this.iter.next() }, reset: function() { this.callBase(); this.pos = 0 }, countable: function() { return this.iter.countable() }, count: function() { return Math.min(this.iter.count() - this.skip, this.take) } }); var arrayQueryImpl = function(iter, queryOptions) { queryOptions = queryOptions || {}; if (!(iter instanceof Iterator)) { iter = new ArrayIterator(iter) } var handleError = function(error) { var handler = queryOptions.errorHandler; if (handler) { handler(error) } errorsModule._errorHandler(error) }; var aggregateCore = function(aggregator) { var seed, d = $.Deferred().fail(handleError), step = aggregator.step, finalize = aggregator.finalize; try { iter.reset(); if ("seed" in aggregator) { seed = aggregator.seed } else { seed = iter.next() ? iter.current() : NaN } var accumulator = seed; while (iter.next()) { accumulator = step(accumulator, iter.current()) } d.resolve(finalize ? finalize(accumulator) : accumulator) } catch (x) { d.reject(x) } return d.promise() }; var aggregate = function(seed, step, finalize) { if (arguments.length < 2) { return aggregateCore({ step: arguments[0] }) } return aggregateCore({ seed: seed, step: step, finalize: finalize }) }; var standardAggregate = function(name) { return aggregateCore(dataUtils.aggregators[name]) }; var select = function(getter) { if (!commonUtils.isFunction(getter) && !Array.isArray(getter)) { getter = $.makeArray(arguments) } return chainQuery(new SelectIterator(iter, getter)) }; var selectProp = function(name) { return select(compileGetter(name)) }; var chainQuery = function(iter) { return arrayQueryImpl(iter, queryOptions) }; return { toArray: function() { return iter.toArray() }, enumerate: function() { var d = $.Deferred().fail(handleError); try { d.resolve(iter.toArray()) } catch (x) { d.reject(x) } return d.promise() }, sortBy: function(getter, desc) { return chainQuery(new SortIterator(iter, getter, desc)) }, thenBy: function(getter, desc) { if (iter instanceof SortIterator) { return chainQuery(iter.thenBy(getter, desc)) } throw errorsModule.errors.Error("E4004") }, filter: function(criteria) { if (!Array.isArray(criteria)) { criteria = $.makeArray(arguments) } return chainQuery(new FilterIterator(iter, criteria)) }, slice: function(skip, take) { if (void 0 === take) { take = Number.MAX_VALUE } return chainQuery(new SliceIterator(iter, skip, take)) }, select: select, groupBy: function(getter) { return chainQuery(new GroupIterator(iter, getter)) }, aggregate: aggregate, count: function() { if (iter.countable()) { var d = $.Deferred().fail(handleError); try { d.resolve(iter.count()) } catch (x) { d.reject(x) } return d.promise() } return standardAggregate("count") }, sum: function(getter) { if (getter) { return selectProp(getter).sum() } return standardAggregate("sum") }, min: function(getter) { if (getter) { return selectProp(getter).min() } return standardAggregate("min") }, max: function(getter) { if (getter) { return selectProp(getter).max() } return standardAggregate("max") }, avg: function(getter) { if (getter) { return selectProp(getter).avg() } return standardAggregate("avg") } } }; module.exports = arrayQueryImpl }, /*!********************************!*\ !*** ./js/data/array_store.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, typeUtils = __webpack_require__( /*! ../core/utils/type */ 12), Guid = __webpack_require__( /*! ../core/guid */ 151), objectUtils = __webpack_require__( /*! ../core/utils/object */ 27), keysEqual = __webpack_require__( /*! ./utils */ 137).keysEqual, Query = __webpack_require__( /*! ./query */ 159), errors = __webpack_require__( /*! ./errors */ 155).errors, Store = __webpack_require__( /*! ./abstract_store */ 154); var hasKey = function(target, keyOrKeys) { var key, keys = $.makeArray(keyOrKeys); while (keys.length) { key = keys.shift(); if (key in target) { return true } } return false }; var trivialPromise = function() { var d = $.Deferred(); return d.resolve.apply(d, arguments).promise() }; var rejectedPromise = function() { var d = $.Deferred(); return d.reject.apply(d, arguments).promise() }; var ArrayStore = Store.inherit({ ctor: function(options) { if (Array.isArray(options)) { options = { data: options } } else { options = options || {} } this.callBase(options); var initialArray = options.data; if (initialArray && !Array.isArray(initialArray)) { throw errors.Error("E4006") } this._array = initialArray || [] }, createQuery: function() { return Query(this._array, { errorHandler: this._errorHandler }) }, _byKeyImpl: function(key) { var index = this._indexByKey(key); if (index === -1) { return rejectedPromise(errors.Error("E4009")) } return trivialPromise(this._array[index]) }, _insertImpl: function(values) { var keyValue, obj, keyExpr = this.key(); if (typeUtils.isPlainObject(values)) { obj = extend({}, values) } else { obj = values } if (keyExpr) { keyValue = this.keyOf(obj); if (void 0 === keyValue || "object" === typeof keyValue && typeUtils.isEmptyObject(keyValue)) { if (Array.isArray(keyExpr)) { throw errors.Error("E4007") } keyValue = obj[keyExpr] = String(new Guid) } else { if (void 0 !== this._array[this._indexByKey(keyValue)]) { return rejectedPromise(errors.Error("E4008")) } } } else { keyValue = obj } this._array.push(obj); return trivialPromise(values, keyValue) }, _updateImpl: function(key, values) { var index, target, keyExpr = this.key(), extendComplexObject = true; if (keyExpr) { if (hasKey(values, keyExpr) && !keysEqual(keyExpr, key, this.keyOf(values))) { return rejectedPromise(errors.Error("E4017")) } index = this._indexByKey(key); if (index < 0) { return rejectedPromise(errors.Error("E4009")) } target = this._array[index] } else { target = key } objectUtils.deepExtendArraySafe(target, values, extendComplexObject); return trivialPromise(key, values) }, _removeImpl: function(key) { var index = this._indexByKey(key); if (index > -1) { this._array.splice(index, 1) } return trivialPromise(key) }, _indexByKey: function(key) { for (var i = 0, arrayLength = this._array.length; i < arrayLength; i++) { if (keysEqual(this.key(), this.keyOf(this._array[i]), key)) { return i } } return -1 }, clear: function() { this.fireEvent("modifying"); this._array = []; this.fireEvent("modified") } }, "array"); module.exports = ArrayStore }, /*!**************************!*\ !*** ./js/data/query.js ***! \**************************/ function(module, exports, __webpack_require__) { var arrayQueryImpl = __webpack_require__( /*! ./array_query */ 157), remoteQueryImpl = __webpack_require__( /*! ./remote_query */ 160); var queryImpl = { array: arrayQueryImpl, remote: remoteQueryImpl }; var query = function() { var impl = Array.isArray(arguments[0]) ? "array" : "remote"; return queryImpl[impl].apply(this, arguments) }; module.exports = query; module.exports.queryImpl = queryImpl }, /*!*********************************!*\ !*** ./js/data/remote_query.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), queryAdapters = __webpack_require__( /*! ./query_adapters */ 161), errorsModule = __webpack_require__( /*! ./errors */ 155), isFunction = __webpack_require__( /*! ../core/utils/common */ 14).isFunction, arrayQueryImpl = __webpack_require__( /*! ./array_query */ 157); var remoteQueryImpl = function(url, queryOptions, tasks) { tasks = tasks || []; queryOptions = queryOptions || {}; var createTask = function(name, args) { return { name: name, args: args } }; var exec = function(executorTask) { var _adapterFactory, _adapter, _taskQueue, _currentTask, _mergedSortArgs, d = $.Deferred(); var rejectWithNotify = function(error) { var handler = queryOptions.errorHandler; if (handler) { handler(error) } errorsModule._errorHandler(error); d.reject(error) }; function mergeSortTask(task) { switch (task.name) { case "sortBy": _mergedSortArgs = [task.args]; return true; case "thenBy": if (!_mergedSortArgs) { throw errorsModule.errors.Error("E4004") } _mergedSortArgs.push(task.args); return true } return false } function unmergeSortTasks() { var head = _taskQueue[0], unmergedTasks = []; if (head && "multiSort" === head.name) { _taskQueue.shift(); $.each(head.args[0], function() { unmergedTasks.push(createTask(unmergedTasks.length ? "thenBy" : "sortBy", this)) }) } _taskQueue = unmergedTasks.concat(_taskQueue) } try { _adapterFactory = queryOptions.adapter; if (!isFunction(_adapterFactory)) { _adapterFactory = queryAdapters[_adapterFactory] } _adapter = _adapterFactory(queryOptions); _taskQueue = [].concat(tasks).concat(executorTask); while (_taskQueue.length) { _currentTask = _taskQueue[0]; if (!mergeSortTask(_currentTask)) { if (_mergedSortArgs) { _taskQueue.unshift(createTask("multiSort", [_mergedSortArgs])); _mergedSortArgs = null; continue } if ("enumerate" !== String(_currentTask.name)) { if (!_adapter[_currentTask.name] || false === _adapter[_currentTask.name].apply(_adapter, _currentTask.args)) { break } } } _taskQueue.shift() } unmergeSortTasks(); _adapter.exec(url).done(function(result, extra) { if (!_taskQueue.length) { d.resolve(result, extra) } else { var clientChain = arrayQueryImpl(result, { errorHandler: queryOptions.errorHandler }); $.each(_taskQueue, function() { clientChain = clientChain[this.name].apply(clientChain, this.args) }); clientChain.done(d.resolve).fail(d.reject) } }).fail(rejectWithNotify) } catch (x) { rejectWithNotify(x) } return d.promise() }; var query = {}; $.each(["sortBy", "thenBy", "filter", "slice", "select", "groupBy"], function() { var name = String(this); query[name] = function() { return remoteQueryImpl(url, queryOptions, tasks.concat(createTask(name, arguments))) } }); $.each(["count", "min", "max", "sum", "avg", "aggregate", "enumerate"], function() { var name = String(this); query[name] = function() { return exec.call(this, createTask(name, arguments)) } }); return query }; module.exports = remoteQueryImpl }, /*!***********************************!*\ !*** ./js/data/query_adapters.js ***! \***********************************/ function(module, exports) { module.exports = {} }, /*!*********************************!*\ !*** ./js/data/custom_store.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), deferredUtils = __webpack_require__( /*! ../integration/jquery/deferred */ 16), dataUtils = __webpack_require__( /*! ./utils */ 137), isFunction = __webpack_require__( /*! ../core/utils/common */ 14).isFunction, errors = __webpack_require__( /*! ./errors */ 155).errors, Store = __webpack_require__( /*! ./abstract_store */ 154), arrayQuery = __webpack_require__( /*! ./array_query */ 157), queryByOptions = __webpack_require__( /*! ./store_helper */ 156).queryByOptions; var TOTAL_COUNT = "totalCount", LOAD = "load", BY_KEY = "byKey", INSERT = "insert", UPDATE = "update", REMOVE = "remove"; function isPromise(obj) { return obj && isFunction(obj.then) } function trivialPromise(value) { return $.Deferred().resolve(value).promise() } function ensureRequiredFuncOption(name, obj) { if (!isFunction(obj)) { throw errors.Error("E4011", name) } } function throwInvalidUserFuncResult(name) { throw errors.Error("E4012", name) } function createUserFuncFailureHandler(pendingDeferred) { function errorMessageFromXhr(promiseArguments) { var xhr = promiseArguments[0], textStatus = promiseArguments[1]; if (!xhr || !xhr.getResponseHeader) { return null } return dataUtils.errorMessageFromXhr(xhr, textStatus) } return function(arg) { var error; if (arg instanceof Error) { error = arg } else { error = new Error(errorMessageFromXhr(arguments) || arg && String(arg) || "Unknown error") } pendingDeferred.reject(error) } } function invokeUserLoad(store, options) { var userResult, userFunc = store._loadFunc; ensureRequiredFuncOption(LOAD, userFunc); userResult = userFunc.apply(store, [options]); if (Array.isArray(userResult)) { userResult = trivialPromise(userResult) } else { if (null === userResult || void 0 === userResult) { userResult = trivialPromise([]) } else { if (!isPromise(userResult)) { throwInvalidUserFuncResult(LOAD) } } } return deferredUtils.fromPromise(userResult) } function invokeUserTotalCountFunc(store, options) { var userResult, userFunc = store._totalCountFunc; if (!isFunction(userFunc)) { throw errors.Error("E4021") } userResult = userFunc.apply(store, [options]); if (!isPromise(userResult)) { userResult = Number(userResult); if (!isFinite(userResult)) { throwInvalidUserFuncResult(TOTAL_COUNT) } userResult = trivialPromise(userResult) } return deferredUtils.fromPromise(userResult) } function invokeUserByKeyFunc(store, key, extraOptions) { var userResult, userFunc = store._byKeyFunc; ensureRequiredFuncOption(BY_KEY, userFunc); userResult = userFunc.apply(store, [key, extraOptions]); if (!isPromise(userResult)) { userResult = trivialPromise(userResult) } return deferredUtils.fromPromise(userResult) } function runRawLoad(pendingDeferred, store, userFuncOptions, continuation) { if (store.__rawData) { continuation(store.__rawData) } else { invokeUserLoad(store, userFuncOptions).done(function(rawData) { if (store._cacheRawData) { store.__rawData = rawData } continuation(rawData) }).fail(createUserFuncFailureHandler(pendingDeferred)) } } function runRawLoadWithQuery(pendingDeferred, store, options, countOnly) { options = options || {}; var userFuncOptions = {}; if ("userData" in options) { userFuncOptions.userData = options.userData } runRawLoad(pendingDeferred, store, userFuncOptions, function(rawData) { var itemsQuery, totalCountQuery, rawDataQuery = arrayQuery(rawData, { errorHandler: store._errorHandler }), waitList = []; var items, totalCount; if (!countOnly) { itemsQuery = queryByOptions(rawDataQuery, options); if (itemsQuery === rawDataQuery) { items = rawData.slice(0) } else { waitList.push(itemsQuery.enumerate().done(function(asyncResult) { items = asyncResult })) } } if (options.requireTotalCount || countOnly) { totalCountQuery = queryByOptions(rawDataQuery, options, true); if (totalCountQuery === rawDataQuery) { totalCount = rawData.length } else { waitList.push(totalCountQuery.count().done(function(asyncResult) { totalCount = asyncResult })) } } $.when.apply($, waitList).done(function() { if (countOnly) { pendingDeferred.resolve(totalCount) } else { if (options.requireTotalCount) { pendingDeferred.resolve(items, { totalCount: totalCount }) } else { pendingDeferred.resolve(items) } } }).fail(function(x) { pendingDeferred.reject(x) }) }) } function runRawLoadWithKey(pendingDeferred, store, key) { runRawLoad(pendingDeferred, store, {}, function(rawData) { var item, keyExpr = store.key(); for (var i = 0, len = rawData.length; i < len; i++) { item = rawData[i]; if (dataUtils.keysEqual(keyExpr, store.keyOf(rawData[i]), key)) { pendingDeferred.resolve(item); return } } pendingDeferred.reject(errors.Error("E4009")) }) } var CustomStore = Store.inherit({ ctor: function(options) { options = options || {}; this.callBase(options); this._useDefaultSearch = !!options.useDefaultSearch || "raw" === options.loadMode; this._loadMode = options.loadMode; this._cacheRawData = false !== options.cacheRawData; this._loadFunc = options[LOAD]; this._totalCountFunc = options[TOTAL_COUNT]; this._byKeyFunc = options[BY_KEY]; this._insertFunc = options[INSERT]; this._updateFunc = options[UPDATE]; this._removeFunc = options[REMOVE] }, createQuery: function() { throw errors.Error("E4010") }, clearRawDataCache: function() { delete this.__rawData }, _totalCountImpl: function(options) { var d = $.Deferred(); if ("raw" === this._loadMode && !this._totalCountFunc) { runRawLoadWithQuery(d, this, options, true) } else { invokeUserTotalCountFunc(this, options).done(function(count) { d.resolve(Number(count)) }).fail(createUserFuncFailureHandler(d)); d = this._addFailHandlers(d) } return d.promise() }, _loadImpl: function(options) { var d = $.Deferred(); if ("raw" === this._loadMode) { runRawLoadWithQuery(d, this, options, false) } else { invokeUserLoad(this, options).done(function(data, extra) { d.resolve(data, extra) }).fail(createUserFuncFailureHandler(d)); d = this._addFailHandlers(d) } return d.promise() }, _byKeyImpl: function(key, extraOptions) { var d = $.Deferred(); if (this._byKeyViaLoad()) { this._requireKey(); runRawLoadWithKey(d, this, key) } else { invokeUserByKeyFunc(this, key, extraOptions).done(function(obj) { d.resolve(obj) }).fail(createUserFuncFailureHandler(d)) } return d.promise() }, _byKeyViaLoad: function() { return "raw" === this._loadMode && !this._byKeyFunc }, _insertImpl: function(values) { var userResult, userFunc = this._insertFunc, d = $.Deferred(); ensureRequiredFuncOption(INSERT, userFunc); userResult = userFunc.apply(this, [values]); if (!isPromise(userResult)) { userResult = trivialPromise(userResult) } deferredUtils.fromPromise(userResult).done(function(newKey) { d.resolve(values, newKey) }).fail(createUserFuncFailureHandler(d)); return d.promise() }, _updateImpl: function(key, values) { var userResult, userFunc = this._updateFunc, d = $.Deferred(); ensureRequiredFuncOption(UPDATE, userFunc); userResult = userFunc.apply(this, [key, values]); if (!isPromise(userResult)) { userResult = trivialPromise() } deferredUtils.fromPromise(userResult).done(function() { d.resolve(key, values) }).fail(createUserFuncFailureHandler(d)); return d.promise() }, _removeImpl: function(key) { var userResult, userFunc = this._removeFunc, d = $.Deferred(); ensureRequiredFuncOption(REMOVE, userFunc); userResult = userFunc.apply(this, [key]); if (!isPromise(userResult)) { userResult = trivialPromise() } deferredUtils.fromPromise(userResult).done(function() { d.resolve(key) }).fail(createUserFuncFailureHandler(d)); return d.promise() } }); module.exports = CustomStore }, /*!**********************************!*\ !*** ./js/ui/collection/item.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), publicComponentUtils = __webpack_require__( /*! ../../core/utils/public_component */ 45); var INVISIBLE_STATE_CLASS = "dx-state-invisible", DISABLED_STATE_CLASS = "dx-state-disabled", ITEM_CONTENT_PLACEHOLDER_CLASS = "dx-item-content-placeholder"; var forcibleWatcher = function(watchMethod, fn, callback) { var filteredCallback = function() { var oldValue; return function(value) { if (oldValue !== value) { callback(value, oldValue); oldValue = value } } }(); return { dispose: watchMethod(fn, filteredCallback), force: function() { filteredCallback(fn()) } } }; var CollectionItem = Class.inherit({ ctor: function($element, options, rawData) { this._$element = $element; this._options = options; this._rawData = rawData; publicComponentUtils.attachInstanceToElement($element, this, this._dispose); this._render() }, _render: function() { var $placeholder = $("<div>").addClass(ITEM_CONTENT_PLACEHOLDER_CLASS); this._$element.append($placeholder); this._watchers = []; this._renderWatchers() }, _renderWatchers: function() { this._startWatcher("disabled", this._renderDisabled.bind(this)); this._startWatcher("visible", this._renderVisible.bind(this)) }, _startWatcher: function(field, render) { var rawData = this._rawData, exprGetter = this._options.fieldGetter(field); var watcher = forcibleWatcher(this._options.watchMethod(), function() { return exprGetter(rawData) }, function(value, oldValue) { this._dirty = true; render(value, oldValue) }.bind(this)); this._watchers.push(watcher) }, setDataField: function() { this._dirty = false; $.each(this._watchers, function(_, watcher) { watcher.force() }); if (this._dirty) { return true } }, _renderDisabled: function(value, oldValue) { this._$element.toggleClass(DISABLED_STATE_CLASS, !!value) }, _renderVisible: function(value, oldValue) { this._$element.toggleClass(INVISIBLE_STATE_CLASS, void 0 !== value && !value) }, _dispose: function() { $.each(this._watchers, function(_, watcher) { watcher.dispose() }) } }); CollectionItem.getInstance = function($element) { return publicComponentUtils.getInstanceByElement($element, this) }; module.exports = CollectionItem }, /*!***************************!*\ !*** ./js/events/hold.js ***! \***************************/ function(module, exports, __webpack_require__) { var eventUtils = __webpack_require__( /*! ./utils */ 71), Emitter = __webpack_require__( /*! ./core/emitter */ 83), registerEmitter = __webpack_require__( /*! ./core/emitter_registrator */ 84), abs = Math.abs; var HOLD_EVENT_NAME = "dxhold", HOLD_TIMEOUT = 750, TOUCH_BOUNDARY = 5; var HoldEmitter = Emitter.inherit({ start: function(e) { this._startEventData = eventUtils.eventData(e); this._startTimer(e) }, _startTimer: function(e) { var holdTimeout = "timeout" in this ? this.timeout : HOLD_TIMEOUT; this._holdTimer = setTimeout(function() { this._requestAccept(e); this._fireEvent(HOLD_EVENT_NAME, e, { target: e.target }); this._forgetAccept() }.bind(this), holdTimeout) }, move: function(e) { if (this._touchWasMoved(e)) { this._cancel(e) } }, _touchWasMoved: function(e) { var delta = eventUtils.eventDelta(this._startEventData, eventUtils.eventData(e)); return abs(delta.x) > TOUCH_BOUNDARY || abs(delta.y) > TOUCH_BOUNDARY }, end: function() { this._stopTimer() }, _stopTimer: function() { clearTimeout(this._holdTimer) }, cancel: function() { this._stopTimer() }, dispose: function() { this._stopTimer() } }); registerEmitter({ emitter: HoldEmitter, bubble: true, events: [HOLD_EVENT_NAME] }); module.exports = { name: HOLD_EVENT_NAME } }, /*!**********************************!*\ !*** ./js/events/contextmenu.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), support = __webpack_require__( /*! ../core/utils/support */ 61), devices = __webpack_require__( /*! ../core/devices */ 53), Class = __webpack_require__( /*! ../core/class */ 25), registerEvent = __webpack_require__( /*! ./core/event_registrator */ 73), eventUtils = __webpack_require__( /*! ./utils */ 71), holdEvent = __webpack_require__( /*! ./hold */ 164); var CONTEXTMENU_NAMESPACE = "dxContexMenu", CONTEXTMENU_NAMESPACED_EVENT_NAME = eventUtils.addNamespace("contextmenu", CONTEXTMENU_NAMESPACE), HOLD_NAMESPACED_EVENT_NAME = eventUtils.addNamespace(holdEvent.name, CONTEXTMENU_NAMESPACE), CONTEXTMENU_EVENT_NAME = "dxcontextmenu"; var ContextMenu = Class.inherit({ setup: function(element) { var $element = $(element); $element.on(CONTEXTMENU_NAMESPACED_EVENT_NAME, this._contextMenuHandler.bind(this)); if (support.touch || devices.isSimulator()) { $element.on(HOLD_NAMESPACED_EVENT_NAME, this._holdHandler.bind(this)) } }, _holdHandler: function(e) { if (eventUtils.isMouseEvent(e) && !devices.isSimulator()) { return } this._fireContextMenu(e) }, _contextMenuHandler: function(e) { this._fireContextMenu(e) }, _fireContextMenu: function(e) { return eventUtils.fireEvent({ type: CONTEXTMENU_EVENT_NAME, originalEvent: e }) }, teardown: function(element) { $(element).off("." + CONTEXTMENU_NAMESPACE) } }); registerEvent(CONTEXTMENU_EVENT_NAME, new ContextMenu); exports.name = CONTEXTMENU_EVENT_NAME }, /*!*******************************************!*\ !*** ./js/ui/widget/bindable_template.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), TemplateBase = __webpack_require__( /*! ./ui.template_base */ 97), removeEvent = __webpack_require__( /*! ../../core/remove_event */ 47), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14); var watchChanges = function() { var start = function(rawData, watchMethod, fields, fieldsMap, callback) { var globalDispose, fieldsDispose; globalDispose = globalWatch(rawData, watchMethod, function(dataWithRawFields) { fieldsDispose && fieldsDispose(); if (commonUtils.isPrimitive(dataWithRawFields)) { callback(dataWithRawFields); return } fieldsDispose = fieldsWatch(dataWithRawFields, watchMethod, fields, fieldsMap, function(data) { callback(data) }) }); return function() { fieldsDispose && fieldsDispose(); globalDispose && globalDispose() } }; var globalWatch = function(data, watchMethod, callback) { return watchMethod(function() { return data }, callback) }; var fieldsWatch = function(data, watchMethod, fields, fieldsMap, callback) { var resolvedData = {}, missedFields = fields.slice(); var watchHandlers = $.map(fields, function(name) { var fieldGetter = fieldsMap[name]; return watchMethod(fieldGetter ? function() { return fieldGetter(data) } : function() { return data[name] }, function(value) { resolvedData[name] = value; if (missedFields.length) { var index = missedFields.indexOf(name); if (index >= 0) { missedFields.splice(index, 1) } } if (!missedFields.length) { callback(resolvedData) } }) }); return function() { $.each(watchHandlers, function(_, dispose) { dispose() }) } }; return start }(); module.exports = TemplateBase.inherit({ ctor: function(render, fields, watchMethod, fieldsMap) { this._render = render; this._fields = fields; this._fieldsMap = fieldsMap || {}; this._watchMethod = watchMethod }, _renderCore: function(options) { var $container = options.container; var dispose = watchChanges(options.model, this._watchMethod, this._fields, this._fieldsMap, function(data) { $container.empty(); this._render($container, data, options.model) }.bind(this)); $container.on(removeEvent, dispose); return $container.contents() } }) }, /*!**********************************************************************!*\ !*** ./js/ui/collection/ui.collection_widget.edit.strategy.plain.js ***! \**********************************************************************/ function(module, exports, __webpack_require__) { var inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, EditStrategy = __webpack_require__( /*! ./ui.collection_widget.edit.strategy */ 168); var PlainEditStrategy = EditStrategy.inherit({ _getPlainItems: function() { return this._collectionWidget.option("items") || [] }, getIndexByItemData: function(itemData) { var keyOf = this._collectionWidget.keyOf.bind(this._collectionWidget); if (keyOf) { return this.getIndexByKey(keyOf(itemData)) } else { return inArray(itemData, this._getPlainItems()) } }, getItemDataByIndex: function(index) { return this._getPlainItems()[index] }, deleteItemAtIndex: function(index) { this._getPlainItems().splice(index, 1) }, itemsGetter: function() { return this._getPlainItems() }, getKeysByItems: function(items) { var keyOf = this._collectionWidget.keyOf.bind(this._collectionWidget); var result = items; if (keyOf) { result = []; for (var i = 0; i < items.length; i++) { result.push(keyOf(items[i])) } } return result }, getIndexByKey: function(key) { var keys = this.getKeysByItems(this._getPlainItems()); for (var i = 0, length = keys.length; i < length; i++) { if (this._equalKeys(key, keys[i])) { return i } } return -1 }, getItemsByKeys: function(keys, items) { return items || keys }, moveItemAtIndexToIndex: function(movingIndex, destinationIndex) { var items = this._getPlainItems(), movedItemData = items[movingIndex]; items.splice(movingIndex, 1); items.splice(destinationIndex, 0, movedItemData) }, _isItemIndex: function(index) { return "number" === typeof index && Math.round(index) === index }, _getNormalizedItemIndex: function(itemElement) { return this._collectionWidget._itemElements().index(itemElement) }, _normalizeItemIndex: function(index) { return index }, _denormalizeItemIndex: function(index) { return index }, _getItemByNormalizedIndex: function(index) { return index > -1 ? this._collectionWidget._itemElements().eq(index) : null }, _itemsFromSameParent: function() { return true } }); module.exports = PlainEditStrategy }, /*!****************************************************************!*\ !*** ./js/ui/collection/ui.collection_widget.edit.strategy.js ***! \****************************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), abstract = Class.abstract; var EditStrategy = Class.inherit({ ctor: function(collectionWidget) { this._collectionWidget = collectionWidget }, getIndexByItemData: abstract, getItemDataByIndex: abstract, getKeysByItems: abstract, getItemsByKeys: abstract, itemsGetter: abstract, getKeyByIndex: function(index) { var resultIndex = this._denormalizeItemIndex(index); return this.getKeysByItems([this.getItemDataByIndex(resultIndex)])[0] }, _equalKeys: function(key1, key2) { if (this._collectionWidget._isKeySpecified()) { return commonUtils.equalByValue(key1, key2) } else { return key1 === key2 } }, getIndexByKey: abstract, getNormalizedIndex: function(value) { if (this._isNormalizedItemIndex(value)) { return value } if (this._isItemIndex(value)) { return this._normalizeItemIndex(value) } if (this._isDOMNode(value)) { return this._getNormalizedItemIndex(value) } return this._normalizeItemIndex(this.getIndexByItemData(value)) }, getIndex: function(value) { if (this._isNormalizedItemIndex(value)) { return this._denormalizeItemIndex(value) } if (this._isItemIndex(value)) { return value } if (this._isDOMNode(value)) { return this._denormalizeItemIndex(this._getNormalizedItemIndex(value)) } return this.getIndexByItemData(value) }, getItemElement: function(value) { if (this._isNormalizedItemIndex(value)) { return this._getItemByNormalizedIndex(value) } if (this._isItemIndex(value)) { return this._getItemByNormalizedIndex(this._normalizeItemIndex(value)) } if (this._isDOMNode(value)) { return $(value) } return this._getItemByNormalizedIndex(this.getIndexByItemData(value)) }, deleteItemAtIndex: abstract, itemPlacementFunc: function(movingIndex, destinationIndex) { return this._itemsFromSameParent(movingIndex, destinationIndex) && movingIndex < destinationIndex ? "after" : "before" }, moveItemAtIndexToIndex: abstract, _isNormalizedItemIndex: function(index) { return "number" === typeof index && Math.round(index) === index }, _isDOMNode: function(value) { var $value; try { $value = $(value) } catch (error) { return false } return $value && $value.length && $value.get(0).nodeType }, _isItemIndex: abstract, _getNormalizedItemIndex: abstract, _normalizeItemIndex: abstract, _denormalizeItemIndex: abstract, _getItemByNormalizedIndex: abstract, _itemsFromSameParent: abstract }); module.exports = EditStrategy }, /*!**************************************!*\ !*** ./js/ui/selection/selection.js ***! \**************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), deferredStrategy = __webpack_require__( /*! ./selection.strategy.deferred */ 170), standardStrategy = __webpack_require__( /*! ./selection.strategy.standard */ 172), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14); module.exports = Class.inherit({ ctor: function(options) { this.options = extend(this._getDefaultOptions(), options, { selectedItemKeys: options.selectedKeys || [] }); this._selectionStrategy = this.options.deferred ? new deferredStrategy(this.options) : new standardStrategy(this.options); this._focusedItemIndex = -1; if (!this.options.equalByReference) { this._selectionStrategy.updateSelectedItemKeyHash(this.options.selectedItemKeys) } }, _getDefaultOptions: function() { return { deferred: false, equalByReference: false, mode: "multiple", selectedItems: [], selectionFilter: [], maxFilterLengthInRequest: 0, onSelectionChanged: commonUtils.noop, key: commonUtils.noop, keyOf: function(item) { return item }, load: function() { return $.Deferred().resolve([]) }, totalCount: function() { return -1 }, isSelectableItem: function() { return true }, isItemSelected: function() { return false }, getItemData: function(item) { return item }, dataFields: commonUtils.noop, filter: commonUtils.noop } }, validate: function() { this._selectionStrategy.validate() }, getSelectedItemKeys: function() { return this._selectionStrategy.getSelectedItemKeys() }, getSelectedItems: function() { return this._selectionStrategy.getSelectedItems() }, selectionFilter: function(value) { if (void 0 === value) { return this.options.selectionFilter } var filterIsChanged = this.options.selectionFilter !== value && JSON.stringify(this.options.selectionFilter) !== JSON.stringify(value); this.options.selectionFilter = value; filterIsChanged && this.onSelectionChanged() }, setSelection: function(keys) { return this.selectedItemKeys(keys) }, select: function(keys) { return this.selectedItemKeys(keys, true) }, deselect: function(keys) { return this.selectedItemKeys(keys, true, true) }, selectedItemKeys: function(keys, preserve, isDeselect, isSelectAll) { var that = this; keys = keys || []; keys = Array.isArray(keys) ? keys : [keys]; that.validate(); return this._selectionStrategy.selectedItemKeys(keys, preserve, isDeselect, isSelectAll) }, clearSelection: function() { return this.selectedItemKeys([]) }, _addSelectedItem: function(itemData, key) { this._selectionStrategy.addSelectedItem(key, itemData) }, _removeSelectedItem: function(key) { this._selectionStrategy.removeSelectedItem(key) }, _setSelectedItems: function(keys, items) { this._selectionStrategy.setSelectedItems(keys, items) }, onSelectionChanged: function() { this._selectionStrategy.onSelectionChanged() }, changeItemSelection: function(itemIndex, keys) { var isSelectedItemsChanged, items = this.options.plainItems(), item = items[itemIndex]; if (!this.isSelectable() || !this.isDataItem(item)) { return false } var itemData = this.options.getItemData(item), itemKey = this.options.keyOf(itemData); keys = keys || {}; if (keys.shift && "multiple" === this.options.mode && this._focusedItemIndex >= 0) { isSelectedItemsChanged = this.changeItemSelectionWhenShiftKeyPressed(itemIndex, items) } else { if (keys.control) { this._resetItemSelectionWhenShiftKeyPressed(); var isSelected = this._selectionStrategy.isItemDataSelected(itemData); if ("single" === this.options.mode) { this.clearSelectedItems() } if (isSelected) { this._removeSelectedItem(itemKey) } else { this._addSelectedItem(itemData, itemKey) } isSelectedItemsChanged = true } else { this._resetItemSelectionWhenShiftKeyPressed(); var isKeysEqual = this._selectionStrategy.equalKeys(this.options.selectedItemKeys[0], itemKey); if (1 !== this.options.selectedItemKeys.length || !isKeysEqual) { this._setSelectedItems([itemKey], [itemData]); isSelectedItemsChanged = true } } } if (isSelectedItemsChanged) { this._focusedItemIndex = itemIndex; this.onSelectionChanged(); return true } }, isDataItem: function(item) { return this.options.isSelectableItem(item) }, isSelectable: function() { return "single" === this.options.mode || "multiple" === this.options.mode }, isItemSelected: function(arg) { return this._selectionStrategy.isItemKeySelected(arg) }, _resetItemSelectionWhenShiftKeyPressed: function() { delete this._shiftFocusedItemIndex }, changeItemSelectionWhenShiftKeyPressed: function(itemIndex, items) { var itemIndexStep, index, isSelectedItemsChanged = false, keyOf = this.options.keyOf, key = keyOf(items[this._focusedItemIndex].data), isFocusedItemSelected = items[this._focusedItemIndex] && this.isItemSelected(key); if (!commonUtils.isDefined(this._shiftFocusedItemIndex)) { this._shiftFocusedItemIndex = this._focusedItemIndex } var data, itemKey; if (this._shiftFocusedItemIndex !== this._focusedItemIndex) { itemIndexStep = this._focusedItemIndex < this._shiftFocusedItemIndex ? 1 : -1; for (index = this._focusedItemIndex; index !== this._shiftFocusedItemIndex; index += itemIndexStep) { if (this.isDataItem(items[index])) { itemKey = keyOf(this.options.getItemData(items[index])); this._removeSelectedItem(itemKey); isSelectedItemsChanged = true } } } if (itemIndex !== this._shiftFocusedItemIndex) { itemIndexStep = itemIndex < this._shiftFocusedItemIndex ? 1 : -1; for (index = itemIndex; index !== this._shiftFocusedItemIndex; index += itemIndexStep) { if (this.isDataItem(items[index])) { data = this.options.getItemData(items[index]); itemKey = keyOf(data); this._addSelectedItem(data, itemKey); isSelectedItemsChanged = true } } } if (this.isDataItem(items[this._focusedItemIndex]) && !isFocusedItemSelected) { data = this.options.getItemData(items[index]); itemKey = keyOf(data); this._addSelectedItem(data, itemKey); isSelectedItemsChanged = true } return isSelectedItemsChanged }, clearSelectedItems: function() { this._setSelectedItems([], []) }, selectAll: function(isOnePage) { if (isOnePage) { return this._onePageSelectAll(false) } else { return this.selectedItemKeys([], true, false, true) } }, deselectAll: function(isOnePage) { if (isOnePage) { return this._onePageSelectAll(true) } else { return this.selectedItemKeys([], true, true, true) } }, _onePageSelectAll: function(isDeselect) { var items = this.options.plainItems(); for (var i = 0; i < items.length; i++) { var item = items[i]; if (this.isDataItem(item)) { var itemData = this.options.getItemData(item), itemKey = this.options.keyOf(itemData), isSelected = this.isItemSelected(itemKey); if (!isSelected && !isDeselect) { this._addSelectedItem(itemData, itemKey) } if (isSelected && isDeselect) { this._removeSelectedItem(itemKey) } } } this.onSelectionChanged(); return $.Deferred().resolve() }, getSelectAllState: function(visibleOnly) { return this._selectionStrategy.getSelectAllState(visibleOnly) } }) }, /*!********************************************************!*\ !*** ./js/ui/selection/selection.strategy.deferred.js ***! \********************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), SelectionStrategy = __webpack_require__( /*! ./selection.strategy */ 171), errors = __webpack_require__( /*! ../widget/ui.errors */ 22), dataQuery = __webpack_require__( /*! ../../data/query */ 159); module.exports = SelectionStrategy.inherit({ getSelectedItems: function() { return this._loadFilteredData(this.options.selectionFilter) }, getSelectedItemKeys: function() { var d = $.Deferred(), that = this, key = this.options.key(), select = commonUtils.isString(key) ? [key] : key; this._loadFilteredData(this.options.selectionFilter, null, select).done(function(items) { var keys = items.map(function(item) { return that.options.keyOf(item) }); d.resolve(keys) }).fail(d.reject); return d.promise() }, selectedItemKeys: function(keys, preserve, isDeselect, isSelectAll) { if (isSelectAll) { var filter = this.options.filter(); if (!filter) { this._setOption("selectionFilter", isDeselect ? [] : null) } else { this._addSelectionFilter(isDeselect, filter, false) } } else { if (!preserve) { this._setOption("selectionFilter", []) } for (var i = 0; i < keys.length; i++) { if (isDeselect) { this.removeSelectedItem(keys[i]) } else { this.addSelectedItem(keys[i]) } } } this.onSelectionChanged(); return $.Deferred().resolve() }, setSelectedItems: function(keys) { this._setOption("selectionFilter", null); for (var i = 0; i < keys.length; i++) { this.addSelectedItem(keys[i]) } }, isItemDataSelected: function(itemData) { return this.isItemKeySelected(itemData) }, isItemKeySelected: function(itemData) { var selectionFilter = this.options.selectionFilter; if (!selectionFilter) { return true } return !!dataQuery([itemData]).filter(selectionFilter).toArray().length }, _processSelectedItem: function(key) { var keyField = this.options.key(), filter = [keyField, "=", key]; if (Array.isArray(keyField)) { filter = []; for (var i = 0; i < keyField.length; i++) { filter.push([keyField[i], "=", key[keyField[i]]]); if (i !== keyField.length - 1) { filter.push("and") } } } return filter }, addSelectedItem: function(key) { var filter = this._processSelectedItem(key); this._addSelectionFilter(false, filter, true) }, removeSelectedItem: function(key) { var filter = this._processSelectedItem(key); this._addSelectionFilter(true, filter, true) }, validate: function() { var key = this.options.key; if (key && void 0 === key()) { throw errors.Error("E1042") } }, _hasSameFilter: function(selectionFilter, currentFilter) { return this._findSubFilter(selectionFilter, currentFilter) >= 0 }, _findSubFilter: function(selectionFilter, filter) { if (!selectionFilter) { return -1 } var filterString = JSON.stringify(filter); for (var index = 0; index < selectionFilter.length; index++) { var subFilter = selectionFilter[index]; if (subFilter && JSON.stringify(subFilter) === filterString) { return index } } return -1 }, _isLastSubFilter: function(selectionFilter, filter) { if (selectionFilter && filter) { return this._findSubFilter(selectionFilter, filter) === selectionFilter.length - 1 } return false }, _addFilterOperator: function(selectionFilter, filterOperator) { if (selectionFilter.length > 1 && commonUtils.isString(selectionFilter[1]) && selectionFilter[1] !== filterOperator) { selectionFilter = [selectionFilter] } if (selectionFilter.length) { selectionFilter.push(filterOperator) } return selectionFilter }, _denormalizeFilter: function(filter) { if (filter && commonUtils.isString(filter[0])) { filter = [filter] } return filter }, _addSelectionFilter: function(isDeselect, filter, isUnique) { var that = this, needAddFilter = true, currentFilter = isDeselect ? ["!", filter] : filter, selectionFilter = that.options.selectionFilter || []; selectionFilter = that._denormalizeFilter(selectionFilter); if (selectionFilter && selectionFilter.length) { if (that._hasSameFilter(selectionFilter, currentFilter)) { return } if (that._removeInvertedFilter(selectionFilter, isDeselect, filter)) { needAddFilter = !isUnique } if (needAddFilter) { selectionFilter = that._addFilterOperator(selectionFilter, isDeselect ? "and" : "or") } } if (needAddFilter) { selectionFilter.push(currentFilter) } selectionFilter = that._normalizeFilter(selectionFilter); that._setOption("selectionFilter", !isDeselect && !selectionFilter.length ? null : selectionFilter) }, _normalizeFilter: function(filter) { if (filter && 1 === filter.length) { filter = filter[0] } return filter }, _removeInvertedFilter: function(selectionFilter, isDeselect, filter) { filter = isDeselect ? filter : ["!", filter]; var filterIndex = this._findSubFilter(selectionFilter, filter); if (JSON.stringify(filter) === JSON.stringify(selectionFilter)) { selectionFilter.splice(0, selectionFilter.length); return true } if (filterIndex >= 0) { if (filterIndex > 0) { selectionFilter.splice(filterIndex - 1, 2) } else { selectionFilter.splice(filterIndex, 2) } return true } return false }, getSelectAllState: function() { var filter = this.options.filter(), selectionFilter = this.options.selectionFilter; if (!selectionFilter) { return true } if (!selectionFilter.length) { return false } if (!filter || !filter.length) { return } selectionFilter = this._denormalizeFilter(selectionFilter); if (this._isLastSubFilter(selectionFilter, filter)) { return true } if (this._isLastSubFilter(selectionFilter, ["!", filter])) { return false } return } }) }, /*!***********************************************!*\ !*** ./js/ui/selection/selection.strategy.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), dataQuery = __webpack_require__( /*! ../../data/query */ 159), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), getKeyHash = commonUtils.getKeyHash, Class = __webpack_require__( /*! ../../core/class */ 25); module.exports = Class.inherit({ ctor: function(options) { this.options = options; this._clearItemKeys() }, _clearItemKeys: function() { this._setOption("addedItemKeys", []); this._setOption("removedItemKeys", []); this._setOption("removedItems", []); this._setOption("addedItems", []) }, validate: commonUtils.noop, _setOption: function(name, value) { this.options[name] = value }, onSelectionChanged: function() { var addedItemKeys = this.options.addedItemKeys, removedItemKeys = this.options.removedItemKeys, addedItems = this.options.addedItems, removedItems = this.options.removedItems, selectedItems = this.options.selectedItems, selectedItemKeys = this.options.selectedItemKeys, onSelectionChanged = this.options.onSelectionChanged || commonUtils.noop; this._clearItemKeys(); onSelectionChanged({ selectedItems: selectedItems, selectedItemKeys: selectedItemKeys, addedItemKeys: addedItemKeys, removedItemKeys: removedItemKeys, addedItems: addedItems, removedItems: removedItems }) }, equalKeys: function(key1, key2) { if (this.options.equalByReference) { if (commonUtils.isObject(key1) && commonUtils.isObject(key2)) { return key1 === key2 } } return commonUtils.equalByValue(key1, key2) }, _clearSelection: function(keys, preserve, isDeselect, isSelectAll) { keys = keys || []; keys = Array.isArray(keys) ? keys : [keys]; this.validate(); return this.selectedItemKeys(keys, preserve, isDeselect, isSelectAll) }, _loadFilteredData: function(remoteFilter, localFilter, select) { var filterLength = encodeURI(JSON.stringify(remoteFilter)).length, needLoadAllData = this.options.maxFilterLengthInRequest && filterLength > this.options.maxFilterLengthInRequest, deferred = $.Deferred(), loadOptions = { filter: needLoadAllData ? void 0 : remoteFilter, select: needLoadAllData ? this.options.dataFields() : select || this.options.dataFields() }; if (remoteFilter && 0 === remoteFilter.length) { deferred.resolve([]) } else { this.options.load(loadOptions).done(function(items) { var filteredItems = typeUtils.isPlainObject(items) ? items.data : items; if (localFilter) { filteredItems = filteredItems.filter(localFilter) } else { if (needLoadAllData) { filteredItems = dataQuery(filteredItems).filter(remoteFilter).toArray() } } deferred.resolve(filteredItems) }).fail(deferred.reject.bind(deferred)) } return deferred }, updateSelectedItemKeyHash: function(keys) { for (var i = 0; i < keys.length; i++) { var keyHash = getKeyHash(keys[i]); if (!commonUtils.isObject(keyHash)) { this.options.keyHashIndices[keyHash] = this.options.keyHashIndices[keyHash] || []; var keyIndices = this.options.keyHashIndices[keyHash]; keyIndices.push(i) } } }, _isAnyItemSelected: function(items) { for (var i = 0; i < items.length; i++) { if (this.options.isItemSelected(items[i])) { return } } return false }, _getFullSelectAllState: function() { var items = this.options.plainItems(), dataFilter = this.options.filter(), selectedItems = this.options.selectedItems; if (dataFilter) { selectedItems = dataQuery(selectedItems).filter(dataFilter).toArray() } var selectedItemsLength = selectedItems.length; if (!selectedItemsLength) { return this._isAnyItemSelected(items) } if (selectedItemsLength >= this.options.totalCount()) { return true } return }, _getVisibleSelectAllState: function() { var items = this.options.plainItems(), hasSelectedItems = false, hasUnselectedItems = false; for (var i = 0; i < items.length; i++) { var item = items[i], itemData = this.options.getItemData(item), key = this.options.keyOf(itemData); if (this.options.isSelectableItem(item)) { if (this.isItemKeySelected(key)) { hasSelectedItems = true } else { hasUnselectedItems = true } } } if (hasSelectedItems) { return !hasUnselectedItems ? true : void 0 } else { return false } } }) }, /*!********************************************************!*\ !*** ./js/ui/selection/selection.strategy.standard.js ***! \********************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), getKeyHash = commonUtils.getKeyHash, dataQuery = __webpack_require__( /*! ../../data/query */ 159), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when, errors = __webpack_require__( /*! ../widget/ui.errors */ 22), SelectionStrategy = __webpack_require__( /*! ./selection.strategy */ 171); function SelectionFilterCreator(keyExpr, selectedItemKeys, isSelectAll, equalKeys, keyOf, equalByReference) { this.getLocalFilter = function() { return functionFilter }; this.getExpr = function() { if (!keyExpr) { return } var filterExpr; for (var i = 0, length = selectedItemKeys.length; i < length; i++) { filterExpr = filterExpr || []; var filterExprPart, itemKeyValue = selectedItemKeys[i]; if (i > 0) { filterExpr.push(isSelectAll ? "and" : "or") } if (commonUtils.isString(keyExpr)) { filterExprPart = getFilterForPlainKey(itemKeyValue) } else { filterExprPart = getFilterForCompositeKey(itemKeyValue) } filterExpr.push(filterExprPart) } if (filterExpr && 1 === filterExpr.length) { filterExpr = filterExpr[0] } this._filter = filterExpr; return filterExpr }; this.getCombinedFilter = function(dataSourceFilter) { var filterExpr = this.getExpr(), combinedFilter = filterExpr; if (isSelectAll && dataSourceFilter) { if (filterExpr) { combinedFilter = []; combinedFilter.push(filterExpr); combinedFilter.push(dataSourceFilter) } else { combinedFilter = dataSourceFilter } } return combinedFilter }; var selectedItemKeyHashesMap; var getSelectedItemKeyHashesMap = function(selectedItemKeys) { if (!selectedItemKeyHashesMap) { selectedItemKeyHashesMap = {}; for (var i = 0; i < selectedItemKeys.length; i++) { selectedItemKeyHashesMap[getKeyHash(selectedItemKeys[i])] = true } } return selectedItemKeyHashesMap }; var functionFilter = function(item) { var keyHash, i, key = keyOf(item); if (!equalByReference) { keyHash = getKeyHash(key); if (!commonUtils.isObject(keyHash)) { var selectedKeyHashesMap = getSelectedItemKeyHashesMap(selectedItemKeys); if (selectedKeyHashesMap[keyHash]) { return !isSelectAll } return !!isSelectAll } } for (i = 0; i < selectedItemKeys.length; i++) { if (equalKeys(selectedItemKeys[i], key)) { return !isSelectAll } } return !!isSelectAll }; var getFilterForPlainKey = function(keyValue, key) { return [key || keyExpr, isSelectAll ? "<>" : "=", keyValue] }; var getFilterForCompositeKey = function(itemKeyValue) { var filterExpr = []; for (var i = 0, length = keyExpr.length; i < length; i++) { if (i > 0) { filterExpr.push(isSelectAll ? "or" : "and") } var currentKeyExpr = keyExpr[i], currentKeyValue = itemKeyValue && itemKeyValue[currentKeyExpr], filterExprPart = getFilterForPlainKey(currentKeyValue, currentKeyExpr); filterExpr.push(filterExprPart) } return filterExpr } } module.exports = SelectionStrategy.inherit({ ctor: function(options) { this.callBase(options); this._initSelectedItemKeyHash() }, _initSelectedItemKeyHash: function() { this._setOption("keyHashIndices", this.options.equalByReference ? null : {}) }, getSelectedItemKeys: function() { return this.options.selectedItemKeys.slice(0) }, getSelectedItems: function() { return this.options.selectedItems.slice(0) }, _preserveSelectionUpdate: function(items, isDeselect) { var keyIndicesToRemoveMap, keyIndex, i, keyOf = this.options.keyOf; if (!keyOf) { return } var isBatchDeselect = isDeselect && items.length > 1 && !this.options.equalByReference; if (isBatchDeselect) { keyIndicesToRemoveMap = {} } for (i = 0; i < items.length; i++) { var item = items[i], key = keyOf(item); if (isDeselect) { keyIndex = this.removeSelectedItem(key, keyIndicesToRemoveMap); if (keyIndicesToRemoveMap && keyIndex >= 0) { keyIndicesToRemoveMap[keyIndex] = true } } else { this.addSelectedItem(key, item) } } if (isBatchDeselect) { this._batchRemoveSelectedItems(keyIndicesToRemoveMap) } }, _batchRemoveSelectedItems: function(keyIndicesToRemoveMap) { var selectedItemKeys = this.options.selectedItemKeys.slice(0); var selectedItems = this.options.selectedItems.slice(0); this.options.selectedItemKeys.length = 0; this.options.selectedItems.length = 0; for (var i = 0; i < selectedItemKeys.length; i++) { if (!keyIndicesToRemoveMap[i]) { this.options.selectedItemKeys.push(selectedItemKeys[i]); this.options.selectedItems.push(selectedItems[i]) } } this._initSelectedItemKeyHash(); this.updateSelectedItemKeyHash(this.options.selectedItemKeys) }, _loadSelectedItemsCore: function(keys, isDeselect, isSelectAll) { var deferred = $.Deferred(), key = this.options.key; if (!keys.length && !isSelectAll) { deferred.resolve([]); return deferred } var filter = this.options.filter(); if (isSelectAll && isDeselect && !filter) { deferred.resolve(this.getSelectedItems()); return deferred } var selectionFilterCreator = new SelectionFilterCreator(key(), keys, isSelectAll, this.equalKeys.bind(this), this.options.keyOf, this.options.equalByReference), combinedFilter = selectionFilterCreator.getCombinedFilter(filter); var deselectedItems = []; if (isDeselect) { deselectedItems = combinedFilter ? dataQuery(this.options.selectedItems).filter(combinedFilter).toArray() : this.options.selectedItems.slice(0) } var filteredItems = deselectedItems.length ? deselectedItems : this.options.plainItems().filter(this.options.isSelectableItem).map(this.options.getItemData); var localFilter = selectionFilterCreator.getLocalFilter(); filteredItems = filteredItems.filter(localFilter); if (deselectedItems.length || !isSelectAll && filteredItems.length === keys.length) { deferred.resolve(filteredItems) } else { deferred = this._loadFilteredData(combinedFilter, localFilter) } return deferred }, _replaceSelectionUpdate: function(items) { var internalKeys = [], keyOf = this.options.keyOf; if (!keyOf) { return } for (var i = 0; i < items.length; i++) { var item = items[i], key = keyOf(item); internalKeys.push(key) } this.setSelectedItems(internalKeys, items) }, _warnOnIncorrectKeys: function(keys) { for (var i = 0; i < keys.length; i++) { if (!this.isItemKeySelected(keys[i])) { errors.log("W1002", keys[i]) } } }, _loadSelectedItems: function(keys, isDeselect, isSelectAll) { var that = this, deferred = $.Deferred(); when(that._lastLoadDeferred).always(function() { that._loadSelectedItemsCore(keys, isDeselect, isSelectAll).done(deferred.resolve).fail(deferred.reject) }); that._lastLoadDeferred = deferred; return deferred }, selectedItemKeys: function(keys, preserve, isDeselect, isSelectAll) { var that = this, deferred = that._loadSelectedItems(keys, isDeselect, isSelectAll); deferred.done(function(items) { if (preserve) { that._preserveSelectionUpdate(items, isDeselect) } else { that._replaceSelectionUpdate(items) } if (!isSelectAll && !isDeselect) { that._warnOnIncorrectKeys(keys) } that.onSelectionChanged() }); return deferred }, addSelectedItem: function(key, itemData) { var keyHash = this._getKeyHash(key); if (this._indexOfSelectedItemKey(keyHash) === -1) { if (!commonUtils.isObject(keyHash) && this.options.keyHashIndices) { this.options.keyHashIndices[keyHash] = [this.options.selectedItemKeys.length] } this.options.selectedItemKeys.push(key); this.options.addedItemKeys.push(key); this.options.addedItems.push(itemData); this.options.selectedItems.push(itemData) } }, _getSelectedIndexByKey: function(key, ignoreIndicesMap) { var selectedItemKeys = this.options.selectedItemKeys; for (var index = 0; index < selectedItemKeys.length; index++) { if ((!ignoreIndicesMap || !ignoreIndicesMap[index]) && this.equalKeys(selectedItemKeys[index], key)) { return index } } return -1 }, _getSelectedIndexByHash: function(key, ignoreIndicesMap) { var indices = this.options.keyHashIndices[key]; if (indices && indices.length > 1 && ignoreIndicesMap) { indices = indices.filter(function(index) { return !ignoreIndicesMap[index] }) } return indices && indices[0] >= 0 ? indices[0] : -1 }, _indexOfSelectedItemKey: function(key, ignoreIndicesMap) { var selectedIndex; if (this.options.equalByReference) { selectedIndex = this.options.selectedItemKeys.indexOf(key) } else { if (commonUtils.isObject(key)) { selectedIndex = this._getSelectedIndexByKey(key, ignoreIndicesMap) } else { selectedIndex = this._getSelectedIndexByHash(key, ignoreIndicesMap) } } return selectedIndex }, _shiftSelectedKeyIndices: function(keyIndex) { for (var currentKeyIndex = keyIndex; currentKeyIndex < this.options.selectedItemKeys.length; currentKeyIndex++) { var currentKey = this.options.selectedItemKeys[currentKeyIndex], currentKeyHash = getKeyHash(currentKey), currentKeyIndices = this.options.keyHashIndices[currentKeyHash]; if (!currentKeyIndices) { continue } for (var i = 0; i < currentKeyIndices.length; i++) { if (currentKeyIndices[i] > keyIndex) { currentKeyIndices[i]-- } } } }, removeSelectedItem: function(key, keyIndicesToRemoveMap) { var keyHash = this._getKeyHash(key), isBatchDeselect = !!keyIndicesToRemoveMap, keyIndex = this._indexOfSelectedItemKey(keyHash, keyIndicesToRemoveMap); if (keyIndex < 0) { return keyIndex } this.options.removedItemKeys.push(key); this.options.removedItems.push(this.options.selectedItems[keyIndex]); if (isBatchDeselect) { return keyIndex } this.options.selectedItemKeys.splice(keyIndex, 1); this.options.selectedItems.splice(keyIndex, 1); if (commonUtils.isObject(keyHash) || !this.options.keyHashIndices) { return keyIndex } var keyIndices = this.options.keyHashIndices[keyHash]; if (!keyIndices) { return keyIndex } keyIndices.shift(); if (!keyIndices.length) { delete this.options.keyHashIndices[keyHash] } this._shiftSelectedKeyIndices(keyIndex); return keyIndex }, _needRemoveItemKey: function(keys, key) { var hashIndices = this.options.keyHashIndices; if (!hashIndices) { return keys.indexOf(key) < 0 } var hash = this._getKeyHash(key); for (var i = 0; i < keys.length; i++) { var keyHash = this._getKeyHash(keys[i]); if (this.equalKeys(hash, keyHash)) { return false } } return true }, _updateAddedItemKeys: function(keys, items) { for (var i = 0; i < keys.length; i++) { if (this._indexOfSelectedItemKey(keys[i]) < 0) { this.options.addedItemKeys.push(keys[i]); this.options.addedItems.push(items[i]) } } }, _updateRemovedItemKeys: function(keys) { var oldSelectedKeys = this.options.selectedItemKeys, oldSelectedItems = this.options.selectedItems; for (var i = 0; i < oldSelectedKeys.length; i++) { if (this._needRemoveItemKey(keys, oldSelectedKeys[i])) { this.options.removedItemKeys.push(oldSelectedKeys[i]); this.options.removedItems.push(oldSelectedItems[i]) } } }, _getKeyHash: function(key) { return this.options.equalByReference ? key : getKeyHash(key) }, setSelectedItems: function(keys, items) { this._updateRemovedItemKeys(keys, items); this._updateAddedItemKeys(keys, items); if (!this.options.equalByReference) { this._initSelectedItemKeyHash(); this.updateSelectedItemKeyHash(keys) } this._setOption("selectedItemKeys", keys); this._setOption("selectedItems", items) }, isItemDataSelected: function(itemData) { var key = this.options.keyOf(itemData); return this.isItemKeySelected(key) }, isItemKeySelected: function(key) { var keyHash = this._getKeyHash(key); var index = this._indexOfSelectedItemKey(keyHash); return index !== -1 }, getSelectAllState: function(visibleOnly) { if (visibleOnly) { return this._getVisibleSelectAllState() } else { return this._getFullSelectAllState() } } }) }, /*!*****************************************************!*\ !*** ./js/integration/angular/event_registrator.js ***! \*****************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), eventRegistrator = __webpack_require__( /*! ../../events/core/event_registrator */ 73), ngModule = __webpack_require__( /*! ./module */ 148); eventRegistrator.callbacks.add(function(name) { var ngEventName = name.slice(0, 2) + name.charAt(2).toUpperCase() + name.slice(3); ngModule.directive(ngEventName, ["$parse", function($parse) { return function(scope, element, attr) { var handler, attrValue = $.trim(attr[ngEventName]), eventOptions = {}; if ("{" === attrValue.charAt(0)) { eventOptions = scope.$eval(attrValue); handler = $parse(eventOptions.execute) } else { handler = $parse(attr[ngEventName]) } element.on(name, eventOptions, function(e) { scope.$apply(function() { handler(scope, { $event: e }) }) }) } }]) }) }, /*!**********************************************!*\ !*** ./js/integration/angular/components.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), ngModule = __webpack_require__( /*! ./module */ 148); ngModule.service("dxDigestCallbacks", ["$rootScope", function($rootScope) { var begin = $.Callbacks(), end = $.Callbacks(); var digestPhase = false; $rootScope.$watch(function() { if (digestPhase) { return } digestPhase = true; begin.fire(); $rootScope.$$postDigest(function() { digestPhase = false; end.fire() }) }); return { begin: { add: function(callback) { if (digestPhase) { callback() } begin.add(callback) }, remove: begin.remove }, end: end } }]) }, /*!****************************************************!*\ !*** ./js/integration/angular/action_executors.js ***! \****************************************************/ function(module, exports, __webpack_require__) { var Action = __webpack_require__( /*! ../../core/action */ 49); Action.registerExecutor({ ngExpression: { execute: function(e) { if ("string" === typeof e.action) { e.context.$eval(e.action) } } } }) }, /*!*******************************************!*\ !*** ./js/localization/globalize/core.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var Globalize = __webpack_require__( /*! globalize */ 177), coreLocalization = __webpack_require__( /*! ../core */ 34); if (Globalize && Globalize.load) { var likelySubtags = { supplemental: { version: { _cldrVersion: "28", _unicodeVersion: "8.0.0", _number: "$Revision: 11965 $" }, likelySubtags: { en: "en-Latn-US", de: "de-Latn-DE", ru: "ru-Cyrl-RU", ja: "ja-Jpan-JP" } } }; if (!Globalize.locale()) { Globalize.load(likelySubtags); Globalize.locale("en") } coreLocalization.inject({ locale: function(locale) { if (!locale) { return Globalize.locale().locale } Globalize.locale(locale) } }) } }, /*!***********************************!*\ !*** external "window.Globalize" ***! \***********************************/ function(module, exports) { module.exports = window.Globalize }, /*!**********************************************!*\ !*** ./js/localization/globalize/message.js ***! \**********************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 176); var Globalize = __webpack_require__( /*! globalize */ 177), messageLocalization = __webpack_require__( /*! ../message */ 89), coreLocalization = __webpack_require__( /*! ../core */ 34); __webpack_require__( /*! globalize/message */ 177); if (Globalize && Globalize.formatMessage) { var DEFAULT_LOCALE = "en"; var originalLoadMessages = Globalize.loadMessages; Globalize.loadMessages = function(messages) { messageLocalization.load(messages) }; var globalizeMessageLocalization = { ctor: function() { this.load(this._dictionary) }, load: function(messages) { this.callBase(messages); originalLoadMessages(messages) }, getMessagesByLocales: function() { return Globalize.cldr.get("globalize-messages") }, getFormatter: function(key, locale) { var currentLocale = locale || coreLocalization.locale(), formatter = this._getFormatterBase(key, locale); if (!formatter) { formatter = this._formatterByGlobalize(key, locale) } if (!formatter && currentLocale !== DEFAULT_LOCALE) { formatter = this.getFormatter(key, DEFAULT_LOCALE) } return formatter }, _formatterByGlobalize: function(key, locale) { var result, currentGlobalize = !locale || locale === coreLocalization.locale() ? Globalize : new Globalize(locale); if (this._messageLoaded(key, locale)) { result = currentGlobalize.messageFormatter(key) } return result }, _messageLoaded: function(key, locale) { var currentCldr = locale ? new Globalize(locale).cldr : Globalize.locale(), value = currentCldr.get(["globalize-messages/{bundle}", key]); return void 0 !== value }, _loadSingle: function(key, value, locale) { var data = {}; data[locale] = {}; data[locale][key] = value; this.load(data) } }; messageLocalization.inject(globalizeMessageLocalization) } }, /*!*********************************************!*\ !*** ./js/localization/globalize/number.js ***! \*********************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 176); var Globalize = __webpack_require__( /*! globalize */ 177), numberLocalization = __webpack_require__( /*! ../number */ 32), errors = __webpack_require__( /*! ../../core/errors */ 7); __webpack_require__( /*! globalize/number */ 177); if (Globalize && Globalize.formatNumber) { var enNumbers = { main: { en: { identity: { version: { _cldrVersion: "28", _number: "$Revision: 11972 $" }, language: "en" }, numbers: { defaultNumberingSystem: "latn", otherNumberingSystems: { "native": "latn" }, minimumGroupingDigits: "1", "symbols-numberSystem-latn": { decimal: ".", group: ",", list: ";", percentSign: "%", plusSign: "+", minusSign: "-", exponential: "E", superscriptingExponent: "×", perMille: "‰", infinity: "∞", nan: "NaN", timeSeparator: ":" }, "decimalFormats-numberSystem-latn": { standard: "#,##0.###", "long": { decimalFormat: { "1000-count-one": "0 thousand", "1000-count-other": "0 thousand", "10000-count-one": "00 thousand", "10000-count-other": "00 thousand", "100000-count-one": "000 thousand", "100000-count-other": "000 thousand", "1000000-count-one": "0 million", "1000000-count-other": "0 million", "10000000-count-one": "00 million", "10000000-count-other": "00 million", "100000000-count-one": "000 million", "100000000-count-other": "000 million", "1000000000-count-one": "0 billion", "1000000000-count-other": "0 billion", "10000000000-count-one": "00 billion", "10000000000-count-other": "00 billion", "100000000000-count-one": "000 billion", "100000000000-count-other": "000 billion", "1000000000000-count-one": "0 trillion", "1000000000000-count-other": "0 trillion", "10000000000000-count-one": "00 trillion", "10000000000000-count-other": "00 trillion", "100000000000000-count-one": "000 trillion", "100000000000000-count-other": "000 trillion" } }, "short": { decimalFormat: { "1000-count-one": "0K", "1000-count-other": "0K", "10000-count-one": "00K", "10000-count-other": "00K", "100000-count-one": "000K", "100000-count-other": "000K", "1000000-count-one": "0M", "1000000-count-other": "0M", "10000000-count-one": "00M", "10000000-count-other": "00M", "100000000-count-one": "000M", "100000000-count-other": "000M", "1000000000-count-one": "0B", "1000000000-count-other": "0B", "10000000000-count-one": "00B", "10000000000-count-other": "00B", "100000000000-count-one": "000B", "100000000000-count-other": "000B", "1000000000000-count-one": "0T", "1000000000000-count-other": "0T", "10000000000000-count-one": "00T", "10000000000000-count-other": "00T", "100000000000000-count-one": "000T", "100000000000000-count-other": "000T" } } }, "scientificFormats-numberSystem-latn": { standard: "#E0" }, "percentFormats-numberSystem-latn": { standard: "#,##0%" }, "currencyFormats-numberSystem-latn": { currencySpacing: { beforeCurrency: { currencyMatch: "[:^S:]", surroundingMatch: "[:digit:]", insertBetween: " " }, afterCurrency: { currencyMatch: "[:^S:]", surroundingMatch: "[:digit:]", insertBetween: " " } }, standard: "¤#,##0.00", accounting: "¤#,##0.00;(¤#,##0.00)", "short": { standard: { "1000-count-one": "¤0K", "1000-count-other": "¤0K", "10000-count-one": "¤00K", "10000-count-other": "¤00K", "100000-count-one": "¤000K", "100000-count-other": "¤000K", "1000000-count-one": "¤0M", "1000000-count-other": "¤0M", "10000000-count-one": "¤00M", "10000000-count-other": "¤00M", "100000000-count-one": "¤000M", "100000000-count-other": "¤000M", "1000000000-count-one": "¤0B", "1000000000-count-other": "¤0B", "10000000000-count-one": "¤00B", "10000000000-count-other": "¤00B", "100000000000-count-one": "¤000B", "100000000000-count-other": "¤000B", "1000000000000-count-one": "¤0T", "1000000000000-count-other": "¤0T", "10000000000000-count-one": "¤00T", "10000000000000-count-other": "¤00T", "100000000000000-count-one": "¤000T", "100000000000000-count-other": "¤000T" } }, "unitPattern-count-one": "{0} {1}", "unitPattern-count-other": "{0} {1}" }, "miscPatterns-numberSystem-latn": { atLeast: "{0}+", range: "{0}–{1}" } } } } }; if ("en" === Globalize.locale().locale) { Globalize.load(enNumbers); Globalize.locale("en") } var formattersCache = {}; var getFormatter = function(format) { var formatter, formatCacheKey; if ("object" === typeof format) { formatCacheKey = Globalize.locale().locale + ":" + JSON.stringify(format) } else { formatCacheKey = Globalize.locale().locale + ":" + format } formatter = formattersCache[formatCacheKey]; if (!formatter) { formatter = formattersCache[formatCacheKey] = Globalize.numberFormatter(format) } return formatter }; var globalizeNumberLocalization = { _formatNumberCore: function(value, format, formatConfig) { if ("exponential" === format) { return this.callBase.apply(this, arguments) } return getFormatter(this._normalizeFormatConfig(format, formatConfig, value))(value) }, _normalizeFormatConfig: function(format, formatConfig, value) { var config; if ("decimal" === format) { config = { minimumIntegerDigits: formatConfig.precision || 1, useGrouping: false, maximumFractionDigits: 0, round: value < 0 ? "ceil" : "floor" } } else { config = this._getPrecisionConfig(formatConfig.precision) } if ("percent" === format) { config.style = "percent" } return config }, _getPrecisionConfig: function(precision) { var config; if (null === precision) { config = { minimumFractionDigits: 0, maximumFractionDigits: 20 } } else { config = { minimumFractionDigits: precision || 0, maximumFractionDigits: precision || 0 } } return config }, format: function(value, format) { if ("number" !== typeof value) { return value } format = this._normalizeFormat(format); if (!format || "function" !== typeof format && !format.type && !format.formatter) { return getFormatter(format)(value) } return this.callBase.apply(this, arguments) }, parse: function(text, format) { if (!text) { return } if (format && format.parser) { return format.parser(text) } if (format) { errors.log("W0011") } return Globalize.parseNumber(text) } }; numberLocalization.inject(globalizeNumberLocalization) } }, /*!*******************************************!*\ !*** ./js/localization/globalize/date.js ***! \*******************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 176); __webpack_require__( /*! ./number */ 179); __webpack_require__( /*! globalize/date */ 177); var timeData = { supplemental: { version: { _cldrVersion: "28", _unicodeVersion: "8.0.0", _number: "$Revision: 11969 $" }, timeData: { "001": { _allowed: "H h", _preferred: "H" }, DE: { _allowed: "H", _preferred: "H" }, JP: { _allowed: "H K h", _preferred: "H" }, RU: { _allowed: "H", _preferred: "H" }, US: { _allowed: "H h", _preferred: "h" } } } }; var enCaGregorian = { main: { en: { identity: { version: { _cldrVersion: "28", _number: "$Revision: 11972 $" }, language: "en" }, dates: { calendars: { gregorian: { months: { format: { abbreviated: { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" }, narrow: { 1: "J", 2: "F", 3: "M", 4: "A", 5: "M", 6: "J", 7: "J", 8: "A", 9: "S", 10: "O", 11: "N", 12: "D" }, wide: { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } }, "stand-alone": { abbreviated: { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" }, narrow: { 1: "J", 2: "F", 3: "M", 4: "A", 5: "M", 6: "J", 7: "J", 8: "A", 9: "S", 10: "O", 11: "N", 12: "D" }, wide: { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } } }, days: { format: { abbreviated: { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat" }, narrow: { sun: "S", mon: "M", tue: "T", wed: "W", thu: "T", fri: "F", sat: "S" }, "short": { sun: "Su", mon: "Mo", tue: "Tu", wed: "We", thu: "Th", fri: "Fr", sat: "Sa" }, wide: { sun: "Sunday", mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday" } }, "stand-alone": { abbreviated: { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat" }, narrow: { sun: "S", mon: "M", tue: "T", wed: "W", thu: "T", fri: "F", sat: "S" }, "short": { sun: "Su", mon: "Mo", tue: "Tu", wed: "We", thu: "Th", fri: "Fr", sat: "Sa" }, wide: { sun: "Sunday", mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday" } } }, quarters: { format: { abbreviated: { 1: "Q1", 2: "Q2", 3: "Q3", 4: "Q4" }, narrow: { 1: "1", 2: "2", 3: "3", 4: "4" }, wide: { 1: "1st quarter", 2: "2nd quarter", 3: "3rd quarter", 4: "4th quarter" } }, "stand-alone": { abbreviated: { 1: "Q1", 2: "Q2", 3: "Q3", 4: "Q4" }, narrow: { 1: "1", 2: "2", 3: "3", 4: "4" }, wide: { 1: "1st quarter", 2: "2nd quarter", 3: "3rd quarter", 4: "4th quarter" } } }, dayPeriods: { format: { abbreviated: { midnight: "midnight", am: "AM", "am-alt-variant": "am", noon: "noon", pm: "PM", "pm-alt-variant": "pm", morning1: "in the morning", afternoon1: "in the afternoon", evening1: "in the evening", night1: "at night" }, narrow: { midnight: "mi", am: "a", "am-alt-variant": "am", noon: "n", pm: "p", "pm-alt-variant": "pm", morning1: "in the morning", afternoon1: "in the afternoon", evening1: "in the evening", night1: "at night" }, wide: { midnight: "midnight", am: "AM", "am-alt-variant": "am", noon: "noon", pm: "PM", "pm-alt-variant": "pm", morning1: "in the morning", afternoon1: "in the afternoon", evening1: "in the evening", night1: "at night" } }, "stand-alone": { abbreviated: { midnight: "midnight", am: "AM", "am-alt-variant": "am", noon: "noon", pm: "PM", "pm-alt-variant": "pm", morning1: "in the morning", afternoon1: "in the afternoon", evening1: "in the evening", night1: "at night" }, narrow: { midnight: "midnight", am: "AM", "am-alt-variant": "am", noon: "noon", pm: "PM", "pm-alt-variant": "pm", morning1: "in the morning", afternoon1: "in the afternoon", evening1: "in the evening", night1: "at night" }, wide: { midnight: "midnight", am: "AM", "am-alt-variant": "am", noon: "noon", pm: "PM", "pm-alt-variant": "pm", morning1: "morning", afternoon1: "afternoon", evening1: "evening", night1: "night" } } }, eras: { eraNames: { 0: "Before Christ", "0-alt-variant": "Before Common Era", 1: "Anno Domini", "1-alt-variant": "Common Era" }, eraAbbr: { 0: "BC", "0-alt-variant": "BCE", 1: "AD", "1-alt-variant": "CE" }, eraNarrow: { 0: "B", "0-alt-variant": "BCE", 1: "A", "1-alt-variant": "CE" } }, dateFormats: { full: "EEEE, MMMM d, y", "long": "MMMM d, y", medium: "MMM d, y", "short": "M/d/yy" }, timeFormats: { full: "h:mm:ss a zzzz", "long": "h:mm:ss a z", medium: "h:mm:ss a", "short": "h:mm a" }, dateTimeFormats: { full: "{1} 'at' {0}", "long": "{1} 'at' {0}", medium: "{1}, {0}", "short": "{1}, {0}", availableFormats: { d: "d", E: "ccc", Ed: "d E", Ehm: "E h:mm a", EHm: "E HH:mm", Ehms: "E h:mm:ss a", EHms: "E HH:mm:ss", Gy: "y G", GyMMM: "MMM y G", GyMMMd: "MMM d, y G", GyMMMEd: "E, MMM d, y G", h: "h a", H: "HH", hm: "h:mm a", Hm: "HH:mm", hms: "h:mm:ss a", Hms: "HH:mm:ss", hmsv: "h:mm:ss a v", Hmsv: "HH:mm:ss v", hmv: "h:mm a v", Hmv: "HH:mm v", M: "L", Md: "M/d", MEd: "E, M/d", MMM: "LLL", MMMd: "MMM d", MMMEd: "E, MMM d", MMMMd: "MMMM d", ms: "mm:ss", y: "y", yM: "M/y", yMd: "M/d/y", yMEd: "E, M/d/y", yMMM: "MMM y", yMMMd: "MMM d, y", yMMMEd: "E, MMM d, y", yMMMM: "MMMM y", yQQQ: "QQQ y", yQQQQ: "QQQQ y" }, appendItems: { Day: "{0} ({2}: {1})", "Day-Of-Week": "{0} {1}", Era: "{0} {1}", Hour: "{0} ({2}: {1})", Minute: "{0} ({2}: {1})", Month: "{0} ({2}: {1})", Quarter: "{0} ({2}: {1})", Second: "{0} ({2}: {1})", Timezone: "{0} {1}", Week: "{0} ({2}: {1})", Year: "{0} {1}" }, intervalFormats: { intervalFormatFallback: "{0} – {1}", d: { d: "d – d" }, h: { a: "h a – h a", h: "h – h a" }, H: { H: "HH – HH" }, hm: { a: "h:mm a – h:mm a", h: "h:mm – h:mm a", m: "h:mm – h:mm a" }, Hm: { H: "HH:mm – HH:mm", m: "HH:mm – HH:mm" }, hmv: { a: "h:mm a – h:mm a v", h: "h:mm – h:mm a v", m: "h:mm – h:mm a v" }, Hmv: { H: "HH:mm – HH:mm v", m: "HH:mm – HH:mm v" }, hv: { a: "h a – h a v", h: "h – h a v" }, Hv: { H: "HH – HH v" }, M: { M: "M – M" }, Md: { d: "M/d – M/d", M: "M/d – M/d" }, MEd: { d: "E, M/d – E, M/d", M: "E, M/d – E, M/d" }, MMM: { M: "MMM – MMM" }, MMMd: { d: "MMM d – d", M: "MMM d – MMM d" }, MMMEd: { d: "E, MMM d – E, MMM d", M: "E, MMM d – E, MMM d" }, y: { y: "y – y" }, yM: { M: "M/y – M/y", y: "M/y – M/y" }, yMd: { d: "M/d/y – M/d/y", M: "M/d/y – M/d/y", y: "M/d/y – M/d/y" }, yMEd: { d: "E, M/d/y – E, M/d/y", M: "E, M/d/y – E, M/d/y", y: "E, M/d/y – E, M/d/y" }, yMMM: { M: "MMM – MMM y", y: "MMM y – MMM y" }, yMMMd: { d: "MMM d – d, y", M: "MMM d – MMM d, y", y: "MMM d, y – MMM d, y" }, yMMMEd: { d: "E, MMM d – E, MMM d, y", M: "E, MMM d – E, MMM d, y", y: "E, MMM d, y – E, MMM d, y" }, yMMMM: { M: "MMMM – MMMM y", y: "MMMM y – MMMM y" } } } } } } } } }; var weekData = { supplemental: { version: { _cldrVersion: "28", _unicodeVersion: "8.0.0", _number: "$Revision: 11969 $" }, weekData: { minDays: { "001": "1", US: "1", DE: "4" }, firstDay: { "001": "mon", DE: "mon", RU: "mon", JP: "sun", US: "sun" }, weekendStart: { "001": "sat" }, weekendEnd: { "001": "sun" } } } }; var ACCEPTABLE_JSON_FORMAT_PROPERTIES = ["skeleton", "date", "time", "datetime", "raw"]; var $ = __webpack_require__( /*! ../../core/renderer */ 9), Globalize = __webpack_require__( /*! globalize */ 177), dateLocalization = __webpack_require__( /*! ../date */ 33), isObject = __webpack_require__( /*! ../../core/utils/common */ 14).isObject, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, errors = __webpack_require__( /*! ../../core/errors */ 7); if (Globalize && Globalize.formatDate) { if ("en" === Globalize.locale().locale) { Globalize.load(weekData, timeData, enCaGregorian); Globalize.locale("en") } var formattersCache = {}; var FORMATS_TO_GLOBALIZE_MAP = { shortdate: { path: "dateTimeFormats/availableFormats/yMd" }, shorttime: { path: "timeFormats/short" }, longdate: { path: "dateFormats/full" }, longtime: { path: "timeFormats/medium" }, monthandday: { path: "dateTimeFormats/availableFormats/MMMMd" }, monthandyear: { path: "dateTimeFormats/availableFormats/yMMMM" }, quarterandyear: { path: "dateTimeFormats/availableFormats/yQQQ" }, day: { path: "dateTimeFormats/availableFormats/d" }, year: { path: "dateTimeFormats/availableFormats/y" }, shortdateshorttime: { path: "dateTimeFormats/short", parts: ["shorttime", "shortdate"] }, mediumdatemediumtime: { path: "dateTimeFormats/medium", parts: ["shorttime", "monthandday"] }, longdatelongtime: { path: "dateTimeFormats/medium", parts: ["longtime", "longdate"] }, month: { pattern: "LLLL" }, shortyear: { pattern: "yy" }, dayofweek: { pattern: "EEEE" }, quarter: { pattern: "QQQ" }, millisecond: { pattern: "SSS" }, hour: { pattern: "HH" }, minute: { pattern: "mm" }, second: { pattern: "ss" } }; var globalizeDateLocalization = { _getPatternByFormat: function(format) { var that = this, lowerFormat = format.toLowerCase(), globalizeFormat = FORMATS_TO_GLOBALIZE_MAP[lowerFormat]; if ("datetime-local" === lowerFormat) { return "yyyy-MM-ddTHH':'mm':'ss" } if (!globalizeFormat) { return } var result = globalizeFormat.path && that._getFormatStringByPath(globalizeFormat.path) || globalizeFormat.pattern; if (globalizeFormat.parts) { $.each(globalizeFormat.parts, function(index, part) { result = result.replace("{" + index + "}", that._getPatternByFormat(part)) }) } return result }, _getFormatStringByPath: function(path) { return Globalize.locale().main("dates/calendars/gregorian/" + path) }, getMonthNames: function(format) { var months = Globalize.locale().main("dates/calendars/gregorian/months/stand-alone/" + (format || "wide")); return $.map(months, function(month) { return month }) }, getDayNames: function(format) { var days = Globalize.locale().main("dates/calendars/gregorian/days/stand-alone/" + (format || "wide")); return $.map(days, function(day) { return day }) }, getTimeSeparator: function() { return Globalize.locale().main("numbers/symbols-numberSystem-latn/timeSeparator") }, format: function(date, format) { if (!date) { return } if (!format) { return date } var formatter, formatCacheKey; if ("function" === typeof format) { return format(date) } if (format.formatter) { return format.formatter(date) } format = format.type || format; if ("string" === typeof format) { formatCacheKey = Globalize.locale().locale + ":" + format; formatter = formattersCache[formatCacheKey]; if (!formatter) { format = { raw: this._getPatternByFormat(format) || format }; formatter = formattersCache[formatCacheKey] = Globalize.dateFormatter(format) } } else { formatter = Globalize.dateFormatter(format) } return formatter(date) }, parse: function(text, format) { if (!text) { return } if (!format || "function" === typeof format || isObject(format) && !this._isAcceptableFormat(format)) { if (format) { errors.log("W0012") } return Globalize.parseDate(text) } if (format.parser) { return format.parser(text) } if ("string" === typeof format) { format = { raw: this._getPatternByFormat(format) || format } } return Globalize.parseDate(text, format) }, _isAcceptableFormat: function(format) { if (format.parser) { return true } for (var i = 0; i < ACCEPTABLE_JSON_FORMAT_PROPERTIES.length; i++) { if (format.hasOwnProperty(ACCEPTABLE_JSON_FORMAT_PROPERTIES[i])) { return true } } }, firstDayOfWeekIndex: function() { var firstDay = Globalize.locale().supplemental.weekData.firstDay(); return inArray(firstDay, this._getDayKeys()) }, _getDayKeys: function() { var days = Globalize.locale().main("dates/calendars/gregorian/days/format/short"); return $.map(days, function(day, key) { return key }) } }; dateLocalization.inject(globalizeDateLocalization) } }, /*!***********************************************!*\ !*** ./js/localization/globalize/currency.js ***! \***********************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 176); __webpack_require__( /*! ./number */ 179); __webpack_require__( /*! ../currency */ 36); __webpack_require__( /*! globalize/currency */ 177); var enCurrencyUSD = { main: { en: { identity: { version: { _cldrVersion: "28", _number: "$Revision: 11972 $" }, language: "en" }, numbers: { currencies: { USD: { displayName: "US Dollar", "displayName-count-one": "US dollar", "displayName-count-other": "US dollars", symbol: "$", "symbol-alt-narrow": "$" } } } } } }; var currencyData = { supplemental: { version: { _cldrVersion: "28", _unicodeVersion: "8.0.0", _number: "$Revision: 11969 $" }, currencyData: { fractions: { DEFAULT: { _rounding: "0", _digits: "2" } } } } }; var Globalize = __webpack_require__( /*! globalize */ 177), config = __webpack_require__( /*! ../../core/config */ 15), numberLocalization = __webpack_require__( /*! ../number */ 32); if (Globalize && Globalize.formatCurrency) { if ("en" === Globalize.locale().locale) { Globalize.load(enCurrencyUSD, currencyData); Globalize.locale("en") } var formattersCache = {}; var getFormatter = function(currency, format) { var formatter, formatCacheKey; if ("object" === typeof format) { formatCacheKey = Globalize.locale().locale + ":" + currency + ":" + JSON.stringify(format) } else { formatCacheKey = Globalize.locale().locale + ":" + currency + ":" + format } formatter = formattersCache[formatCacheKey]; if (!formatter) { formatter = formattersCache[formatCacheKey] = Globalize.currencyFormatter(currency, format) } return formatter }; var globalizeCurrencyLocalization = { _formatNumberCore: function(value, format, formatConfig) { if ("currency" === format) { var currency = formatConfig && formatConfig.currency || config().defaultCurrency; return getFormatter(currency, this._normalizeFormatConfig(format, formatConfig, value))(value) } return this.callBase.apply(this, arguments) }, _normalizeFormatConfig: function(format, formatConfig, value) { var config = this.callBase(format, formatConfig, value); if ("currency" === format) { config.style = "accounting" } return config }, format: function(value, format) { if ("number" !== typeof value) { return value } format = this._normalizeFormat(format); if (format) { if ("default" === format.currency) { format.currency = config().defaultCurrency } if ("currency" === format.type) { return this._formatNumber(value, this._parseNumberFormatString("currency"), format) } else { if (!format.type && format.currency) { return getFormatter(format.currency, format)(value) } } } return this.callBase.apply(this, arguments) }, getCurrencySymbol: function(currency) { if (!currency) { currency = config().defaultCurrency } return Globalize.cldr.main("numbers/currencies/" + currency) }, getOpenXmlCurrencyFormat: function(currency) { var i, result, symbol, encodeSymbols, currencySymbol = this.getCurrencySymbol(currency).symbol, currencyFormat = Globalize.cldr.main("numbers/currencyFormats-numberSystem-latn"); if (currencyFormat.accounting) { encodeSymbols = { ".00": "{0}", "'": "\\'", "\\(": "\\(", "\\)": "\\)", " ": "\\ ", '"': """, "\\¤": currencySymbol }; result = currencyFormat.accounting.split(";"); for (i = 0; i < result.length; i++) { for (symbol in encodeSymbols) { if (encodeSymbols.hasOwnProperty(symbol)) { result[i] = result[i].replace(new RegExp(symbol, "g"), encodeSymbols[symbol]) } } } return 2 === result.length ? result[0] + "_);" + result[1] : result[0] } } }; numberLocalization.inject(globalizeCurrencyLocalization) } }, /*!***********************************!*\ !*** ./js/events/double_click.js ***! \***********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), domUtils = __webpack_require__( /*! ../core/utils/dom */ 56), Class = __webpack_require__( /*! ../core/class */ 25), registerEvent = __webpack_require__( /*! ./core/event_registrator */ 73), clickEvent = __webpack_require__( /*! ./click */ 75), eventUtils = __webpack_require__( /*! ./utils */ 71); var DBLCLICK_EVENT_NAME = "dxdblclick", DBLCLICK_NAMESPACE = "dxDblClick", NAMESPACED_CLICK_EVENT = eventUtils.addNamespace(clickEvent.name, DBLCLICK_NAMESPACE), DBLCLICK_TIMEOUT = 300; var DblClick = Class.inherit({ ctor: function() { this._handlerCount = 0; this._forgetLastClick() }, _forgetLastClick: function() { this._firstClickTarget = null; this._lastClickTimeStamp = -DBLCLICK_TIMEOUT }, add: function() { if (this._handlerCount <= 0) { $(document).on(NAMESPACED_CLICK_EVENT, this._clickHandler.bind(this)) } this._handlerCount++ }, _clickHandler: function(e) { var timeStamp = e.timeStamp || $.now(); if (timeStamp - this._lastClickTimeStamp < DBLCLICK_TIMEOUT) { eventUtils.fireEvent({ type: DBLCLICK_EVENT_NAME, target: domUtils.closestCommonParent(this._firstClickTarget, e.target), originalEvent: e }); this._forgetLastClick() } else { this._firstClickTarget = e.target; this._lastClickTimeStamp = timeStamp } }, remove: function() { this._handlerCount--; if (this._handlerCount <= 0) { this._forgetLastClick(); $(document).off(NAMESPACED_CLICK_EVENT) } } }); registerEvent(DBLCLICK_EVENT_NAME, new DblClick); exports.name = DBLCLICK_EVENT_NAME }, /*!****************************!*\ !*** ./js/events/swipe.js ***! \****************************/ function(module, exports, __webpack_require__) { var eventUtils = __webpack_require__( /*! ./utils */ 71), GestureEmitter = __webpack_require__( /*! ./gesture/emitter.gesture */ 86), registerEmitter = __webpack_require__( /*! ./core/emitter_registrator */ 84); var SWIPE_START_EVENT = "dxswipestart", SWIPE_EVENT = "dxswipe", SWIPE_END_EVENT = "dxswipeend"; var HorizontalStrategy = { defaultItemSizeFunc: function() { return this.getElement().width() }, getBounds: function() { return [this._maxLeftOffset, this._maxRightOffset] }, calcOffsetRatio: function(e) { var endEventData = eventUtils.eventData(e); return (endEventData.x - (this._savedEventData && this._savedEventData.x || 0)) / this._itemSizeFunc().call(this, e) }, isFastSwipe: function(e) { var endEventData = eventUtils.eventData(e); return this.FAST_SWIPE_SPEED_LIMIT * Math.abs(endEventData.x - this._tickData.x) >= endEventData.time - this._tickData.time } }; var VerticalStrategy = { defaultItemSizeFunc: function() { return this.getElement().height() }, getBounds: function() { return [this._maxTopOffset, this._maxBottomOffset] }, calcOffsetRatio: function(e) { var endEventData = eventUtils.eventData(e); return (endEventData.y - (this._savedEventData && this._savedEventData.y || 0)) / this._itemSizeFunc().call(this, e) }, isFastSwipe: function(e) { var endEventData = eventUtils.eventData(e); return this.FAST_SWIPE_SPEED_LIMIT * Math.abs(endEventData.y - this._tickData.y) >= endEventData.time - this._tickData.time } }; var STRATEGIES = { horizontal: HorizontalStrategy, vertical: VerticalStrategy }; var SwipeEmitter = GestureEmitter.inherit({ TICK_INTERVAL: 300, FAST_SWIPE_SPEED_LIMIT: 10, ctor: function(element) { this.callBase(element); this.direction = "horizontal"; this.elastic = true }, _getStrategy: function() { return STRATEGIES[this.direction] }, _defaultItemSizeFunc: function() { return this._getStrategy().defaultItemSizeFunc.call(this) }, _itemSizeFunc: function() { return this.itemSizeFunc || this._defaultItemSizeFunc }, _init: function(e) { this._tickData = eventUtils.eventData(e) }, _start: function(e) { this._savedEventData = eventUtils.eventData(e); e = this._fireEvent(SWIPE_START_EVENT, e); if (!e.cancel) { this._maxLeftOffset = e.maxLeftOffset; this._maxRightOffset = e.maxRightOffset; this._maxTopOffset = e.maxTopOffset; this._maxBottomOffset = e.maxBottomOffset } }, _move: function(e) { var strategy = this._getStrategy(), moveEventData = eventUtils.eventData(e), offset = strategy.calcOffsetRatio.call(this, e); offset = this._fitOffset(offset, this.elastic); if (moveEventData.time - this._tickData.time > this.TICK_INTERVAL) { this._tickData = moveEventData } this._fireEvent(SWIPE_EVENT, e, { offset: offset }); e.preventDefault() }, _end: function(e) { var strategy = this._getStrategy(), offsetRatio = strategy.calcOffsetRatio.call(this, e), isFast = strategy.isFastSwipe.call(this, e), startOffset = offsetRatio, targetOffset = this._calcTargetOffset(offsetRatio, isFast); startOffset = this._fitOffset(startOffset, this.elastic); targetOffset = this._fitOffset(targetOffset, false); this._fireEvent(SWIPE_END_EVENT, e, { offset: startOffset, targetOffset: targetOffset }) }, _fitOffset: function(offset, elastic) { var strategy = this._getStrategy(), bounds = strategy.getBounds.call(this); if (offset < -bounds[0]) { return elastic ? (-2 * bounds[0] + offset) / 3 : -bounds[0] } if (offset > bounds[1]) { return elastic ? (2 * bounds[1] + offset) / 3 : bounds[1] } return offset }, _calcTargetOffset: function(offsetRatio, isFast) { var result; if (isFast) { result = Math.ceil(Math.abs(offsetRatio)); if (offsetRatio < 0) { result = -result } } else { result = Math.round(offsetRatio) } return result } }); registerEmitter({ emitter: SwipeEmitter, events: [SWIPE_START_EVENT, SWIPE_EVENT, SWIPE_END_EVENT] }); exports.swipe = SWIPE_EVENT; exports.start = SWIPE_START_EVENT; exports.end = SWIPE_END_EVENT }, /*!********************************!*\ !*** ./js/events/transform.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), mathUtils = __webpack_require__( /*! ../core/utils/math */ 87), errors = __webpack_require__( /*! ../core/errors */ 7), eventUtils = __webpack_require__( /*! ./utils */ 71), Emitter = __webpack_require__( /*! ./core/emitter */ 83), registerEmitter = __webpack_require__( /*! ./core/emitter_registrator */ 84); var DX_PREFIX = "dx", TRANSFORM = "transform", TRANSLATE = "translate", ZOOM = "zoom", PINCH = "pinch", ROTATE = "rotate", START_POSTFIX = "start", UPDATE_POSTFIX = "", END_POSTFIX = "end"; var eventAliases = []; var addAlias = function(eventName, eventArgs) { eventAliases.push({ name: eventName, args: eventArgs }) }; addAlias(TRANSFORM, { scale: true, deltaScale: true, rotation: true, deltaRotation: true, translation: true, deltaTranslation: true }); addAlias(TRANSLATE, { translation: true, deltaTranslation: true }); addAlias(ZOOM, { scale: true, deltaScale: true }); addAlias(PINCH, { scale: true, deltaScale: true }); addAlias(ROTATE, { rotation: true, deltaRotation: true }); var getVector = function(first, second) { return { x: second.pageX - first.pageX, y: -second.pageY + first.pageY, centerX: .5 * (second.pageX + first.pageX), centerY: .5 * (second.pageY + first.pageY) } }; var getEventVector = function(e) { var pointers = e.pointers; return getVector(pointers[0], pointers[1]) }; var getDistance = function(vector) { return Math.sqrt(vector.x * vector.x + vector.y * vector.y) }; var getScale = function(firstVector, secondVector) { return getDistance(firstVector) / getDistance(secondVector) }; var getRotation = function(firstVector, secondVector) { var scalarProduct = firstVector.x * secondVector.x + firstVector.y * secondVector.y; var distanceProduct = getDistance(firstVector) * getDistance(secondVector); if (0 === distanceProduct) { return 0 } var sign = mathUtils.sign(firstVector.x * secondVector.y - secondVector.x * firstVector.y); var angle = Math.acos(mathUtils.fitIntoRange(scalarProduct / distanceProduct, -1, 1)); return sign * angle }; var getTranslation = function(firstVector, secondVector) { return { x: firstVector.centerX - secondVector.centerX, y: firstVector.centerY - secondVector.centerY } }; var TransformEmitter = Emitter.inherit({ configure: function(data, eventName) { if (eventName.indexOf(ZOOM) > -1) { errors.log("W0005", eventName, "15.1", "Use '" + eventName.replace(ZOOM, PINCH) + "' event instead") } this.callBase(data) }, validatePointers: function(e) { return eventUtils.hasTouches(e) > 1 }, start: function(e) { this._accept(e); var startVector = getEventVector(e); this._startVector = startVector; this._prevVector = startVector; this._fireEventAliases(START_POSTFIX, e) }, move: function(e) { var currentVector = getEventVector(e), eventArgs = this._getEventArgs(currentVector); this._fireEventAliases(UPDATE_POSTFIX, e, eventArgs); this._prevVector = currentVector }, end: function(e) { var eventArgs = this._getEventArgs(this._prevVector); this._fireEventAliases(END_POSTFIX, e, eventArgs) }, _getEventArgs: function(vector) { return { scale: getScale(vector, this._startVector), deltaScale: getScale(vector, this._prevVector), rotation: getRotation(vector, this._startVector), deltaRotation: getRotation(vector, this._prevVector), translation: getTranslation(vector, this._startVector), deltaTranslation: getTranslation(vector, this._prevVector) } }, _fireEventAliases: function(eventPostfix, originalEvent, eventArgs) { eventArgs = eventArgs || {}; $.each(eventAliases, function(_, eventAlias) { var args = {}; $.each(eventAlias.args, function(name) { if (name in eventArgs) { args[name] = eventArgs[name] } }); this._fireEvent(DX_PREFIX + eventAlias.name + eventPostfix, originalEvent, args) }.bind(this)) } }); var eventNames = $.map(eventAliases, function(eventAlias) { var eventNames = []; $.each([START_POSTFIX, UPDATE_POSTFIX, END_POSTFIX], function(_, eventPostfix) { eventNames.push(DX_PREFIX + eventAlias.name + eventPostfix) }); return eventNames }); registerEmitter({ emitter: TransformEmitter, events: eventNames }); $.each(eventNames, function(_, eventName) { exports[eventName.substring(DX_PREFIX.length)] = eventName }) }, /*!******************************************!*\ !*** ./js/bundles/modules/parts/data.js ***! \******************************************/ function(module, exports, __webpack_require__) { var DevExpress = __webpack_require__( /*! ./core */ 5); var data = DevExpress.data = __webpack_require__( /*! ../../../bundles/modules/data */ 186); data.odata = __webpack_require__( /*! ../../../bundles/modules/data.odata */ 191); module.exports = data }, /*!************************************!*\ !*** ./js/bundles/modules/data.js ***! \************************************/ function(module, exports, __webpack_require__) { var DevExpress = __webpack_require__( /*! ./core */ 6); module.exports = DevExpress.data = DevExpress.data || {}; Object.defineProperty(DevExpress.data, "errorHandler", { get: function() { /*! ../../data/errors */ return __webpack_require__(155).errorHandler }, set: function(value) { __webpack_require__( /*! ../../data/errors */ 155).errorHandler = value } }); Object.defineProperty(DevExpress.data, "_errorHandler", { get: function() { /*! ../../data/errors */ return __webpack_require__(155)._errorHandler }, set: function(value) { __webpack_require__( /*! ../../data/errors */ 155)._errorHandler = value } }); DevExpress.data.DataSource = __webpack_require__( /*! ../../data/data_source */ 187); DevExpress.data.query = __webpack_require__( /*! ../../data/query */ 159); DevExpress.data.Store = __webpack_require__( /*! ../../data/abstract_store */ 154); DevExpress.data.ArrayStore = __webpack_require__( /*! ../../data/array_store */ 158); DevExpress.data.CustomStore = __webpack_require__( /*! ../../data/custom_store */ 162); DevExpress.data.LocalStore = __webpack_require__( /*! ../../data/local_store */ 188); DevExpress.data.base64_encode = __webpack_require__( /*! ../../data/utils */ 137).base64_encode; DevExpress.data.Guid = __webpack_require__( /*! ../../core/guid */ 151); DevExpress.data.utils = {}; DevExpress.data.utils.compileGetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileGetter; DevExpress.data.utils.compileSetter = __webpack_require__( /*! ../../core/utils/data */ 50).compileSetter; DevExpress.EndpointSelector = __webpack_require__( /*! ../../data/endpoint_selector */ 189); DevExpress.data.queryImpl = __webpack_require__( /*! ../../data/query */ 159).queryImpl; DevExpress.data.queryAdapters = __webpack_require__( /*! ../../data/query_adapters */ 161); var dataUtils = __webpack_require__( /*! ../../data/utils */ 137); DevExpress.data.utils.normalizeBinaryCriterion = dataUtils.normalizeBinaryCriterion; DevExpress.data.utils.normalizeSortingInfo = dataUtils.normalizeSortingInfo; DevExpress.data.utils.errorMessageFromXhr = dataUtils.errorMessageFromXhr; DevExpress.data.utils.aggregators = dataUtils.aggregators; DevExpress.data.utils.keysEqual = dataUtils.keysEqual; DevExpress.data.utils.isDisjunctiveOperator = dataUtils.isDisjunctiveOperator; DevExpress.data.utils.isConjunctiveOperator = dataUtils.isConjunctiveOperator; DevExpress.data.utils.processRequestResultLock = dataUtils.processRequestResultLock; DevExpress.data.utils.toComparable = __webpack_require__( /*! ../../core/utils/data */ 50).toComparable; DevExpress.data.utils.multiLevelGroup = __webpack_require__( /*! ../../data/store_helper */ 156).multiLevelGroup; DevExpress.data.utils.arrangeSortingInfo = __webpack_require__( /*! ../../data/store_helper */ 156).arrangeSortingInfo; DevExpress.data.utils.normalizeDataSourceOptions = __webpack_require__( /*! ../../data/data_source/data_source */ 153).normalizeDataSourceOptions }, /*!********************************!*\ !*** ./js/data/data_source.js ***! \********************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./data_source/data_source */ 153).DataSource }, /*!********************************!*\ !*** ./js/data/local_store.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), Class = __webpack_require__( /*! ../core/class */ 25), abstract = Class.abstract, errors = __webpack_require__( /*! ./errors */ 155).errors, ArrayStore = __webpack_require__( /*! ./array_store */ 158); var LocalStoreBackend = Class.inherit({ ctor: function(store, storeOptions) { this._store = store; this._dirty = !!storeOptions.data; this.save(); var immediate = this._immediate = storeOptions.immediate; var flushInterval = Math.max(100, storeOptions.flushInterval || 1e4); if (!immediate) { var saveProxy = this.save.bind(this); setInterval(saveProxy, flushInterval); $(window).on("beforeunload", saveProxy); if (window.cordova) { document.addEventListener("pause", saveProxy, false) } } }, notifyChanged: function() { this._dirty = true; if (this._immediate) { this.save() } }, load: function() { this._store._array = this._loadImpl(); this._dirty = false }, save: function() { if (!this._dirty) { return } this._saveImpl(this._store._array); this._dirty = false }, _loadImpl: abstract, _saveImpl: abstract }); var DomLocalStoreBackend = LocalStoreBackend.inherit({ ctor: function(store, storeOptions) { var name = storeOptions.name; if (!name) { throw errors.Error("E4013") } this._key = "dx-data-localStore-" + name; this.callBase(store, storeOptions) }, _loadImpl: function() { var raw = localStorage.getItem(this._key); if (raw) { return JSON.parse(raw) } return [] }, _saveImpl: function(array) { if (!array.length) { localStorage.removeItem(this._key) } else { localStorage.setItem(this._key, JSON.stringify(array)) } } }); var localStoreBackends = { dom: DomLocalStoreBackend }; var LocalStore = ArrayStore.inherit({ ctor: function(options) { if ("string" === typeof options) { options = { name: options } } else { options = options || {} } this.callBase(options); this._backend = new localStoreBackends[options.backend || "dom"](this, options); this._backend.load() }, clear: function() { this.callBase(); this._backend.notifyChanged() }, _insertImpl: function(values) { var b = this._backend; return this.callBase(values).done(b.notifyChanged.bind(b)) }, _updateImpl: function(key, values) { var b = this._backend; return this.callBase(key, values).done(b.notifyChanged.bind(b)) }, _removeImpl: function(key) { var b = this._backend; return this.callBase(key).done(b.notifyChanged.bind(b)) } }, "local"); module.exports = LocalStore }, /*!**************************************!*\ !*** ./js/data/endpoint_selector.js ***! \**************************************/ function(module, exports, __webpack_require__) { var errors = __webpack_require__( /*! ../core/errors */ 7), proxyUrlFormatter = __webpack_require__( /*! ./proxy_url_formatter */ 190); var location = window.location, IS_WINJS_ORIGIN = "ms-appx:" === location.protocol, IS_LOCAL_ORIGIN = isLocalHostName(location.hostname); function isLocalHostName(url) { return /^(localhost$|127\.)/i.test(url) } var EndpointSelector = function(config) { this.config = config }; EndpointSelector.prototype = { urlFor: function(key) { var bag = this.config[key]; if (!bag) { throw errors.Error("E0006") } if (proxyUrlFormatter.isProxyUsed()) { return proxyUrlFormatter.formatProxyUrl(bag.local) } if (bag.production) { if (IS_WINJS_ORIGIN && !Debug.debuggerEnabled || !IS_WINJS_ORIGIN && !IS_LOCAL_ORIGIN) { return bag.production } } return bag.local } }; module.exports = EndpointSelector }, /*!****************************************!*\ !*** ./js/data/proxy_url_formatter.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), location = window.location, DXPROXY_HOST = "dxproxy.devexpress.com:8000", IS_DXPROXY_ORIGIN = location.host === DXPROXY_HOST, urlMapping = {}; var parseUrl = function() { var a = document.createElement("a"), props = ["protocol", "hostname", "port", "pathname", "search", "hash"]; var normalizePath = function(value) { if ("/" !== value.charAt(0)) { value = "/" + value } return value }; return function(url) { a.href = url; var result = {}; $.each(props, function() { result[this] = a[this] }); result.pathname = normalizePath(result.pathname); return result } }(); var extractProxyAppId = function() { return location.pathname.split("/")[1] }; module.exports = { parseUrl: parseUrl, isProxyUsed: function() { return IS_DXPROXY_ORIGIN }, formatProxyUrl: function(localUrl) { var urlData = parseUrl(localUrl); if (!/^(localhost$|127\.)/i.test(urlData.hostname)) { return localUrl } var proxyUrlPart = DXPROXY_HOST + "/" + extractProxyAppId() + "_" + urlData.port; urlMapping[proxyUrlPart] = urlData.hostname + ":" + urlData.port; var resultUrl = "http://" + proxyUrlPart + urlData.pathname + urlData.search; return resultUrl }, formatLocalUrl: function(proxyUrl) { if (proxyUrl.indexOf(DXPROXY_HOST) < 0) { return proxyUrl } var resultUrl = proxyUrl; for (var proxyUrlPart in urlMapping) { if (urlMapping.hasOwnProperty(proxyUrlPart)) { if (proxyUrl.indexOf(proxyUrlPart) >= 0) { resultUrl = proxyUrl.replace(proxyUrlPart, urlMapping[proxyUrlPart]); break } } } return resultUrl } } }, /*!******************************************!*\ !*** ./js/bundles/modules/data.odata.js ***! \******************************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./data */ 186); DevExpress.data.ODataStore = __webpack_require__( /*! ../../data/odata/store */ 192); DevExpress.data.ODataContext = __webpack_require__( /*! ../../data/odata/context */ 196); DevExpress.data.utils = DevExpress.data.utils || {}; DevExpress.data.utils.odata = {}; DevExpress.data.utils.odata.keyConverters = __webpack_require__( /*! ../../data/odata/utils */ 193).keyConverters; DevExpress.data.EdmLiteral = __webpack_require__( /*! ../../data/odata/utils */ 193).EdmLiteral; var ODataUtilsModule = __webpack_require__( /*! ../../data/odata/utils */ 193); DevExpress.data.utils.odata.serializePropName = ODataUtilsModule.serializePropName; DevExpress.data.utils.odata.serializeValue = ODataUtilsModule.serializeValue; DevExpress.data.utils.odata.serializeKey = ODataUtilsModule.serializeKey; DevExpress.data.utils.odata.sendRequest = ODataUtilsModule.sendRequest; DevExpress.data.OData__internals = ODataUtilsModule.OData__internals; DevExpress.data.queryAdapters = DevExpress.data.queryAdapters || {}; DevExpress.data.queryAdapters.odata = __webpack_require__( /*! ../../data/odata/query_adapter */ 195).odata }, /*!********************************!*\ !*** ./js/data/odata/store.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), odataUtils = __webpack_require__( /*! ./utils */ 193), proxyUrlFormatter = __webpack_require__( /*! ../proxy_url_formatter */ 190), errors = __webpack_require__( /*! ../errors */ 155).errors, query = __webpack_require__( /*! ../query */ 159), Store = __webpack_require__( /*! ../abstract_store */ 154), mixins = __webpack_require__( /*! ./mixins */ 194), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; __webpack_require__( /*! ./query_adapter */ 195); var ANONYMOUS_KEY_NAME = "5d46402c-7899-4ea9-bd81-8b73c47c7683"; function expandKeyType(key, keyType) { var result = {}; result[key] = keyType; return result } function mergeFieldTypesWithKeyType(fieldTypes, keyType) { var result = {}; for (var field in fieldTypes) { result[field] = fieldTypes[field] } for (var keyName in keyType) { if (keyName in result) { if (result[keyName] !== keyType[keyName]) { errors.log("W4001", keyName) } } else { result[keyName] = keyType[keyName] } } return result } var ODataStore = Store.inherit({ ctor: function(options) { this.callBase(options); this._extractServiceOptions(options); var key = this.key(), fieldTypes = options.fieldTypes, keyType = options.keyType; if (keyType) { var keyTypeIsString = "string" === typeof keyType; if (!key) { key = keyTypeIsString ? ANONYMOUS_KEY_NAME : Object.keys(keyType); this._legacyAnonymousKey = key } if (keyTypeIsString) { keyType = expandKeyType(key, keyType) } fieldTypes = mergeFieldTypesWithKeyType(fieldTypes, keyType) } this._fieldTypes = fieldTypes || {}; if (2 === this.version()) { this._updateMethod = "MERGE" } else { this._updateMethod = "PATCH" } }, _customLoadOptions: function() { return ["expand", "customQueryParams"] }, _byKeyImpl: function(key, extraOptions) { var params = {}; if (extraOptions) { if (extraOptions.expand) { params.$expand = $.map($.makeArray(extraOptions.expand), odataUtils.serializePropName).join() } } return this._sendRequest(this._byKeyUrl(key), "GET", params) }, createQuery: function(loadOptions) { var url, queryOptions; loadOptions = loadOptions || {}; queryOptions = { adapter: "odata", beforeSend: this._beforeSend, errorHandler: this._errorHandler, jsonp: this._jsonp, version: this._version, withCredentials: this._withCredentials, expand: loadOptions.expand, requireTotalCount: loadOptions.requireTotalCount, deserializeDates: this._deserializeDates, fieldTypes: this._fieldTypes }; if (commonUtils.isDefined(loadOptions.urlOverride)) { url = loadOptions.urlOverride } else { url = this._url } if (loadOptions.customQueryParams) { var params = mixins.escapeServiceOperationParams(loadOptions.customQueryParams, this.version()); if (4 === this.version()) { url = mixins.formatFunctionInvocationUrl(url, params) } else { queryOptions.params = params } } return query(url, queryOptions) }, _insertImpl: function(values) { this._requireKey(); var that = this, d = $.Deferred(); when(this._sendRequest(this._url, "POST", null, values)).done(function(serverResponse) { d.resolve(values, that.keyOf(serverResponse)) }).fail(d.reject); return d.promise() }, _updateImpl: function(key, values) { var d = $.Deferred(); when(this._sendRequest(this._byKeyUrl(key), this._updateMethod, null, values)).done(function() { d.resolve(key, values) }).fail(d.reject); return d.promise() }, _removeImpl: function(key) { var d = $.Deferred(); when(this._sendRequest(this._byKeyUrl(key), "DELETE")).done(function() { d.resolve(key) }).fail(d.reject); return d.promise() }, _convertKey: function(value) { var result = value, fieldTypes = this._fieldTypes, key = this.key() || this._legacyAnonymousKey; if (Array.isArray(key)) { result = {}; for (var keyIndex in key) { var keyName = key[keyIndex]; result[keyName] = odataUtils.convertPrimitiveValue(fieldTypes[keyName], value[keyName]) } } else { if (fieldTypes[key]) { result = odataUtils.convertPrimitiveValue(fieldTypes[key], value) } } return result }, _byKeyUrl: function(value, useOriginalHost) { var baseUrl = useOriginalHost ? proxyUrlFormatter.formatLocalUrl(this._url) : this._url; var convertedKey = this._convertKey(value); return baseUrl + "(" + encodeURIComponent(odataUtils.serializeKey(convertedKey, this._version)) + ")" } }, "odata").include(mixins.SharedMethods); module.exports = ODataStore }, /*!********************************!*\ !*** ./js/data/odata/utils.js ***! \********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), Guid = __webpack_require__( /*! ../../core/guid */ 151), isDefined = commonUtils.isDefined, errors = __webpack_require__( /*! ../errors */ 155).errors, dataUtils = __webpack_require__( /*! ../utils */ 137); var GUID_REGEX = /^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$/; var VERBOSE_DATE_REGEX = /^\/Date\((-?\d+)((\+|-)?(\d+)?)\)\/$/; var ISO8601_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[-+]{1}\d{2}(:?)(\d{2})?)?$/; var JSON_VERBOSE_MIME_TYPE = "application/json;odata=verbose"; function formatISO8601(date, skipZeroTime, skipTimezone) { var bag = []; var pad = function(n) { if (n < 10) { return "0".concat(n) } return String(n) }; var isZeroTime = function() { return date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds() < 1 }; bag.push(date.getFullYear()); bag.push("-"); bag.push(pad(date.getMonth() + 1)); bag.push("-"); bag.push(pad(date.getDate())); if (!(skipZeroTime && isZeroTime())) { bag.push("T"); bag.push(pad(date.getHours())); bag.push(":"); bag.push(pad(date.getMinutes())); bag.push(":"); bag.push(pad(date.getSeconds())); if (date.getMilliseconds()) { bag.push("."); bag.push(date.getMilliseconds()) } if (!skipTimezone) { bag.push("Z") } } return bag.join("") } function parseISO8601(isoString) { var result = new Date(60 * new Date(0).getTimezoneOffset() * 1e3), chunks = isoString.replace("Z", "").split("T"), date = /(\d{4})-(\d{2})-(\d{2})/.exec(chunks[0]), time = /(\d{2}):(\d{2}):(\d{2})\.?(\d{0,7})?/.exec(chunks[1]); result.setFullYear(Number(date[1])); result.setMonth(Number(date[2]) - 1); result.setDate(Number(date[3])); if (Array.isArray(time) && time.length) { result.setHours(Number(time[1])); result.setMinutes(Number(time[2])); result.setSeconds(Number(time[3])); result.setMilliseconds(Number(String(time[4]).substr(0, 3)) || 0) } return result } function isAbsoluteUrl(url) { return /^(?:[a-z]+:)?\/\//i.test(url) } function toAbsoluteUrl(basePath, relativePath) { var part; var baseParts = stripParams(basePath).split("/"); var relativeParts = relativePath.split("/"); function stripParams(url) { var index = url.indexOf("?"); if (index > -1) { return url.substr(0, index) } return url } baseParts.pop(); while (relativeParts.length) { part = relativeParts.shift(); if (".." === part) { baseParts.pop() } else { baseParts.push(part) } } return baseParts.join("/") } var ajaxOptionsForRequest = function(protocolVersion, request, options) { request = extend({ async: true, method: "get", url: "", params: {}, payload: null, headers: {}, timeout: 3e4 }, request); options = options || {}; var beforeSend = options.beforeSend; if (beforeSend) { beforeSend(request) } var method = (request.method || "get").toLowerCase(), isGet = "get" === method, useJsonp = isGet && options.jsonp, params = extend({}, request.params), ajaxData = isGet ? params : formatPayload(request.payload), qs = !isGet && $.param(params), url = request.url, contentType = !isGet && JSON_VERBOSE_MIME_TYPE; if (qs) { url += (url.indexOf("?") > -1 ? "&" : "?") + qs } if (useJsonp) { ajaxData.$format = "json" } return { url: url, data: ajaxData, dataType: useJsonp ? "jsonp" : "json", jsonp: useJsonp && "$callback", type: method, async: request.async, timeout: request.timeout, headers: request.headers, contentType: contentType, accepts: { json: [JSON_VERBOSE_MIME_TYPE, "text/plain"].join() }, xhrFields: { withCredentials: options.withCredentials } }; function formatPayload(payload) { return JSON.stringify(payload, function(key, value) { if (!(this[key] instanceof Date)) { return value } value = formatISO8601(this[key]); switch (protocolVersion) { case 2: return value.substr(0, value.length - 1); case 3: case 4: return value; default: throw errors.Error("E4002") } }) } }; var sendRequest = function(protocolVersion, request, options) { var d = $.Deferred(); var ajaxOptions = ajaxOptionsForRequest(protocolVersion, request, options); $.ajax(ajaxOptions).always(function(obj, textStatus) { var extra, transformOptions = { deserializeDates: options.deserializeDates, fieldTypes: options.fieldTypes }, tuple = interpretJsonFormat(obj, textStatus, transformOptions), error = tuple.error, data = tuple.data, nextUrl = tuple.nextUrl; if (error) { d.reject(error) } else { if (options.countOnly) { if (isFinite(tuple.count)) { d.resolve(tuple.count) } else { d.reject(new errors.Error("E4018")) } } else { if (nextUrl) { if (!isAbsoluteUrl(nextUrl)) { nextUrl = toAbsoluteUrl(ajaxOptions.url, nextUrl) } sendRequest(protocolVersion, { url: nextUrl }, options).fail(d.reject).done(function(nextData) { d.resolve(data.concat(nextData)) }) } else { if (isFinite(tuple.count)) { extra = { totalCount: tuple.count } } d.resolve(data, extra) } } } }); return d.promise() }; var formatDotNetError = function(errorObj) { var message, currentError = errorObj; if ("message" in errorObj) { if (errorObj.message.value) { message = errorObj.message.value } else { message = errorObj.message } } while (currentError = currentError.innererror || currentError.internalexception) { message = currentError.message; if (currentError.internalexception && message.indexOf("inner exception") === -1) { break } } return message }; var errorFromResponse = function(obj, textStatus) { if ("nocontent" === textStatus) { return null } var httpStatus = 200, message = "Unknown error", response = obj; if ("success" !== textStatus) { httpStatus = obj.status; message = dataUtils.errorMessageFromXhr(obj, textStatus); try { response = JSON.parse(obj.responseText) } catch (x) {} } var errorObj = response && (response.then && response || response.error || response["odata.error"] || response["@odata.error"]); if (errorObj) { message = formatDotNetError(errorObj) || message; if (200 === httpStatus) { httpStatus = 500 } if (errorObj.code) { httpStatus = Number(errorObj.code) } return extend(Error(message), { httpStatus: httpStatus, errorDetails: errorObj }) } else { if (200 !== httpStatus) { return extend(Error(message), { httpStatus: httpStatus }) } } }; var interpretJsonFormat = function(obj, textStatus, transformOptions) { var value, error = errorFromResponse(obj, textStatus); if (error) { return { error: error } } if (!typeUtils.isPlainObject(obj)) { return { data: obj } } if ("d" in obj && (Array.isArray(obj.d) || commonUtils.isObject(obj.d))) { value = interpretVerboseJsonFormat(obj, textStatus) } else { value = interpretLightJsonFormat(obj, textStatus) } transformTypes(value, transformOptions); return value }; var interpretVerboseJsonFormat = function(obj) { var data = obj.d; if (!isDefined(data)) { return { error: Error("Malformed or unsupported JSON response received") } } data = data; if (isDefined(data.results)) { data = data.results } return { data: data, nextUrl: obj.d.__next, count: parseInt(obj.d.__count, 10) } }; var interpretLightJsonFormat = function(obj) { var data = obj; if (isDefined(data.value)) { data = data.value } return { data: data, nextUrl: obj["@odata.nextLink"], count: parseInt(obj["@odata.count"], 10) } }; var EdmLiteral = Class.inherit({ ctor: function(value) { this._value = value }, valueOf: function() { return this._value } }); var transformTypes = function(obj, options) { options = options || {}; $.each(obj, function(key, value) { if (null !== value && "object" === typeof value) { if ("results" in value) { obj[key] = value.results } transformTypes(obj[key], options) } else { if ("string" === typeof value) { var fieldTypes = options.fieldTypes, canBeGuid = !fieldTypes || "String" !== fieldTypes[key]; if (canBeGuid && GUID_REGEX.test(value)) { obj[key] = new Guid(value) } if (false !== options.deserializeDates) { if (value.match(VERBOSE_DATE_REGEX)) { var date = new Date(Number(RegExp.$1) + 60 * RegExp.$2 * 1e3); obj[key] = new Date(date.valueOf() + 60 * date.getTimezoneOffset() * 1e3) } else { if (ISO8601_DATE_REGEX.test(value)) { obj[key] = new Date(parseISO8601(obj[key]).valueOf()) } } } } } }) }; var serializeDate = function(date) { return "datetime'" + formatISO8601(date, true, true) + "'" }; var serializeString = function(value) { return "'" + value.replace(/'/g, "''") + "'" }; var serializePropName = function(propName) { if (propName instanceof EdmLiteral) { return propName.valueOf() } return propName.replace(/\./g, "/") }; var serializeValueV4 = function(value) { if (value instanceof Date) { return formatISO8601(value, false, false) } if (value instanceof Guid) { return value.valueOf() } if (Array.isArray(value)) { return "[" + value.map(function(item) { return serializeValueV4(item) }).join(",") + "]" } return serializeValueV2(value) }; var serializeValueV2 = function(value) { if (value instanceof Date) { return serializeDate(value) } if (value instanceof Guid) { return "guid'" + value + "'" } if (value instanceof EdmLiteral) { return value.valueOf() } if ("string" === typeof value) { return serializeString(value) } return String(value) }; var serializeValue = function(value, protocolVersion) { switch (protocolVersion) { case 2: case 3: return serializeValueV2(value); case 4: return serializeValueV4(value); default: throw errors.Error("E4002") } }; var serializeKey = function(key, protocolVersion) { if (typeUtils.isPlainObject(key)) { var parts = []; $.each(key, function(k, v) { parts.push(serializePropName(k) + "=" + serializeValue(v, protocolVersion)) }); return parts.join() } return serializeValue(key, protocolVersion) }; var keyConverters = { String: function(value) { return value + "" }, Int32: function(value) { return Math.floor(value) }, Int64: function(value) { if (value instanceof EdmLiteral) { return value } return new EdmLiteral(value + "L") }, Guid: function(value) { if (value instanceof Guid) { return value } return new Guid(value) }, Boolean: function(value) { return !!value }, Single: function(value) { if (value instanceof EdmLiteral) { return value } return new EdmLiteral(value + "f") }, Decimal: function(value) { if (value instanceof EdmLiteral) { return value } return new EdmLiteral(value + "m") } }; var convertPrimitiveValue = function(type, value) { var converter = keyConverters[type]; if (!converter) { throw errors.Error("E4014", type) } return converter(value) }; exports.sendRequest = sendRequest; exports.serializePropName = serializePropName; exports.serializeValue = serializeValue; exports.serializeKey = serializeKey; exports.keyConverters = keyConverters; exports.convertPrimitiveValue = convertPrimitiveValue; exports.EdmLiteral = EdmLiteral; exports.OData__internals = { interpretJsonFormat: interpretJsonFormat } }, /*!*********************************!*\ !*** ./js/data/odata/mixins.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), stringUtils = __webpack_require__( /*! ../../core/utils/string */ 18), odataUtils = __webpack_require__( /*! ./utils */ 193); __webpack_require__( /*! ./query_adapter */ 195); var DEFAULT_PROTOCOL_VERSION = 2; var formatFunctionInvocationUrl = function(baseUrl, args) { return stringUtils.format("{0}({1})", baseUrl, $.map(args || {}, function(value, key) { return stringUtils.format("{0}={1}", key, value) }).join(",")) }; var escapeServiceOperationParams = function(params, version) { if (!params) { return params } var result = {}; $.each(params, function(k, v) { result[k] = odataUtils.serializeValue(v, version) }); return result }; var SharedMethods = { _extractServiceOptions: function(options) { options = options || {}; this._url = String(options.url).replace(/\/+$/, ""); this._beforeSend = options.beforeSend; this._jsonp = options.jsonp; this._version = options.version || DEFAULT_PROTOCOL_VERSION; this._withCredentials = options.withCredentials; this._deserializeDates = options.deserializeDates }, _sendRequest: function(url, method, params, payload) { return odataUtils.sendRequest(this.version(), { url: url, method: method, params: params || {}, payload: payload }, { beforeSend: this._beforeSend, jsonp: this._jsonp, withCredentials: this._withCredentials, deserializeDates: this._deserializeDates }) }, version: function() { return this._version } }; exports.SharedMethods = SharedMethods; exports.escapeServiceOperationParams = escapeServiceOperationParams; exports.formatFunctionInvocationUrl = formatFunctionInvocationUrl }, /*!****************************************!*\ !*** ./js/data/odata/query_adapter.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, queryAdapters = __webpack_require__( /*! ../query_adapters */ 161), odataUtils = __webpack_require__( /*! ./utils */ 193), serializePropName = odataUtils.serializePropName, errors = __webpack_require__( /*! ../errors */ 155).errors, dataUtils = __webpack_require__( /*! ../utils */ 137), isFunction = commonUtils.isFunction, isPlainObject = typeUtils.isPlainObject, grep = commonUtils.grep; var DEFAULT_PROTOCOL_VERSION = 2; var compileCriteria = function() { var protocolVersion, fieldTypes; var createBinaryOperationFormatter = function(op) { return function(prop, val) { return prop + " " + op + " " + val } }; var createStringFuncFormatter = function(op, reverse) { return function(prop, val) { var bag = [op, "("]; if (reverse) { bag.push(val, ",", prop) } else { bag.push(prop, ",", val) } bag.push(")"); return bag.join("") } }; var formatters = { "=": createBinaryOperationFormatter("eq"), "<>": createBinaryOperationFormatter("ne"), ">": createBinaryOperationFormatter("gt"), ">=": createBinaryOperationFormatter("ge"), "<": createBinaryOperationFormatter("lt"), "<=": createBinaryOperationFormatter("le"), startswith: createStringFuncFormatter("startswith"), endswith: createStringFuncFormatter("endswith") }; var formattersV2 = extend({}, formatters, { contains: createStringFuncFormatter("substringof", true), notcontains: createStringFuncFormatter("not substringof", true) }); var formattersV4 = extend({}, formatters, { contains: createStringFuncFormatter("contains"), notcontains: createStringFuncFormatter("not contains") }); var compileBinary = function(criteria) { criteria = dataUtils.normalizeBinaryCriterion(criteria); var op = criteria[1], formatters = 4 === protocolVersion ? formattersV4 : formattersV2, formatter = formatters[op.toLowerCase()]; if (!formatter) { throw errors.Error("E4003", op) } var fieldName = criteria[0], value = criteria[2]; if (fieldTypes && fieldTypes[fieldName]) { value = odataUtils.convertPrimitiveValue(fieldTypes[fieldName], value) } return formatter(serializePropName(fieldName), odataUtils.serializeValue(value, protocolVersion)) }; var compileUnary = function(criteria) { var op = criteria[0], crit = compileCore(criteria[1]); if ("!" === op) { return "not (" + crit + ")" } throw errors.Error("E4003", op) }; var compileGroup = function(criteria) { var groupOperator, nextGroupOperator, bag = []; $.each(criteria, function(index, criterion) { if (Array.isArray(criterion)) { if (bag.length > 1 && groupOperator !== nextGroupOperator) { throw new errors.Error("E4019") } bag.push("(" + compileCore(criterion) + ")"); groupOperator = nextGroupOperator; nextGroupOperator = "and" } else { nextGroupOperator = dataUtils.isConjunctiveOperator(this) ? "and" : "or" } }); return bag.join(" " + groupOperator + " ") }; var compileCore = function(criteria) { if (Array.isArray(criteria[0])) { return compileGroup(criteria) } if (dataUtils.isUnaryOperation(criteria)) { return compileUnary(criteria) } return compileBinary(criteria) }; return function(criteria, version, types) { fieldTypes = types; protocolVersion = version; return compileCore(criteria) } }(); var createODataQueryAdapter = function(queryOptions) { var _select, _skip, _take, _countQuery, _sorting = [], _criteria = [], _expand = queryOptions.expand, _oDataVersion = queryOptions.version || DEFAULT_PROTOCOL_VERSION; var hasSlice = function() { return _skip || void 0 !== _take }; var hasFunction = function(criterion) { for (var i = 0; i < criterion.length; i++) { if (isFunction(criterion[i])) { return true } if (Array.isArray(criterion[i]) && hasFunction(criterion[i])) { return true } } return false }; var generateSelectExpand = function() { var hasDot = function(x) { return /\./.test(x) }; var generateSelect = function() { if (!_select) { return } if (_oDataVersion < 4) { return serializePropName(_select.join()) } return grep(_select, hasDot, true).join() }; var generateExpand = function() { var generatorV2 = function() { var hash = {}; if (_expand) { $.each($.makeArray(_expand), function() { hash[serializePropName(this)] = 1 }) } if (_select) { $.each($.makeArray(_select), function() { var path = this.split("."); if (path.length < 2) { return } path.pop(); hash[serializePropName(path.join("."))] = 1 }) } return $.map(hash, function(k, v) { return v }).join() }; var generatorV4 = function() { var format = function(hash) { var formatCore = function(hash) { var result = "", select = [], expand = []; $.each(hash, function(key, value) { if (Array.isArray(value)) { [].push.apply(select, value) } if (isPlainObject(value)) { expand.push(key + formatCore(value)) } }); if (select.length || expand.length) { result += "("; if (select.length) { result += "$select=" + $.map(select, serializePropName).join() } if (expand.length) { if (select.length) { result += ";" } result += "$expand=" + $.map(expand, serializePropName).join() } result += ")" } return result }; var result = []; $.each(hash, function(key, value) { result.push(key + formatCore(value)) }); return result.join() }; var parseTree = function(exprs, root, stepper) { var parseCore = function(exprParts, root, stepper) { var result = stepper(root, exprParts.shift(), exprParts); if (false === result) { return } parseCore(exprParts, result, stepper) }; $.each(exprs, function(_, x) { parseCore(x.split("."), root, stepper) }) }; var hash = {}; if (_expand || _select) { if (_expand) { parseTree($.makeArray(_expand), hash, function(node, key, path) { node[key] = node[key] || {}; if (!path.length) { return false } return node[key] }) } if (_select) { parseTree(grep($.makeArray(_select), hasDot), hash, function(node, key, path) { if (!path.length) { node[key] = node[key] || []; node[key].push(key); return false } return node[key] = node[key] || {} }) } return format(hash) } }; if (_oDataVersion < 4) { return generatorV2() } return generatorV4() }; var tuple = { $select: generateSelect() || void 0, $expand: generateExpand() || void 0 }; return tuple }; var requestData = function() { var result = {}; if (!_countQuery) { if (_sorting.length) { result.$orderby = _sorting.join(",") } if (_skip) { result.$skip = _skip } if (void 0 !== _take) { result.$top = _take } var tuple = generateSelectExpand(); result.$select = tuple.$select; result.$expand = tuple.$expand } if (_criteria.length) { var criteria = _criteria.length < 2 ? _criteria[0] : _criteria, fieldTypes = queryOptions && queryOptions.fieldTypes; result.$filter = compileCriteria(criteria, _oDataVersion, fieldTypes) } if (_countQuery) { result.$top = 0 } if (queryOptions.requireTotalCount || _countQuery) { if (4 !== _oDataVersion) { result.$inlinecount = "allpages" } else { result.$count = "true" } } return result }; return { exec: function(url) { return odataUtils.sendRequest(_oDataVersion, { url: url, params: extend(requestData(), queryOptions && queryOptions.params) }, { beforeSend: queryOptions.beforeSend, jsonp: queryOptions.jsonp, withCredentials: queryOptions.withCredentials, countOnly: _countQuery, deserializeDates: queryOptions.deserializeDates, fieldTypes: queryOptions.fieldTypes }) }, multiSort: function(args) { var rules; if (hasSlice()) { return false } for (var i = 0; i < args.length; i++) { var rule, getter = args[i][0], desc = !!args[i][1]; if ("string" !== typeof getter) { return false } rule = serializePropName(getter); if (desc) { rule += " desc" } rules = rules || []; rules.push(rule) } _sorting = rules }, slice: function(skipCount, takeCount) { if (hasSlice()) { return false } _skip = skipCount; _take = takeCount }, filter: function(criterion) { if (hasSlice()) { return false } if (!Array.isArray(criterion)) { criterion = $.makeArray(arguments) } if (hasFunction(criterion)) { return false } if (_criteria.length) { _criteria.push("and") } _criteria.push(criterion) }, select: function(expr) { if (_select || isFunction(expr)) { return false } if (!Array.isArray(expr)) { expr = $.makeArray(arguments) } _select = expr }, count: function() { _countQuery = true } } }; queryAdapters.odata = createODataQueryAdapter; exports.odata = createODataQueryAdapter }, /*!**********************************!*\ !*** ./js/data/odata/context.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), errorsModule = __webpack_require__( /*! ../errors */ 155), ODataStore = __webpack_require__( /*! ./store */ 192), mixins = __webpack_require__( /*! ./mixins */ 194), when = __webpack_require__( /*! ../../integration/jquery/deferred */ 16).when; __webpack_require__( /*! ./query_adapter */ 195); var ODataContext = Class.inherit({ ctor: function(options) { var that = this; that._extractServiceOptions(options); that._errorHandler = options.errorHandler; $.each(options.entities || [], function(entityAlias, entityOptions) { that[entityAlias] = new ODataStore(extend({}, options, { url: that._url + "/" + encodeURIComponent(entityOptions.name || entityAlias) }, entityOptions)) }) }, get: function(operationName, params) { return this.invoke(operationName, params, "GET") }, invoke: function(operationName, params, httpMethod) { params = params || {}; httpMethod = (httpMethod || "POST").toLowerCase(); var payload, d = $.Deferred(), url = this._url + "/" + encodeURIComponent(operationName); if (4 === this.version()) { if ("get" === httpMethod) { url = mixins.formatFunctionInvocationUrl(url, mixins.escapeServiceOperationParams(params, this.version())); params = null } else { if ("post" === httpMethod) { payload = params; params = null } } } when(this._sendRequest(url, httpMethod, mixins.escapeServiceOperationParams(params, this.version()), payload)).done(function(r) { if (typeUtils.isPlainObject(r) && operationName in r) { r = r[operationName] } d.resolve(r) }).fail([this._errorHandler, errorsModule._errorHandler, d.reject]); return d.promise() }, objectLink: function(entityAlias, key) { var store = this[entityAlias]; if (!store) { throw errorsModule.errors.Error("E4015", entityAlias) } if (!commonUtils.isDefined(key)) { return null } return { __metadata: { uri: store._byKeyUrl(key, true) } } } }).include(mixins.SharedMethods); module.exports = ODataContext }, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , /*!*********************************************!*\ !*** ./js/core/utils/date_serialization.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var config = __webpack_require__( /*! ../config */ 15), commonUtils = __webpack_require__( /*! ./common */ 14), isString = commonUtils.isString, isDate = commonUtils.isDate, isNumber = commonUtils.isNumeric; var NUMBER_SERIALIZATION_FORMAT = "number", DATE_SERIALIZATION_FORMAT = "yyyy/MM/dd", DATETIME_SERIALIZATION_FORMAT = "yyyy/MM/dd HH:mm:ss"; var ISO8601_PATTERN = /^(\d{4,})(-)?(\d{2})(-)?(\d{2})(?:T(\d{2})(:)?(\d{2})?(:)?(\d{2}(?:\.(\d+))?)?)?(Z|([\+\-])(\d{2})(:)?(\d{2})?)?$/; var ISO8601_TIME_PATTERN = /^(\d{2}):(\d{2})(:(\d{2}))?$/; var ISO8601_PATTERN_PARTS = ["", "yyyy", "", "MM", "", "dd", "THH", "", "mm", "", "ss", ".SSS"]; function leftPad(text, length) { while (text.length < length) { text = "0" + text } return text } var LDML_FORMATTERS = { y: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCFullYear" : "getFullYear"]().toString(), count) }, M: function(date, count, useUtc) { return leftPad((date[useUtc ? "getUTCMonth" : "getMonth"]() + 1).toString(), Math.min(count, 2)) }, d: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCDate" : "getDate"]().toString(), Math.min(count, 2)) }, H: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCHours" : "getHours"]().toString(), Math.min(count, 2)) }, m: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCMinutes" : "getMinutes"]().toString(), Math.min(count, 2)) }, s: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCSeconds" : "getSeconds"]().toString(), Math.min(count, 2)) }, S: function(date, count, useUtc) { return leftPad(date[useUtc ? "getUTCMilliseconds" : "getMilliseconds"]().toString(), 3).substr(0, count) }, x: function(date, count, useUtc) { var timezoneOffset = useUtc ? 0 : date.getTimezoneOffset(), signPart = timezoneOffset > 0 ? "-" : "+", timezoneOffsetAbs = Math.abs(timezoneOffset), hours = Math.floor(timezoneOffsetAbs / 60), minutes = timezoneOffsetAbs % 60, hoursPart = leftPad(hours.toString(), 2), minutesPart = leftPad(minutes.toString(), 2); return signPart + hoursPart + (count >= 3 ? ":" : "") + (count > 1 || minutes ? minutesPart : "") }, X: function(date, count, useUtc) { if (useUtc || !date.getTimezoneOffset()) { return "Z" } return LDML_FORMATTERS.x(date, count, useUtc) }, Z: function(date, count, useUtc) { return LDML_FORMATTERS.X(date, count >= 5 ? 3 : 2, useUtc) } }; var formatDate = function(date, format) { var charIndex, formatter, char, isCurrentCharEqualsNext, charCount = 0, separator = "'", isEscaping = false, result = ""; if (!date) { return null } if (!format) { return date } var useUtc = "Z" === format[format.length - 1] || "'Z'" === format.slice(-3); for (charIndex = 0; charIndex < format.length; charIndex++) { char = format[charIndex]; formatter = LDML_FORMATTERS[char]; isCurrentCharEqualsNext = char === format[charIndex + 1]; charCount++; if (!isCurrentCharEqualsNext) { if (formatter && !isEscaping) { result += formatter(date, charCount, useUtc) } charCount = 0 } if (char === separator && !isCurrentCharEqualsNext) { isEscaping = !isEscaping } else { if (isEscaping || !formatter) { result += char } } if (char === separator && isCurrentCharEqualsNext) { charIndex++ } } return result }; var dateParser = function(text, skipISO8601Parsing) { var result; var parsedValue; if (isString(text) && !skipISO8601Parsing) { result = parseISO8601String(text) } if (!result) { parsedValue = !isDate(text) && Date.parse(text); result = isNumber(parsedValue) ? new Date(parsedValue) : text } return result }; var parseISO8601String = function(text) { var parts = text.match(ISO8601_PATTERN); var timePart = function(part) { return +part || 0 }; if (!parts) { parts = text.match(ISO8601_TIME_PATTERN); if (parts) { return new Date(0, 0, 0, timePart(parts[1]), timePart(parts[2]), timePart(parts[4])) } return } var year = parts[1], month = --parts[3], day = parts[5], timeZoneHour = 0, timeZoneMinute = 0; timeZoneHour = timePart(parts[14]); timeZoneMinute = timePart(parts[16]); if ("-" === parts[13]) { timeZoneHour = -timeZoneHour; timeZoneMinute = -timeZoneMinute } var hour = timePart(parts[6]) - timeZoneHour, minute = timePart(parts[8]) - timeZoneMinute, second = timePart(parts[10]); if (!!parts[12]) { return new Date(Date.UTC(year, month, day, hour, minute, second)) } return new Date(year, month, day, hour, minute, second) }; var getIso8601Format = function(text, useUtc) { var parts = text.match(ISO8601_PATTERN), result = ""; if (!parts) { parts = text.match(ISO8601_TIME_PATTERN); if (parts) { return parts[3] ? "HH:mm:ss" : "HH:mm" } return } for (var i = 1; i < ISO8601_PATTERN_PARTS.length; i++) { if (parts[i]) { result += ISO8601_PATTERN_PARTS[i] || parts[i] } } if ("Z" === parts[12]) { result += "'Z'" } if (parts[14]) { if (parts[15]) { result += "xxx" } else { if (parts[16]) { result += "xx" } else { result += "x" } } } return result }; var deserializeDate = function(value) { if ("number" === typeof value) { return new Date(value) } return dateParser(value, !config().forceIsoDateParsing) }; var serializeDate = function(value, serializationFormat) { if (!serializationFormat) { return value } if (!isDate(value)) { return null } if (serializationFormat === NUMBER_SERIALIZATION_FORMAT) { return value && value.valueOf ? value.valueOf() : null } return formatDate(value, serializationFormat) }; var getDateSerializationFormat = function(value) { if ("number" === typeof value) { return NUMBER_SERIALIZATION_FORMAT } else { if (isString(value)) { var format; if (config().forceIsoDateParsing) { format = getIso8601Format(value) } if (format) { return format } else { if (value.indexOf(":") >= 0) { return DATETIME_SERIALIZATION_FORMAT } else { return DATE_SERIALIZATION_FORMAT } } } else { if (value) { return null } } } }; module.exports = { dateParser: dateParser, deserializeDate: deserializeDate, serializeDate: serializeDate, getDateSerializationFormat: getDateSerializationFormat } }, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , /*!*****************************************!*\ !*** ./js/bundles/modules/parts/viz.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var DevExpress = __webpack_require__( /*! ./core */ 5); __webpack_require__( /*! ./data */ 185); var viz = DevExpress.viz = __webpack_require__( /*! ../../../bundles/modules/viz */ 507); viz.currentTheme = __webpack_require__( /*! ../../../viz/themes */ 508).currentTheme; viz.registerTheme = __webpack_require__( /*! ../../../viz/themes */ 508).registerTheme; viz.exportFromMarkup = __webpack_require__( /*! ../../../viz/export */ 510).exportFromMarkup; viz.getMarkup = __webpack_require__( /*! ../../../viz/export */ 510).getMarkup; viz.currentPalette = __webpack_require__( /*! ../../../viz/palette */ 512).currentPalette; viz.getPalette = __webpack_require__( /*! ../../../viz/palette */ 512).getPalette; viz.registerPalette = __webpack_require__( /*! ../../../viz/palette */ 512).registerPalette; viz.refreshTheme = __webpack_require__( /*! ../../../viz/themes */ 508).refreshTheme; viz.dxChart = __webpack_require__( /*! ../../../viz/chart */ 513); viz.dxPieChart = __webpack_require__( /*! ../../../viz/pie_chart */ 584); viz.dxPolarChart = __webpack_require__( /*! ../../../viz/polar_chart */ 586); viz.dxLinearGauge = __webpack_require__( /*! ../../../viz/linear_gauge */ 587); viz.dxCircularGauge = __webpack_require__( /*! ../../../viz/circular_gauge */ 597); viz.dxBarGauge = __webpack_require__( /*! ../../../viz/bar_gauge */ 601); viz.dxRangeSelector = __webpack_require__( /*! ../../../viz/range_selector */ 603); viz.dxVectorMap = __webpack_require__( /*! ../../../viz/vector_map */ 613); viz.map = {}; viz.map.sources = {}; viz.map.projection = __webpack_require__( /*! ../../../viz/vector_map/projection */ 626).projection; viz.dxSparkline = __webpack_require__( /*! ../../../viz/sparkline */ 627); viz.dxBullet = __webpack_require__( /*! ../../../viz/bullet */ 630); viz.dxTreeMap = __webpack_require__( /*! ../../../viz/tree_map */ 632); var core = {}; viz.core = core; core.currentTheme = __webpack_require__( /*! ../../../viz/themes */ 508).currentTheme; core.registerTheme = __webpack_require__( /*! ../../../viz/themes */ 508).registerTheme; core.currentPalette = __webpack_require__( /*! ../../../viz/palette */ 512).currentPalette; core.getPalette = __webpack_require__( /*! ../../../viz/palette */ 512).getPalette; core.registerPalette = __webpack_require__( /*! ../../../viz/palette */ 512).registerPalette; viz.BaseWidget = __webpack_require__( /*! ../../../viz/core/base_widget */ 515); viz.findTheme = __webpack_require__( /*! ../../../viz/themes */ 508).findTheme; viz.refreshAll = __webpack_require__( /*! ../../../viz/themes */ 508).refreshTheme; viz.refreshPaths = __webpack_require__( /*! ../../../viz/utils */ 655).refreshPaths; viz.gauges = { __internals: {} }; viz._dashboard = {}; viz._dashboard.Renderer = __webpack_require__( /*! ../../../viz/core/renderers/renderer */ 518).Renderer; viz._dashboard.SvgElement = __webpack_require__( /*! ../../../viz/core/renderers/renderer */ 518).SvgElement; viz._dashboard.patchFontOptions = __webpack_require__( /*! ../../../viz/core/utils */ 509).patchFontOptions; module.exports = viz }, /*!***********************************!*\ !*** ./js/bundles/modules/viz.js ***! \***********************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./core */ 6); module.exports = DevExpress.viz = DevExpress.viz || {} }, /*!**************************!*\ !*** ./js/viz/themes.js ***! \**************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, vizUtils = __webpack_require__( /*! ./core/utils */ 509), themes = {}, themesMapping = {}, themesSchemeMapping = {}, _extend = extend, _each = $.each, _normalizeEnum = vizUtils.normalizeEnum, currentThemeName = null, nextCacheUid = 0, widgetsCache = {}; function findTheme(themeName) { var name = _normalizeEnum(themeName); return themes[name] || themes[themesMapping[name] || currentThemeName] } function findThemeNameByName(name, scheme) { return themesMapping[name + "." + scheme] || themesSchemeMapping[name + "." + scheme] || themesMapping[name] } function findThemeNameByPlatform(platform, version, scheme) { return findThemeNameByName(platform + version, scheme) || findThemeNameByName(platform, scheme) } function currentTheme(themeName, colorScheme) { if (!arguments.length) { return currentThemeName } var scheme = _normalizeEnum(colorScheme); currentThemeName = (themeName && themeName.platform ? findThemeNameByPlatform(_normalizeEnum(themeName.platform), themeName.version, scheme) : findThemeNameByName(_normalizeEnum(themeName), scheme)) || currentThemeName; return this } function getThemeInfo(themeName, splitter) { var k = themeName.indexOf(splitter); return k > 0 ? { name: themeName.substring(0, k), scheme: themeName.substring(k + 1) } : null } function registerThemeName(themeName, targetThemeName) { var themeInfo = getThemeInfo(themeName, ".") || getThemeInfo(themeName, "-") || { name: themeName }, name = themeInfo.name, scheme = themeInfo.scheme; if (scheme) { themesMapping[name] = themesMapping[name] || targetThemeName; themesMapping[name + "." + scheme] = themesMapping[name + "-" + scheme] = targetThemeName } else { themesMapping[name] = targetThemeName } } function registerTheme(theme, baseThemeName) { var themeName = _normalizeEnum(theme && theme.name); if (themeName) { registerThemeName(themeName, themeName); themes[themeName] = _extend(true, {}, findTheme(baseThemeName), patchTheme(theme)) } } function registerThemeAlias(alias, theme) { registerThemeName(_normalizeEnum(alias), _normalizeEnum(theme)) } function registerThemeSchemeAlias(from, to) { themesSchemeMapping[from] = to } function mergeScalar(target, field, source, sourceValue) { var _value = source ? source[field] : sourceValue; if (void 0 !== _value && void 0 === target[field]) { target[field] = _value } } function mergeObject(target, field, source, sourceValue) { var _value = source ? source[field] : sourceValue; if (void 0 !== _value) { target[field] = _extend(true, {}, _value, target[field]) } } function patchTheme(theme) { theme = _extend(true, { loadingIndicator: { font: {} }, "export": { font: {} }, legend: { font: {}, border: {} }, title: { font: {} }, tooltip: { font: {} }, "chart:common": {}, "chart:common:axis": { grid: {}, minorGrid: {}, tick: {}, minorTick: {}, title: { font: {} }, label: { font: {} } }, chart: { commonSeriesSettings: { candlestick: {} } }, pie: {}, polar: {}, gauge: { scale: { tick: {}, minorTick: {}, label: { font: {} } } }, barGauge: {}, map: { background: {} }, treeMap: { tile: { selectionStyle: { border: {} } }, group: { border: {}, selectionStyle: { border: {} }, label: { font: {} } } }, rangeSelector: { scale: { tick: {}, minorTick: {}, label: { font: {} } }, chart: {} }, sparkline: {}, bullet: {} }, theme); mergeScalar(theme.loadingIndicator, "backgroundColor", theme); mergeScalar(theme.chart.commonSeriesSettings.candlestick, "innerColor", null, theme.backgroundColor); mergeScalar(theme.map.background, "color", null, theme.backgroundColor); mergeScalar(theme.title.font, "color", null, theme.primaryTitleColor); mergeObject(theme.title, "subtitle", null, theme.title); mergeScalar(theme.legend.font, "color", null, theme.secondaryTitleColor); mergeScalar(theme.legend.border, "color", null, theme.axisColor); patchAxes(theme); _each(["chart", "pie", "polar", "gauge", "barGauge", "map", "treeMap", "rangeSelector", "sparkline", "bullet"], function(_, section) { mergeScalar(theme[section], "redrawOnResize", theme); mergeScalar(theme[section], "containerBackgroundColor", null, theme.backgroundColor); mergeObject(theme[section], "tooltip", theme) }); _each(["chart", "pie", "polar", "gauge", "barGauge", "map", "treeMap", "rangeSelector"], function(_, section) { mergeObject(theme[section], "loadingIndicator", theme); mergeObject(theme[section], "export", theme); mergeObject(theme[section], "legend", theme); mergeObject(theme[section], "title", theme) }); _each(["chart", "pie", "polar"], function(_, section) { mergeObject(theme, section, null, theme["chart:common"]) }); _each(["chart", "polar"], function(_, section) { theme[section] = theme[section] || {}; mergeObject(theme[section], "commonAxisSettings", null, theme["chart:common:axis"]) }); mergeObject(theme.rangeSelector.chart, "commonSeriesSettings", theme.chart); mergeObject(theme.rangeSelector.chart, "dataPrepareSettings", theme.chart); mergeScalar(theme.treeMap.group.border, "color", null, theme.axisColor); mergeScalar(theme.treeMap.tile.selectionStyle.border, "color", null, theme.primaryTitleColor); mergeScalar(theme.treeMap.group.selectionStyle.border, "color", null, theme.primaryTitleColor); mergeScalar(theme.treeMap.group.label.font, "color", null, theme.secondaryTitleColor); mergeScalar(theme.map.legend, "backgroundColor", theme); patchMapLayers(theme); return theme } function patchAxes(theme) { var commonAxisSettings = theme["chart:common:axis"], colorFieldName = "color"; _each([commonAxisSettings, commonAxisSettings.grid, commonAxisSettings.minorGrid, commonAxisSettings.tick, commonAxisSettings.minorTick], function(_, obj) { mergeScalar(obj, colorFieldName, null, theme.axisColor) }); mergeScalar(commonAxisSettings.title.font, colorFieldName, null, theme.secondaryTitleColor); mergeScalar(commonAxisSettings.label.font, colorFieldName, null, theme.axisLabelColor); mergeScalar(theme.gauge.scale.label.font, colorFieldName, null, theme.axisLabelColor); mergeScalar(theme.gauge.scale.tick, colorFieldName, null, theme.backgroundColor); mergeScalar(theme.gauge.scale.minorTick, colorFieldName, null, theme.backgroundColor); mergeScalar(theme.rangeSelector.scale.tick, colorFieldName, null, theme.axisColor); mergeScalar(theme.rangeSelector.scale.minorTick, colorFieldName, null, theme.axisColor); mergeScalar(theme.rangeSelector.scale.label.font, colorFieldName, null, theme.axisLabelColor) } function patchMapLayers(theme) { var map = theme.map; _each(["area", "line", "marker"], function(_, section) { mergeObject(map, "layer:" + section, null, map.layer) }); _each(["dot", "bubble", "pie", "image"], function(_, section) { mergeObject(map, "layer:marker:" + section, null, map["layer:marker"]) }) } function addCacheItem(target) { var cacheUid = ++nextCacheUid; target._cache = cacheUid; widgetsCache[cacheUid] = target } function removeCacheItem(target) { delete widgetsCache[target._cache] } function refreshTheme() { _each(widgetsCache, function() { this.refresh() }); return this } _extend(exports, { currentTheme: currentTheme, registerTheme: registerTheme, findTheme: findTheme, registerThemeAlias: registerThemeAlias, registerThemeSchemeAlias: registerThemeSchemeAlias, refreshTheme: refreshTheme, addCacheItem: addCacheItem, removeCacheItem: removeCacheItem }); _extend(exports, { themes: themes, themesMapping: themesMapping, themesSchemeMapping: themesSchemeMapping, widgetsCache: widgetsCache, resetCurrentTheme: function() { currentThemeName = null } }) }, /*!******************************!*\ !*** ./js/viz/core/utils.js ***! \******************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, _isDefined = commonUtils.isDefined, _inArray = inArray, _each = $.each, _math = Math, _round = _math.round, _sqrt = Math.sqrt, _extend = extend; var PI = Math.PI, MAX_PIXEL_COUNT = 1e10, PI_DIV_180 = PI / 180, LN10 = Math.LN10; var cosFunc = Math.cos, sinFunc = Math.sin, abs = Math.abs, log = Math.log, floor = Math.floor, ceil = Math.ceil, max = Math.max, isNaN = window.isNaN, Number = window.Number, NaN = window.NaN; var isNumber = commonUtils.isNumeric, isExponential = commonUtils.isExponential; var getPrecision = function(value) { var stringFraction, startIndex, precision, stringValue = value.toString(), pointIndex = stringValue.indexOf("."); if (isExponential(value)) { precision = getDecimalOrder(value); if (precision < 0) { return Math.abs(precision) } else { return 0 } } if (pointIndex !== -1) { startIndex = pointIndex + 1; stringFraction = stringValue.substring(startIndex, startIndex + 20); return stringFraction.length } return 0 }; var getLog = function(value, base) { if (!value) { return NaN } return Math.log(value) / Math.log(base) }; var raiseTo = function(power, base) { return Math.pow(base, power) }; var normalizeAngle = function(angle) { return (angle % 360 + 360) % 360 }; var convertAngleToRendererSpace = function(angle) { return 90 - angle }; var degreesToRadians = function(value) { return PI * value / 180 }; var getCosAndSin = function(angle) { var angleInRadians = degreesToRadians(angle); return { cos: cosFunc(angleInRadians), sin: sinFunc(angleInRadians) } }; var DECIMAL_ORDER_THRESHOLD = 1e-14; var getDistance = function(x1, y1, x2, y2) { var diffX = x2 - x1, diffY = y2 - y1; return Math.sqrt(diffY * diffY + diffX * diffX) }; var getDecimalOrder = function(number) { var cn, n = abs(number); if (!isNaN(n)) { if (n > 0) { n = log(n) / LN10; cn = ceil(n); return cn - n < DECIMAL_ORDER_THRESHOLD ? cn : floor(n) } return 0 } return NaN }; var getAppropriateFormat = function(start, end, count) { var format, order = max(getDecimalOrder(start), getDecimalOrder(end)), precision = -getDecimalOrder(abs(end - start) / count); if (!isNaN(order) && !isNaN(precision)) { if (abs(order) <= 4) { format = "fixedPoint"; precision < 0 && (precision = 0); precision > 4 && (precision = 4) } else { format = "exponential"; precision += order - 1; precision > 3 && (precision = 3) } return { type: format, precision: precision } } return null }; var getFraction = function(value) { var valueString, dotIndex; if (isNumber(value)) { valueString = value.toString(); dotIndex = valueString.indexOf("."); if (dotIndex >= 0) { if (isExponential(value)) { return valueString.substr(dotIndex + 1, valueString.indexOf("e") - dotIndex - 1) } else { valueString = value.toFixed(20); return valueString.substr(dotIndex + 1, valueString.length - dotIndex + 1) } } } return "" }; var getSignificantDigitPosition = function(value) { var i, fraction = getFraction(value); if (fraction) { for (i = 0; i < fraction.length; i++) { if ("0" !== fraction.charAt(i)) { return i + 1 } } } return 0 }; var adjustValue = function(value) { var nextValue, i, fraction = getFraction(value); if (fraction) { for (i = 1; i <= fraction.length; i++) { nextValue = roundValue(value, i); if (0 !== nextValue && fraction[i - 2] && fraction[i - 1] && fraction[i - 2] === fraction[i - 1]) { return nextValue } } } return value }; var roundValue = function(value, precision) { if (precision > 20) { precision = 20 } if (isNumber(value)) { if (isExponential(value)) { return Number(value.toExponential(precision)) } else { return Number(value.toFixed(precision)) } } }; var applyPrecisionByMinDelta = function(min, delta, value) { var minPrecision = getPrecision(min), deltaPrecision = getPrecision(delta); return roundValue(value, minPrecision < deltaPrecision ? deltaPrecision : minPrecision) }; var getPower = function(value) { return value.toExponential().split("e")[1] }; function map(array, callback) { var value, i = 0, len = array.length, result = []; while (i < len) { value = callback(array[i], i); if (null !== value) { result.push(value) } i++ } return result } function selectByKeys(object, keys) { return map(keys, function(key) { return object[key] ? object[key] : null }) } function decreaseFields(object, keys, eachDecrease, decrease) { var dec = decrease; _each(keys, function(_, key) { if (object[key]) { object[key] -= eachDecrease; dec -= eachDecrease } }); return dec } function normalizeEnum(value) { return String(value).toLowerCase() } function setCanvasValues(canvas) { if (canvas) { canvas.originalTop = canvas.top; canvas.originalBottom = canvas.bottom; canvas.originalLeft = canvas.left; canvas.originalRight = canvas.right } } function normalizeBBoxField(value) { return -MAX_PIXEL_COUNT < value && value < +MAX_PIXEL_COUNT ? value : 0 } function normalizeBBox(bBox) { var xl = normalizeBBoxField(floor(bBox.x)), yt = normalizeBBoxField(floor(bBox.y)), xr = normalizeBBoxField(ceil(bBox.width + bBox.x)), yb = normalizeBBoxField(ceil(bBox.height + bBox.y)), result = { x: xl, y: yt, width: xr - xl, height: yb - yt }; result.isEmpty = !result.x && !result.y && !result.width && !result.height; return result } function rotateBBox(bBox, center, angle) { var cos = Number(cosFunc(angle * PI_DIV_180).toFixed(3)), sin = Number(sinFunc(angle * PI_DIV_180).toFixed(3)), w2 = bBox.width / 2, h2 = bBox.height / 2, centerX = bBox.x + w2, centerY = bBox.y + h2, w2_ = abs(w2 * cos) + abs(h2 * sin), h2_ = abs(w2 * sin) + abs(h2 * cos), centerX_ = center[0] + (centerX - center[0]) * cos + (centerY - center[1]) * sin, centerY_ = center[1] - (centerX - center[0]) * sin + (centerY - center[1]) * cos; return normalizeBBox({ x: centerX_ - w2_, y: centerY_ - h2_, width: 2 * w2_, height: 2 * h2_ }) } extend(exports, { decreaseGaps: function(object, keys, decrease) { var arrayGaps; do { arrayGaps = selectByKeys(object, keys); arrayGaps.push(_math.ceil(decrease / arrayGaps.length)); decrease = decreaseFields(object, keys, _math.min.apply(null, arrayGaps), decrease) } while (decrease > 0 && arrayGaps.length > 1); return decrease }, normalizeEnum: normalizeEnum, parseScalar: function(value, defaultValue) { return void 0 !== value ? value : defaultValue }, enumParser: function(values) { var i, ii, stored = {}; for (i = 0, ii = values.length; i < ii; ++i) { stored[normalizeEnum(values[i])] = 1 } return function(value, defaultValue) { var _value = normalizeEnum(value); return stored[_value] ? _value : defaultValue } }, patchFontOptions: function(options) { var fontOptions = {}; _each(options || {}, function(key, value) { if (/^(cursor|opacity)$/i.test(key)) {} else { if ("color" === key) { key = "fill" } else { key = "font-" + key } } fontOptions[key] = value }); return fontOptions }, convertPolarToXY: function(centerCoords, startAngle, angle, radius) { var cosSin, shiftAngle = 90; angle = _isDefined(angle) ? angle + startAngle - shiftAngle : 0; cosSin = getCosAndSin(angle); return { x: _round(centerCoords.x + radius * cosSin.cos), y: _round(centerCoords.y + radius * cosSin.sin) } }, convertXYToPolar: function(centerCoords, x, y) { var radius = getDistance(centerCoords.x, centerCoords.y, x, y), angle = _math.atan2(y - centerCoords.y, x - centerCoords.x); return { phi: _round(normalizeAngle(180 * angle / _math.PI)), r: _round(radius) } }, processSeriesTemplate: function(seriesTemplate, items) { var series, length, data, customizeSeries = commonUtils.isFunction(seriesTemplate.customizeSeries) ? seriesTemplate.customizeSeries : commonUtils.noop, nameField = seriesTemplate.nameField || "series", generatedSeries = {}, seriesOrder = [], i = 0; items = items || []; for (length = items.length; i < length; i++) { data = items[i]; if (nameField in data) { series = generatedSeries[data[nameField]]; if (!series) { series = generatedSeries[data[nameField]] = { name: data[nameField], data: [] }; seriesOrder.push(series.name) } series.data.push(data) } } return map(seriesOrder, function(orderedName) { var group = generatedSeries[orderedName]; return extend(group, customizeSeries.call(null, group.name)) }) }, getCategoriesInfo: function(categories, startValue, endValue) { if (!(categories && categories.length > 0)) { return {} } startValue = _isDefined(startValue) ? startValue : categories[0]; endValue = _isDefined(endValue) ? endValue : categories[categories.length - 1]; var visibleCategories, swapBuf, hasVisibleCategories, visibleCategoriesLen, categoriesValue = map(categories, function(category) { return _isDefined(category) ? category.valueOf() : null }), indexStartValue = _isDefined(startValue) ? _inArray(startValue.valueOf(), categoriesValue) : 0, indexEndValue = _isDefined(endValue) ? _inArray(endValue.valueOf(), categoriesValue) : categories.length - 1, inverted = false; indexStartValue < 0 && (indexStartValue = 0); indexEndValue < 0 && (indexEndValue = categories.length - 1); if (indexEndValue < indexStartValue) { swapBuf = indexEndValue; indexEndValue = indexStartValue; indexStartValue = swapBuf; inverted = true } visibleCategories = categories.slice(indexStartValue, indexEndValue + 1); visibleCategoriesLen = visibleCategories.length; hasVisibleCategories = visibleCategoriesLen > 0; return { categories: hasVisibleCategories ? visibleCategories : null, start: hasVisibleCategories ? visibleCategories[inverted ? visibleCategoriesLen - 1 : 0] : null, end: hasVisibleCategories ? visibleCategories[inverted ? 0 : visibleCategoriesLen - 1] : null, inverted: inverted } }, setCanvasValues: setCanvasValues, updatePanesCanvases: function(panes, canvas, rotated) { var weightSum = 0; _each(panes, function(_, pane) { pane.weight = pane.weight || 1; weightSum += pane.weight }); var distributedSpace = 0, padding = panes.padding || 10, paneSpace = rotated ? canvas.width - canvas.left - canvas.right : canvas.height - canvas.top - canvas.bottom, oneWeight = (paneSpace - padding * (panes.length - 1)) / weightSum, startName = rotated ? "left" : "top", endName = rotated ? "right" : "bottom"; _each(panes, function(_, pane) { var calcLength = _round(pane.weight * oneWeight); pane.canvas = pane.canvas || {}; _extend(pane.canvas, canvas); pane.canvas[startName] = canvas[startName] + distributedSpace; pane.canvas[endName] = canvas[endName] + (paneSpace - calcLength - distributedSpace); distributedSpace = distributedSpace + calcLength + padding; setCanvasValues(pane.canvas) }) }, unique: function(array) { var values = {}; return map(array, function(item) { var result = !values[item] ? item : null; values[item] = true; return result }) }, map: map, getVerticallyShiftedAngularCoords: function(bBox, dy, center) { var isPositive = bBox.x + bBox.width / 2 >= center.x, horizontalOffset1 = (isPositive ? bBox.x : bBox.x + bBox.width) - center.x, verticalOffset1 = bBox.y - center.y, verticalOffset2 = verticalOffset1 + dy, horizontalOffset2 = _round(_sqrt(horizontalOffset1 * horizontalOffset1 + verticalOffset1 * verticalOffset1 - verticalOffset2 * verticalOffset2)), dx = (isPositive ? +horizontalOffset2 : -horizontalOffset2) || horizontalOffset1; return { x: center.x + (isPositive ? dx : dx - bBox.width), y: bBox.y + dy } } }); exports.getPrecision = getPrecision; exports.getLog = getLog; exports.raiseTo = raiseTo; exports.normalizeAngle = normalizeAngle; exports.convertAngleToRendererSpace = convertAngleToRendererSpace; exports.degreesToRadians = degreesToRadians; exports.getCosAndSin = getCosAndSin; exports.getDecimalOrder = getDecimalOrder; exports.getAppropriateFormat = getAppropriateFormat; exports.getDistance = getDistance; exports.getFraction = getFraction; exports.adjustValue = adjustValue; exports.roundValue = roundValue; exports.applyPrecisionByMinDelta = applyPrecisionByMinDelta; exports.getSignificantDigitPosition = getSignificantDigitPosition; exports.getPower = getPower; exports.rotateBBox = rotateBBox; exports.normalizeBBox = normalizeBBox }, /*!**************************!*\ !*** ./js/viz/export.js ***! \**************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./core/export */ 511) }, /*!*******************************!*\ !*** ./js/viz/core/export.js ***! \*******************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, patchFontOptions = __webpack_require__( /*! ./utils */ 509).patchFontOptions, _extend = extend, clientExporter = __webpack_require__( /*! ../../client_exporter */ 20), messageLocalization = __webpack_require__( /*! ../../localization/message */ 89), imageExporter = clientExporter.image, svgExporter = clientExporter.svg, pdfExporter = clientExporter.pdf, hoverEvent = __webpack_require__( /*! ../../events/hover */ 103), pointerEvents = __webpack_require__( /*! ../../events/pointer */ 76), pointerActions = [pointerEvents.down, pointerEvents.move].join(" "), BUTTON_SIZE = 35, ICON_COORDS = [ [9, 12, 26, 12, 26, 14, 9, 14], [9, 17, 26, 17, 26, 19, 9, 19], [9, 22, 26, 22, 26, 24, 9, 24] ], LIST_PADDING_TOP = 4, LIST_WIDTH = 120, VERTICAL_TEXT_MARGIN = 8, HORIZONTAL_TEXT_MARGIN = 15, MENU_ITEM_HEIGHT = 30, LIST_STROKE_WIDTH = 1, MARGIN = 10, SHADOW_OFFSET = 2, SHADOW_BLUR = 3, ALLOWED_EXPORT_FORMATS = ["PNG", "PDF", "JPEG", "SVG", "GIF"], EXPORT_CSS_CLASS = "dx-export-menu", EXPORT_DATA_KEY = "export-element-type", FORMAT_DATA_KEY = "export-element-format"; function validateFormat(format) { var validatedFormat = String(format).toUpperCase(); if (inArray(validatedFormat, ALLOWED_EXPORT_FORMATS) !== -1) { return validatedFormat } } function getCreatorFunc(format) { if ("SVG" === format) { return svgExporter.getData } else { if ("PDF" === format) { return pdfExporter.getData } else { return imageExporter.getData } } } function doExport(menu, markup, options) { menu && menu.hide(); clientExporter.export(markup(), options, getCreatorFunc(options.format)); menu && menu.show() } function print(data, backgroundColor) { var svg, vizWindow = window.open(); if (!vizWindow) { return } vizWindow.document.open(); vizWindow.document.write(data); vizWindow.document.close(); svg = vizWindow.document.body.getElementsByTagName("svg")[0]; svg && (svg.style.backgroundColor = backgroundColor); vizWindow.print(); vizWindow.close() } function getItemAttributes(options, type, itemIndex) { var path, attr = {}, x = BUTTON_SIZE - LIST_WIDTH, y = BUTTON_SIZE + LIST_PADDING_TOP + itemIndex * MENU_ITEM_HEIGHT; attr.rect = { width: LIST_WIDTH - 2 * LIST_STROKE_WIDTH, height: MENU_ITEM_HEIGHT, x: x + LIST_STROKE_WIDTH, y: y }; attr.text = { x: x + HORIZONTAL_TEXT_MARGIN, y: y + MENU_ITEM_HEIGHT - VERTICAL_TEXT_MARGIN, align: "left" }; if ("printing" === type) { path = "M " + x + " " + (y + MENU_ITEM_HEIGHT - LIST_STROKE_WIDTH) + " L " + (x + LIST_WIDTH) + " " + (y + MENU_ITEM_HEIGHT - LIST_STROKE_WIDTH); attr.separator = { stroke: options.button.default.borderColor, "stroke-width": LIST_STROKE_WIDTH, cursor: "pointer", sharp: "v", d: path } } return attr } function createMenuItem(renderer, options, settings) { var menuItem, itemData = {}, type = settings.type, format = settings.format, attr = getItemAttributes(options, type, settings.itemIndex), fontStyle = patchFontOptions(options.font), rect = renderer.rect(), text = renderer.text(settings.text); fontStyle["pointer-events"] = "none"; menuItem = renderer.g().attr({ "class": EXPORT_CSS_CLASS + "-list-item" }); itemData[EXPORT_DATA_KEY] = type; if (format) { itemData[FORMAT_DATA_KEY] = format } rect.attr(attr.rect).css({ cursor: "pointer", "pointer-events": "all" }).data(itemData); rect.on(hoverEvent.start + ".export", function() { rect.attr({ fill: options.button.hover.backgroundColor }) }).on(hoverEvent.end + ".export", function() { rect.attr({ fill: null }) }); rect.append(menuItem); text.css(fontStyle).attr(attr.text).append(menuItem); if ("printing" === type) { renderer.path(null, "line").attr(attr.separator).append(menuItem) } return { g: menuItem, rect: rect, resetState: function() { rect.attr({ fill: null }) } } } function createMenuItems(renderer, options) { var formats = options.formats, items = []; if (options.printingEnabled) { items.push(createMenuItem(renderer, options, { type: "printing", text: messageLocalization.format("vizExport-printingButtonText"), itemIndex: items.length })) } items = formats.reduce(function(r, format) { format = validateFormat(format); if (format) { r.push(createMenuItem(renderer, options, { type: "exporting", text: messageLocalization.getFormatter("vizExport-exportButtonText")(format), format: format, itemIndex: r.length })) } return r }, items); return items } exports.exportFromMarkup = function(markup, options) { options.format = validateFormat(options.format) || "PNG"; options.fileName = options.fileName || "file"; options.exportingAction = options.onExporting; options.exportedAction = options.onExported; options.fileSavingAction = options.onFileSaving; clientExporter.export(markup, options, getCreatorFunc(options.format)) }; exports.getMarkup = function(widgets) { var svgArr = [], height = 0, width = 0; widgets.forEach(function(widget) { var size = widget.getSize(); svgArr.push(widget.svg().replace("<svg", '<g transform="translate(0,' + height + ')" ').replace("</svg>", "</g>")); height += size.height; width = Math.max(width, size.width) }); return '<svg height="' + height + '" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join("") + "</svg>" }; exports.ExportMenu = function(params) { var that = this, renderer = that._renderer = params.renderer; that._incidentOccurred = params.incidentOccurred; that._svgMethod = params.svgMethod; that._shadow = renderer.shadowFilter("-50%", "-50%", "200%", "200%", SHADOW_OFFSET, 6, SHADOW_BLUR); that._shadow.attr({ opacity: .8 }); that._group = renderer.g().attr({ "class": EXPORT_CSS_CLASS }).linkOn(renderer.root, { name: "export-menu", after: "peripheral" }); that._buttonGroup = renderer.g().attr({ "class": EXPORT_CSS_CLASS + "-button" }).append(that._group); that._listGroup = renderer.g().attr({ "class": EXPORT_CSS_CLASS + "-list" }).append(that._group); that._overlay = renderer.rect(-LIST_WIDTH + BUTTON_SIZE, BUTTON_SIZE + LIST_PADDING_TOP, LIST_WIDTH, 0); that._overlay.attr({ "stroke-width": LIST_STROKE_WIDTH, cursor: "pointer", rx: 4, ry: 4, filter: that._shadow.id }); that._overlay.data({ "export-element-type": "list" }); that._subscribeEvents() }; _extend(exports.ExportMenu.prototype, { getLayoutOptions: function() { if (this._hiddenDueToLayout) { return { width: 0, height: 0 } } var bBox = this._buttonGroup.getBBox(); bBox.cutSide = "vertical"; bBox.cutLayoutSide = "top"; bBox.height += MARGIN; bBox.position = { vertical: "top", horizontal: "right" }; bBox.verticalAlignment = "top"; bBox.horizontalAlignment = "right"; return bBox }, probeDraw: function() { this._hiddenDueToLayout = false; this.show() }, shift: function(_, y) { this._group.attr({ translateY: this._group.attr("translateY") + y }) }, draw: function(width, height, canvas) { var layoutOptions; this._options.exportOptions.width = canvas.width; this._options.exportOptions.height = canvas.height; this._group.move(width - BUTTON_SIZE - SHADOW_OFFSET - SHADOW_BLUR + canvas.left, Math.floor(height / 2 - BUTTON_SIZE / 2)); layoutOptions = this.getLayoutOptions(); if (layoutOptions.width > width || layoutOptions.height > height) { this._incidentOccurred("W2107"); this._hiddenDueToLayout = true; this.hide() } return this }, show: function() { !this._hiddenDueToLayout && this._group.linkAppend() }, hide: function() { this._group.linkRemove() }, setOptions: function(options) { this._options = options; options.formats = options.formats || ALLOWED_EXPORT_FORMATS; options.printingEnabled = void 0 === options.printingEnabled ? true : options.printingEnabled; if (options.enabled && (options.formats.length || options.printingEnabled)) { this.show(); this._updateButton(); this._updateList(); this._hideList() } else { this.hide() } }, dispose: function() { var that = this; that._unsubscribeEvents(); that._group.linkRemove().linkOff(); that._group.dispose(); that._shadow.dispose(); that._shadow = that._group = that._listGroup = that._buttonGroup = that._button = null; that._options = null }, layoutOptions: function() { var options = this._options; return options.enabled && { horizontalAlignment: "right", verticalAlignment: "top", weak: true } }, measure: function() { return [BUTTON_SIZE + SHADOW_OFFSET, BUTTON_SIZE] }, move: function(rect) { this._group.attr({ translateX: Math.round(rect[0]), translateY: Math.round(rect[1]) }) }, _hideList: function() { this._listGroup.remove(); this._listShown = false; this._setButtonState("default"); this._menuItems.forEach(function(item) { item.resetState() }) }, _showList: function() { this._listGroup.append(this._group); this._listShown = true }, _setButtonState: function(state) { var that = this, style = that._options.button[state]; this._button.attr({ stroke: style.borderColor, fill: style.backgroundColor }); this._icon.attr({ fill: style.color }) }, _subscribeEvents: function() { var that = this; that._renderer.root.on(pointerEvents.up + ".export", function(e) { var exportOptions, elementType = e.target[EXPORT_DATA_KEY], options = that._options; if (!elementType) { if (that._button) { that._hideList() } return } if ("button" === elementType) { if (that._listShown) { that._setButtonState("default"); that._hideList() } else { that._setButtonState("focus"); that._showList() } } else { if ("printing" === elementType) { that.hide(); print(that._svgMethod(), options.backgroundColor); that.show(); that._hideList() } else { if ("exporting" === elementType) { exportOptions = _extend({}, options.exportOptions, { format: e.target[FORMAT_DATA_KEY] }); doExport(that, function() { return that._svgMethod() }, exportOptions); that._hideList() } } } }); that._listGroup.on(pointerActions, function(e) { e.stopPropagation() }); that._buttonGroup.on(pointerEvents.enter, function() { that._setButtonState("hover") }); that._buttonGroup.on(pointerEvents.leave, function() { that._setButtonState(that._listShown ? "focus" : "default") }); that._buttonGroup.on(pointerEvents.down + ".export", function() { that._setButtonState("active") }) }, _unsubscribeEvents: function() { this._renderer.root.off(".export"); this._listGroup.off(); this._buttonGroup.off() }, _updateButton: function() { var that = this, renderer = that._renderer, options = that._options, iconAttr = { fill: options.button.default.color, cursor: "pointer" }, exportData = { "export-element-type": "button" }; if (!that._button) { that._button = renderer.rect(0, 0, BUTTON_SIZE, BUTTON_SIZE).append(that._buttonGroup); that._button.attr({ rx: 4, ry: 4, fill: options.button.default.backgroundColor, stroke: options.button.default.borderColor, "stroke-width": 1, cursor: "pointer" }); that._button.data(exportData); that._icon = renderer.path(ICON_COORDS).append(that._buttonGroup); that._icon.attr(iconAttr); that._icon.data(exportData); that._buttonGroup.setTitle(messageLocalization.format("vizExport-titleMenuText")) } }, _updateList: function() { var that = this, options = that._options, buttonDefault = options.button.default, listGroup = that._listGroup, items = createMenuItems(that._renderer, options); that._shadow.attr({ color: options.shadowColor }); that._overlay.attr({ height: items.length * MENU_ITEM_HEIGHT, fill: buttonDefault.backgroundColor, stroke: buttonDefault.borderColor }); listGroup.clear(); that._overlay.append(listGroup); items.forEach(function(item) { item.g.append(listGroup) }); that._menuItems = items } }); function getExportOptions(widget, exportOptions, fileName, format) { return { format: validateFormat(format || exportOptions.format) || "PNG", fileName: fileName || exportOptions.fileName || "file", proxyUrl: exportOptions.proxyUrl, backgroundColor: exportOptions.backgroundColor, width: widget._canvas.width, height: widget._canvas.height, exportingAction: widget._createActionByOption("onExporting"), exportedAction: widget._createActionByOption("onExported"), fileSavingAction: widget._createActionByOption("onFileSaving") } } exports.plugin = { name: "export", init: function() { var that = this; that._exportMenu = new exports.ExportMenu({ renderer: that._renderer, svgMethod: function() { return that.svg() }, incidentOccurred: that._incidentOccurred }); that._layout.add(that._exportMenu) }, dispose: function() { this._exportMenu.dispose(); this._exportMenu = null }, members: { _getExportMenuOptions: function() { var userOptions = this._getOption("export") || {}, options = getExportOptions(this, userOptions); return _extend({}, userOptions, { exportOptions: options }) }, exportTo: function(fileName, format) { var that = this, exportOptions = getExportOptions(that, that._getOption("export") || {}, fileName, format); doExport(that._exportMenu, function() { return that.svg() }, exportOptions) }, print: function() { print(this.svg(), this._getOption("export").backgroundColor) } }, customize: function(constructor) { var proto = constructor.prototype; constructor.addChange({ code: "EXPORT", handler: function() { this._exportMenu.setOptions(this._getExportMenuOptions()); this._change(["LAYOUT"]) }, isThemeDependent: true, isOptionChange: true, option: "export" }); proto._optionChangesMap.onExporting = "EXPORT"; proto._optionChangesMap.onExported = "EXPORT"; proto._optionChangesMap.onFileSaving = "EXPORT" } } }, /*!***************************!*\ !*** ./js/viz/palette.js ***! \***************************/ function(module, exports, __webpack_require__) { var vizUtils = __webpack_require__( /*! ./core/utils */ 509), _floor = Math.floor, _ceil = Math.ceil, _Color = __webpack_require__( /*! ../color */ 38), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, _isArray = Array.isArray, _isString = commonUtils.isString, _extend = extend, _normalizeEnum = vizUtils.normalizeEnum, HIGHLIGHTING_STEP = 50, DEFAULT = "default", currentPaletteName = DEFAULT; var palettes = { "default": { simpleSet: ["#5f8b95", "#ba4d51", "#af8a53", "#955f71", "#859666", "#7e688c"], indicatingSet: ["#a3b97c", "#e1b676", "#ec7f83"], gradientSet: ["#5f8b95", "#ba4d51"] }, "harmony light": { simpleSet: ["#fcb65e", "#679ec5", "#ad79ce", "#7abd5c", "#e18e92", "#b6d623", "#b7abea", "#85dbd5"], indicatingSet: ["#b6d623", "#fcb65e", "#e18e92"], gradientSet: ["#7abd5c", "#fcb65e"] }, "soft pastel": { simpleSet: ["#60a69f", "#78b6d9", "#6682bb", "#a37182", "#eeba69", "#90ba58", "#456c68", "#7565a4"], indicatingSet: ["#90ba58", "#eeba69", "#a37182"], gradientSet: ["#78b6d9", "#eeba69"] }, pastel: { simpleSet: ["#bb7862", "#70b3a1", "#bb626a", "#057d85", "#ab394b", "#dac599", "#153459", "#b1d2c6"], indicatingSet: ["#70b3a1", "#dac599", "#bb626a"], gradientSet: ["#bb7862", "#70b3a1"] }, bright: { simpleSet: ["#70c92f", "#f8ca00", "#bd1550", "#e97f02", "#9d419c", "#7e4452", "#9ab57e", "#36a3a6"], indicatingSet: ["#70c92f", "#f8ca00", "#bd1550"], gradientSet: ["#e97f02", "#f8ca00"] }, soft: { simpleSet: ["#cbc87b", "#9ab57e", "#e55253", "#7e4452", "#e8c267", "#565077", "#6babac", "#ad6082"], indicatingSet: ["#9ab57e", "#e8c267", "#e55253"], gradientSet: ["#9ab57e", "#e8c267"] }, ocean: { simpleSet: ["#75c099", "#acc371", "#378a8a", "#5fa26a", "#064970", "#38c5d2", "#00a7c6", "#6f84bb"], indicatingSet: ["#c8e394", "#7bc59d", "#397c8b"], gradientSet: ["#acc371", "#38c5d2"] }, vintage: { simpleSet: ["#dea484", "#efc59c", "#cb715e", "#eb9692", "#a85c4c", "#f2c0b5", "#c96374", "#dd956c"], indicatingSet: ["#ffe5c6", "#f4bb9d", "#e57660"], gradientSet: ["#efc59c", "#cb715e"] }, violet: { simpleSet: ["#d1a1d1", "#eeacc5", "#7b5685", "#7e7cad", "#a13d73", "#5b41ab", "#e287e2", "#689cc1"], indicatingSet: ["#d8e2f6", "#d0b2da", "#d56a8a"], gradientSet: ["#eeacc5", "#7b5685"] } }; function currentPalette(name) { if (void 0 === name) { return currentPaletteName } else { name = _normalizeEnum(name); currentPaletteName = name in palettes ? name : DEFAULT } } function getPalette(palette, parameters) { var result, type = parameters && parameters.type; if (_isArray(palette)) { return palette.slice(0) } else { if (_isString(palette)) { result = palettes[_normalizeEnum(palette)] } if (!result) { result = palettes[currentPaletteName] } } result = result || null; return type ? result ? result[type].slice(0) : result : result } function registerPalette(name, palette) { var paletteName, item = {}; if (_isArray(palette)) { item.simpleSet = palette.slice(0) } else { if (palette) { item.simpleSet = _isArray(palette.simpleSet) ? palette.simpleSet.slice(0) : void 0; item.indicatingSet = _isArray(palette.indicatingSet) ? palette.indicatingSet.slice(0) : void 0; item.gradientSet = _isArray(palette.gradientSet) ? palette.gradientSet.slice(0) : void 0 } } if (item.simpleSet || item.indicatingSet || item.gradientSet) { paletteName = _normalizeEnum(name); _extend(palettes[paletteName] = palettes[paletteName] || {}, item) } } function RingBuf(buf) { var ind = 0; this.next = function() { var res = buf[ind++]; if (ind === buf.length) { this.reset() } return res }; this.reset = function() { ind = 0 } } function Palette(palette, parameters) { parameters = parameters || {}; var stepHighlight = parameters.useHighlight ? HIGHLIGHTING_STEP : 0; this._originalPalette = getPalette(palette, { type: parameters.type || "simpleSet" }); this._paletteSteps = new RingBuf([0, stepHighlight, -stepHighlight]); this._resetPalette() } Palette.prototype = { constructor: Palette, dispose: function() { this._originalPalette = this._palette = this._paletteSteps = null }, getNextColor: function() { var that = this; if (that._currentColor >= that._palette.length) { that._resetPalette() } return that._palette[that._currentColor++] }, _resetPalette: function() { var that = this, step = that._paletteSteps.next(); that._palette = step ? getAlteredPalette(that._originalPalette, step) : that._originalPalette.slice(0); that._currentColor = 0 }, reset: function() { this._paletteSteps.reset(); this._resetPalette(); return this } }; function getAlteredPalette(originalPalette, step) { var i, palette = [], ii = originalPalette.length; for (i = 0; i < ii; ++i) { palette.push(getNewColor(originalPalette[i], step)) } return palette } function getNewColor(currentColor, step) { var newColor = new _Color(currentColor).alter(step), lightness = getLightness(newColor); if (lightness > 200 || lightness < 55) { newColor = new _Color(currentColor).alter(-step / 2) } return newColor.toHex() } function getLightness(color) { return .3 * color.r + .59 * color.g + .11 * color.b } function DiscretePalette(source, size) { var palette = size > 0 ? createDiscreteColors(getPalette(source, { type: "gradientSet" }), size) : []; this.getColor = function(index) { return palette[index] || null } } function createDiscreteColors(source, count) { var i, colorCount = count - 1, sourceCount = source.length - 1, colors = [], gradient = []; function addColor(pos) { var k = sourceCount * pos, kl = _floor(k), kr = _ceil(k); gradient.push(colors[kl].blend(colors[kr], k - kl).toHex()) } for (i = 0; i <= sourceCount; ++i) { colors.push(new _Color(source[i])) } if (colorCount > 0) { for (i = 0; i <= colorCount; ++i) { addColor(i / colorCount) } } else { addColor(.5) } return gradient } function GradientPalette(source) { var palette = getPalette(source, { type: "gradientSet" }), color1 = new _Color(palette[0]), color2 = new _Color(palette[1]); this.getColor = function(ratio) { return 0 <= ratio && ratio <= 1 ? color1.blend(color2, ratio).toHex() : null } } _extend(exports, { Palette: Palette, DiscretePalette: DiscretePalette, GradientPalette: GradientPalette, registerPalette: registerPalette, getPalette: getPalette, currentPalette: currentPalette }); exports._DEBUG_palettes = palettes }, /*!*************************!*\ !*** ./js/viz/chart.js ***! \*************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), _extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../core/utils/array */ 26).inArray, registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), vizUtils = __webpack_require__( /*! ./core/utils */ 509), overlapping = __webpack_require__( /*! ./chart_components/base_chart */ 514).overlapping, LayoutManagerModule = __webpack_require__( /*! ./chart_components/layout_manager */ 555), multiAxesSynchronizer = __webpack_require__( /*! ./chart_components/multi_axes_synchronizer */ 562), AdvancedChart = __webpack_require__( /*! ./chart_components/advanced_chart */ 563).AdvancedChart, scrollBarModule = __webpack_require__( /*! ./chart_components/scroll_bar */ 582), crosshairModule = __webpack_require__( /*! ./chart_components/crosshair */ 581), DEFAULT_PANE_NAME = "default", DEFAULT_PANES = [{ name: DEFAULT_PANE_NAME, border: {} }], _map = vizUtils.map, _each = $.each, _isArray = Array.isArray, _isDefined = commonUtils.isDefined; function getFirstAxisNameForPane(axes, paneName, defaultPane) { var result; for (var i = 0; i < axes.length; i++) { if (axes[i].pane === paneName || void 0 === axes[i].pane && paneName === defaultPane) { result = axes[i].name; break } } if (!result) { result = axes[0].name } return result } function hideGridsOnNonFirstValueAxisForPane(valAxes, paneName, synchronizeMultiAxes) { var firstShownAxis, axesForPane = []; _each(valAxes, function(_, axis) { if (axis.pane === paneName) { axesForPane.push(axis) } }); if (axesForPane.length > 1 && synchronizeMultiAxes) { _each(axesForPane, function(_, axis) { var gridOpt = axis.getOptions().grid, minorGridOpt = axis.getOptions().minorGrid; if (firstShownAxis && gridOpt && gridOpt.visible) { gridOpt.visible = false; minorGridOpt && (minorGridOpt.visible = false) } else { firstShownAxis = firstShownAxis ? firstShownAxis : gridOpt && gridOpt.visible } }) } } function findAxisOptions(valueAxes, valueAxesOptions, axisName) { var result, axInd; for (axInd = 0; axInd < valueAxesOptions.length; axInd++) { if (valueAxesOptions[axInd].name === axisName) { result = valueAxesOptions[axInd]; result.priority = axInd; break } } if (!result) { for (axInd = 0; axInd < valueAxes.length; axInd++) { if (valueAxes[axInd].name === axisName) { result = valueAxes[axInd].getOptions(); result.priority = valueAxes[axInd].priority; break } } } return result } function findAxis(paneName, axisName, axes) { var axis, i; for (i = 0; i < axes.length; i++) { axis = axes[i]; if (axis.name === axisName && axis.pane === paneName) { return axis } } if (paneName) { return findAxis(void 0, axisName, axes) } } function applyClipSettings(clipRects, settings) { _each(clipRects || [], function(_, c) { c && c.attr(settings) }) } function compareAxes(a, b) { return a.priority - b.priority } function doesPaneExist(panes, paneName) { var found = false; _each(panes, function(_, pane) { if (pane.name === paneName) { found = true; return false } }); return found } var prepareSegmentRectPoints = function(left, top, width, height, borderOptions) { var maxSW = ~~((width < height ? width : height) / 2), sw = borderOptions.width || 0, newSW = sw < maxSW ? sw : maxSW; left += newSW / 2; top += newSW / 2; width -= newSW; height -= newSW; var segmentSequence, right = left + width, bottom = top + height, points = [], segments = [], visiblyOpt = 0, prevSegmentVisibility = 0; var allSegment = { top: [ [left, top], [right, top] ], right: [ [right, top], [right, bottom] ], bottom: [ [right, bottom], [left, bottom] ], left: [ [left, bottom], [left, top] ] }; _each(allSegment, function(seg) { var visibility = !!borderOptions[seg]; visiblyOpt = 2 * visiblyOpt + ~~visibility }); switch (visiblyOpt) { case 13: case 9: segmentSequence = ["left", "top", "right", "bottom"]; break; case 11: segmentSequence = ["bottom", "left", "top", "right"]; break; default: segmentSequence = ["top", "right", "bottom", "left"] } _each(segmentSequence, function(_, seg) { var segmentVisibility = !!borderOptions[seg]; if (!prevSegmentVisibility && segments.length) { points.push(segments); segments = [] } if (segmentVisibility) { _each(allSegment[seg].slice(prevSegmentVisibility), function(_, segment) { segments = segments.concat(segment) }) } prevSegmentVisibility = ~~segmentVisibility }); segments.length && points.push(segments); 1 === points.length && (points = points[0]); return { points: points, pathType: 15 === visiblyOpt ? "area" : "line" } }; function accumulate(field, src1, src2, auxSpacing) { var val1 = src1[field] || 0, val2 = src2[field] || 0; return val1 + val2 + (val1 && val2 ? auxSpacing : 0) } function pickMax(field, src1, src2) { return pickMaxValue(src1[field], src2[field]) } function pickMaxValue(val1, val2) { return Math.max(val1 || 0, val2 || 0) } function getAxisMargins(axis) { return axis.getMargins() } function getHorizontalAxesMargins(axes, getMarginsFunc) { return axes.reduce(function(margins, axis) { var axisMargins = getMarginsFunc(axis), paneMargins = margins.panes[axis.pane] = margins.panes[axis.pane] || {}, spacing = axis.getMultipleAxesSpacing(); paneMargins.top = accumulate("top", paneMargins, axisMargins, spacing); paneMargins.bottom = accumulate("bottom", paneMargins, axisMargins, spacing); paneMargins.left = pickMax("left", paneMargins, axisMargins); paneMargins.right = pickMax("right", paneMargins, axisMargins); margins.top = pickMax("top", paneMargins, margins); margins.bottom = pickMax("bottom", paneMargins, margins); margins.left = pickMax("left", paneMargins, margins); margins.right = pickMax("right", paneMargins, margins); return margins }, { panes: {} }) } function getVerticalAxesMargins(axes) { return axes.reduce(function(margins, axis) { var axisMargins = axis.getMargins(), paneMargins = margins.panes[axis.pane] = margins.panes[axis.pane] || {}, spacing = axis.getMultipleAxesSpacing(); paneMargins.top = pickMax("top", paneMargins, axisMargins); paneMargins.bottom = pickMax("bottom", paneMargins, axisMargins); paneMargins.left = accumulate("left", paneMargins, axisMargins, spacing); paneMargins.right = accumulate("right", paneMargins, axisMargins, spacing); margins.top = pickMax("top", paneMargins, margins); margins.bottom = pickMax("bottom", paneMargins, margins); margins.left = pickMax("left", paneMargins, margins); margins.right = pickMax("right", paneMargins, margins); return margins }, { panes: {} }) } function performActionOnAxes(axes, action, actionArgument1, actionArgument2) { axes.forEach(function(axis) { axis[action](actionArgument1 && actionArgument1[axis.pane], actionArgument2 && actionArgument2[axis.pane]) }) } function shrinkCanvases(isRotated, canvases, verticalMargins, horizontalMargins) { function getMargin(side, margins, pane) { var m = (isRotated ? ["left", "right"] : ["top", "bottom"]).indexOf(side) === -1 ? margins : margins.panes[pane] || {}; return m[side] } function getMaxMargin(side, margins1, margins2, pane) { return pickMaxValue(getMargin(side, margins1, pane), getMargin(side, margins2, pane)) } for (var pane in canvases) { canvases[pane].top = canvases[pane].originalTop + getMaxMargin("top", verticalMargins, horizontalMargins, pane); canvases[pane].bottom = canvases[pane].originalBottom + getMaxMargin("bottom", verticalMargins, horizontalMargins, pane); canvases[pane].left = canvases[pane].originalLeft + getMaxMargin("left", verticalMargins, horizontalMargins, pane); canvases[pane].right = canvases[pane].originalRight + getMaxMargin("right", verticalMargins, horizontalMargins, pane) } return canvases } function drawAxesWithTicks(axes, condition, canvases, panesBorderOptions) { if (condition) { performActionOnAxes(axes, "createTicks", canvases); multiAxesSynchronizer.synchronize(axes) } performActionOnAxes(axes, "draw", !condition && canvases, panesBorderOptions) } function shiftAxis(side1, side2) { var shifts = {}; return function(axis) { var shift = shifts[axis.pane] = shifts[axis.pane] || { top: 0, left: 0, bottom: 0, right: 0 }, spacing = axis.getMultipleAxesSpacing(), margins = axis.getMargins(); axis.shift(shift); shift[side1] = accumulate(side1, shift, margins, spacing); shift[side2] = accumulate(side2, shift, margins, spacing) } } function getCommonSize(side, margins) { var pane, paneMargins, size = 0; for (pane in margins.panes) { paneMargins = margins.panes[pane]; size += "height" === side ? paneMargins.top + paneMargins.bottom : paneMargins.left + paneMargins.right } return size } function checkUsedSpace(sizeShortage, side, axes, getMarginFunc) { var size = 0; if (sizeShortage[side] > 0) { size = getCommonSize(side, getMarginFunc(axes, getAxisMargins)); performActionOnAxes(axes, "hideTitle"); sizeShortage[side] -= size - getCommonSize(side, getMarginFunc(axes, getAxisMargins)) } if (sizeShortage[side] > 0) { performActionOnAxes(axes, "hideOuterElements") } } var dxChart = AdvancedChart.inherit({ _chartType: "chart", _setDeprecatedOptions: function() { this.callBase.apply(this, arguments); _extend(this._deprecatedOptions, { "argumentAxis.label.overlappingBehavior.rotationAngle": { since: "17.1", message: "Use the 'argumentAxis.label.rotationAngle' option instead" }, "argumentAxis.label.overlappingBehavior.staggeringSpacing": { since: "17.1", message: "Use the 'argumentAxis.label.staggeringSpacing' option instead" }, "argumentAxis.label.overlappingBehavior.mode": { since: "17.1", message: "Use the 'overlappingBehavior' option directly" }, "valueAxis.label.overlappingBehavior.rotationAngle": { since: "17.1", message: "Use the 'valueAxis.label.rotationAngle' option instead" }, "valueAxis.label.overlappingBehavior.staggeringSpacing": { since: "17.1", message: "Use the 'valueAxis.label.staggeringSpacing' option instead" }, "valueAxis.label.overlappingBehavior.mode": { since: "17.1", message: "Use the 'overlappingBehavior' option directly" }, "commonAxisSettings.label.overlappingBehavior.rotationAngle": { since: "17.1", message: "Use the 'commonAxisSettings.label.rotationAngle' option instead" }, "commonAxisSettings.label.overlappingBehavior.staggeringSpacing": { since: "17.1", message: "Use the 'commonAxisSettings.label.staggeringSpacing' option instead" }, "commonAxisSettings.label.overlappingBehavior.mode": { since: "17.1", message: "Use the 'overlappingBehavior' option directly" } }) }, _initCore: function() { this.paneAxis = {}; this._panesClipRects = {}; this.callBase() }, _disposeCore: function() { var that = this, disposeObjectsInArray = this._disposeObjectsInArray, panesClipRects = that._panesClipRects; that.callBase(); disposeObjectsInArray.call(panesClipRects, "fixed"); disposeObjectsInArray.call(panesClipRects, "base"); disposeObjectsInArray.call(panesClipRects, "wide"); that._panesClipRects = null }, _correctAxes: function() { this._correctValueAxes() }, _getExtraOptions: commonUtils.noop, _processSingleSeries: commonUtils.noop, _cleanPanesClipRects: function(clipArrayName) { var that = this, clipArray = that._panesClipRects[clipArrayName]; _each(clipArray || [], function(_, clipRect) { clipRect && clipRect.dispose() }); that._panesClipRects[clipArrayName] = [] }, _createPanes: function() { var defaultPane, that = this, panes = that.option("panes"), panesNameCounter = 0; if (!panes || _isArray(panes) && !panes.length) { panes = DEFAULT_PANES } that._cleanPanesClipRects("fixed"); that._cleanPanesClipRects("base"); that._cleanPanesClipRects("wide"); defaultPane = that.option("defaultPane"); panes = _extend(true, [], _isArray(panes) ? panes : [panes]); _each(panes, function(_, pane) { pane.name = !_isDefined(pane.name) ? DEFAULT_PANE_NAME + panesNameCounter++ : pane.name }); if (_isDefined(defaultPane)) { if (!doesPaneExist(panes, defaultPane)) { that._incidentOccurred("W2101", [defaultPane]); defaultPane = panes[panes.length - 1].name } } else { defaultPane = panes[panes.length - 1].name } that.defaultPane = defaultPane; panes = that._isRotated() ? panes.reverse() : panes; return panes }, _getAxisRenderingOptions: function() { return { axisType: "xyAxes", drawingType: "linear" } }, _prepareAxisOptions: function(typeSelector, userOptions, rotated) { return { isHorizontal: "argumentAxis" === typeSelector !== rotated } }, _checkPaneName: function(seriesTheme) { var paneList = _map(this.panes, function(pane) { return pane.name }); seriesTheme.pane = seriesTheme.pane || this.defaultPane; return inArray(seriesTheme.pane, paneList) !== -1 }, _getValueAxis: function(paneName, axisName) { var axisOptions, axis, that = this, valueAxes = that._valueAxes, valueAxisOptions = that.option("valueAxis") || {}, valueAxesOptions = _isArray(valueAxisOptions) ? valueAxisOptions : [valueAxisOptions]; axisName = axisName || getFirstAxisNameForPane(valueAxes, paneName, that.defaultPane); axis = findAxis(paneName, axisName, valueAxes); if (!axis) { axisOptions = findAxisOptions(valueAxes, valueAxesOptions, axisName); if (!axisOptions) { that._incidentOccurred("W2102", [axisName]); axisOptions = { name: axisName, priority: valueAxes.length } } axis = that._createAxis("valueAxis", axisOptions, { pane: paneName, name: axisName }, that._isRotated()); valueAxes.push(axis) } axis.setPane(paneName); return axis }, _correctValueAxes: function() { var that = this, synchronizeMultiAxes = that._themeManager.getOptions("synchronizeMultiAxes"), valueAxes = that._valueAxes, paneWithAxis = {}; that.series.forEach(function(series) { var axis = series.getValueAxis(); paneWithAxis[axis.pane] = true }); that.panes.forEach(function(pane) { var paneName = pane.name; if (!paneWithAxis[paneName]) { that._getValueAxis(paneName) } hideGridsOnNonFirstValueAxisForPane(valueAxes, pane.name, synchronizeMultiAxes) }); that._valueAxes = valueAxes.filter(function(axis) { if (!axis.pane) { axis.setPane(that.defaultPane) } return doesPaneExist(that.panes, axis.pane) }).sort(compareAxes) }, _getSeriesForPane: function(paneName) { var paneSeries = []; _each(this.series, function(_, oneSeries) { if (oneSeries.pane === paneName) { paneSeries.push(oneSeries) } }); return paneSeries }, _createPanesBorderOptions: function() { var commonBorderOptions = this._themeManager.getOptions("commonPaneSettings").border, panesBorderOptions = {}; _each(this.panes, function(_, pane) { panesBorderOptions[pane.name] = _extend(true, {}, commonBorderOptions, pane.border) }); return panesBorderOptions }, _createScrollBar: function() { var that = this, scrollBarOptions = that._themeManager.getOptions("scrollBar") || {}, scrollBarGroup = that._scrollBarGroup; if (scrollBarOptions.visible) { scrollBarOptions.rotated = that._isRotated(); that._scrollBar = (that._scrollBar || new scrollBarModule.ScrollBar(that._renderer, scrollBarGroup)).update(scrollBarOptions) } else { scrollBarGroup.linkRemove(); that._scrollBar && that._scrollBar.dispose(); that._scrollBar = null } }, _prepareToRender: function(drawOptions) { var that = this, panesBorderOptions = that._createPanesBorderOptions(), useAggregation = that._options.useAggregation, canvas = that._canvas, canvasLength = that._isRotated() ? canvas.height - canvas.top - canvas.bottom : canvas.width - canvas.left - canvas.right; that._createPanesBackground(); that._appendAxesGroups(); that._transformed && that._resetTransform(); that._updatePanesCanvases(drawOptions); if (useAggregation) { that.series.forEach(function(series) { series.resamplePoints(canvasLength) }) } if ((useAggregation || _isDefined(that._zoomMinArg) || _isDefined(that._zoomMaxArg)) && that._themeManager.getOptions("adjustOnZoom")) { that._valueAxes.forEach(function(axis) { var viewport = that.series.filter(function(s) { return s.getValueAxis() === axis }).reduce(function(range, s) { var seriesRange = s.getViewport(); range.min = range.min < seriesRange.min ? range.min : seriesRange.min; range.max = range.max > seriesRange.max ? range.max : seriesRange.max; return range }, {}); axis.zoom(viewport.min, viewport.max) }) } return panesBorderOptions }, _isLegendInside: function() { return this._legend && "inside" === this._legend.getPosition() }, _renderAxes: function(drawOptions, panesBorderOptions, rotated) { if (drawOptions && drawOptions.recreateCanvas) { vizUtils.updatePanesCanvases(this.panes, this._canvas, rotated) } this._drawAxes(drawOptions, panesBorderOptions) }, _isRotated: function() { return this._themeManager.getOptions("rotated") }, _getLayoutTargets: function() { return this.panes }, _applyClipRects: function(panesBorderOptions) { var i, that = this, canvasClipRectID = that._getCanvasClipRectID(); that._drawPanesBorders(panesBorderOptions); that._createClipRectsForPanes(); for (i = 0; i < that._argumentAxes.length; i++) { that._argumentAxes[i].applyClipRects(that._getElementsClipRectID(that._argumentAxes[i].pane), canvasClipRectID) } for (i = 0; i < that._valueAxes.length; i++) { that._valueAxes[i].applyClipRects(that._getElementsClipRectID(that._valueAxes[i].pane), canvasClipRectID) } that._fillPanesBackground() }, _updateLegendPosition: function(drawOptions, legendHasInsidePosition) { var that = this; if (drawOptions.drawLegend && that._legend && legendHasInsidePosition) { var panes = that.panes, newCanvas = _extend({}, panes[0].canvas), layoutManager = new LayoutManagerModule.LayoutManager; newCanvas.right = panes[panes.length - 1].canvas.right; newCanvas.bottom = panes[panes.length - 1].canvas.bottom; layoutManager.setOptions({ width: 0, height: 0 }); layoutManager.layoutElements([that._legend], newCanvas, commonUtils.noop, [{ canvas: newCanvas }], void 0) } }, _applyExtraSettings: function(series) { var that = this, paneIndex = that._getPaneIndex(series.pane), panesClipRects = that._panesClipRects, wideClipRect = panesClipRects.wide[paneIndex]; series.setClippingParams(panesClipRects.base[paneIndex].id, wideClipRect && wideClipRect.id, that._getPaneBorderVisibility(paneIndex)) }, _updatePanesCanvases: function(drawOptions) { if (!drawOptions.recreateCanvas) { return } vizUtils.updatePanesCanvases(this.panes, this._canvas, this._isRotated()) }, _restoreOriginalBusinessRange: function() { this._argumentAxes.concat(this._valueAxes).forEach(function(axis) { axis.restoreBusinessRange() }) }, _prepareAxesAndDraw: function(drawOptions, panesBorderOptions) { var that = this, rotated = that._isRotated(), synchronizeMultiAxes = that._themeManager.getOptions("synchronizeMultiAxes"), extendedArgAxes = (that._scrollBar ? [that._scrollBar] : []).concat(that._argumentAxes), verticalAxes = rotated ? extendedArgAxes : that._valueAxes, horizontalAxes = rotated ? that._valueAxes : extendedArgAxes, allAxes = verticalAxes.concat(horizontalAxes); var panesCanvases = that.panes.reduce(function(canvases, pane) { canvases[pane.name] = _extend({}, pane.canvas); return canvases }, {}); if (!drawOptions.adjustAxes) { drawAxesWithTicks(verticalAxes, !rotated && synchronizeMultiAxes, panesCanvases, panesBorderOptions); drawAxesWithTicks(horizontalAxes, rotated && synchronizeMultiAxes, panesCanvases, panesBorderOptions); return } if (that._scrollBar) { that._scrollBar.setPane(that.panes) } var vAxesMargins = { panes: {} }, hAxesMargins = getHorizontalAxesMargins(horizontalAxes, function(axis) { return axis.estimateMargins(panesCanvases[axis.pane]) }); panesCanvases = shrinkCanvases(rotated, panesCanvases, vAxesMargins, hAxesMargins); drawAxesWithTicks(verticalAxes, !rotated && synchronizeMultiAxes, panesCanvases, panesBorderOptions); vAxesMargins = getVerticalAxesMargins(verticalAxes); panesCanvases = shrinkCanvases(rotated, panesCanvases, vAxesMargins, hAxesMargins); drawAxesWithTicks(horizontalAxes, rotated && synchronizeMultiAxes, panesCanvases, panesBorderOptions); hAxesMargins = getHorizontalAxesMargins(horizontalAxes, getAxisMargins); panesCanvases = shrinkCanvases(rotated, panesCanvases, vAxesMargins, hAxesMargins); performActionOnAxes(allAxes, "updateSize", panesCanvases); horizontalAxes.forEach(shiftAxis("top", "bottom")); verticalAxes.forEach(shiftAxis("left", "right")); that.panes.forEach(function(pane) { _extend(pane.canvas, panesCanvases[pane.name]) }) }, _shrinkAxes: function(drawOptions, sizeShortage) { var panesCanvases, that = this, rotated = that._isRotated(), extendedArgAxes = (that._scrollBar ? [that._scrollBar] : []).concat(that._argumentAxes), verticalAxes = rotated ? extendedArgAxes : that._valueAxes, horizontalAxes = rotated ? that._valueAxes : extendedArgAxes, allAxes = verticalAxes.concat(horizontalAxes); if (sizeShortage.width || sizeShortage.height) { panesCanvases = that.panes.reduce(function(canvases, pane) { canvases[pane.name] = _extend({}, pane.canvas); return canvases }, {}); checkUsedSpace(sizeShortage, "height", horizontalAxes, getHorizontalAxesMargins); checkUsedSpace(sizeShortage, "width", verticalAxes, getVerticalAxesMargins); panesCanvases = shrinkCanvases(rotated, panesCanvases, getVerticalAxesMargins(verticalAxes), getHorizontalAxesMargins(horizontalAxes, getAxisMargins)); performActionOnAxes(allAxes, "updateSize", panesCanvases); horizontalAxes.forEach(shiftAxis("top", "bottom")); verticalAxes.forEach(shiftAxis("left", "right")); that.panes.forEach(function(pane) { $.extend(pane.canvas, panesCanvases[pane.name]) }) } }, _getPanesParameters: function() { var i, that = this, panes = that.panes, params = []; for (i = 0; i < panes.length; i++) { if (that._getPaneBorderVisibility(i)) { params.push({ coords: panes[i].borderCoords, clipRect: that._panesClipRects.fixed[i] }) } } return params }, _createCrosshairCursor: function() { var that = this, options = that._themeManager.getOptions("crosshair") || {}, index = that._displayedArgumentAxisIndex, axes = !that._isRotated() ? [ [that._argumentAxes[index]], that._valueAxes ] : [that._valueAxes, [that._argumentAxes[index]]], parameters = { canvas: that._getCommonCanvas(), panes: that._getPanesParameters(), axes: axes }; if (!options || !options.enabled) { return } if (!that._crosshair) { that._crosshair = new crosshairModule.Crosshair(that._renderer, options, parameters, that._crosshairCursorGroup) } else { that._crosshair.update(options, parameters) } that._crosshair.render() }, _getCommonCanvas: function() { var i, canvas, commonCanvas, panes = this.panes; for (i = 0; i < panes.length; i++) { canvas = panes[i].canvas; if (!commonCanvas) { commonCanvas = _extend({}, canvas) } else { commonCanvas.right = canvas.right; commonCanvas.bottom = canvas.bottom } } return commonCanvas }, _createPanesBackground: function() { var backgroundColor, rect, i, that = this, defaultBackgroundColor = that._themeManager.getOptions("commonPaneSettings").backgroundColor, renderer = that._renderer, rects = []; that._panesBackgroundGroup.clear(); for (i = 0; i < that.panes.length; i++) { backgroundColor = that.panes[i].backgroundColor || defaultBackgroundColor; if (!backgroundColor || "none" === backgroundColor) { rects.push(null); continue } rect = renderer.rect(0, 0, 0, 0).attr({ fill: backgroundColor, "stroke-width": 0 }).append(that._panesBackgroundGroup); rects.push(rect) } that.panesBackground = rects }, _fillPanesBackground: function() { var bc, that = this; _each(that.panes, function(i, pane) { bc = pane.borderCoords; if (null !== that.panesBackground[i]) { that.panesBackground[i].attr({ x: bc.left, y: bc.top, width: bc.width, height: bc.height }) } }) }, _calcPaneBorderCoords: function(pane) { var canvas = pane.canvas, bc = pane.borderCoords = pane.borderCoords || {}; bc.left = canvas.left; bc.top = canvas.top; bc.right = canvas.width - canvas.right; bc.bottom = canvas.height - canvas.bottom; bc.width = Math.max(bc.right - bc.left, 0); bc.height = Math.max(bc.bottom - bc.top, 0) }, _drawPanesBorders: function(panesBorderOptions) { var that = this, rotated = that._isRotated(); that._panesBorderGroup.linkRemove().clear(); _each(that.panes, function(i, pane) { var bc, segmentRectParams, borderOptions = panesBorderOptions[pane.name], attr = { fill: "none", stroke: borderOptions.color, "stroke-opacity": borderOptions.opacity, "stroke-width": borderOptions.width, dashStyle: borderOptions.dashStyle, "stroke-linecap": "square" }; that._calcPaneBorderCoords(pane, rotated); if (!borderOptions.visible) { return } bc = pane.borderCoords; segmentRectParams = prepareSegmentRectPoints(bc.left, bc.top, bc.width, bc.height, borderOptions); that._renderer.path(segmentRectParams.points, segmentRectParams.pathType).attr(attr).append(that._panesBorderGroup) }); that._panesBorderGroup.linkAppend() }, _createClipRect: function(clipArray, index, left, top, width, height) { var that = this, clipRect = clipArray[index]; if (!clipRect) { clipRect = that._renderer.clipRect(left, top, width, height); clipArray[index] = clipRect } else { clipRect.attr({ x: left, y: top, width: width, height: height }) } }, _createClipRectsForPanes: function() { var that = this, canvas = that._canvas; _each(that.panes, function(i, pane) { var needWideClipRect = false, bc = pane.borderCoords, left = bc.left, top = bc.top, width = bc.width, height = bc.height, panesClipRects = that._panesClipRects; that._createClipRect(panesClipRects.fixed, i, left, top, width, height); that._createClipRect(panesClipRects.base, i, left, top, width, height); _each(that.series, function(_, series) { if (series.pane === pane.name && (series.isFinancialSeries() || series.areErrorBarsVisible())) { needWideClipRect = true } }); if (needWideClipRect) { if (that._isRotated()) { top = 0; height = canvas.height } else { left = 0; width = canvas.width } that._createClipRect(panesClipRects.wide, i, left, top, width, height) } else { panesClipRects.wide[i] = null } }) }, _getPaneIndex: function(paneName) { var paneIndex; _each(this.panes, function(index, pane) { if (pane.name === paneName) { paneIndex = index; return false } }); return paneIndex }, _getPaneBorderVisibility: function(paneIndex) { var commonPaneBorderVisible = this._themeManager.getOptions("commonPaneSettings").border.visible, pane = this.panes[paneIndex] || {}, paneBorder = pane.border || {}; return "visible" in paneBorder ? paneBorder.visible : commonPaneBorderVisible }, _getElementsClipRectID: function(paneName) { return this._panesClipRects.fixed[this._getPaneIndex(paneName)].id }, _getCanvasForPane: function(paneName) { var i, panes = this.panes, panesNumber = panes.length; for (i = 0; i < panesNumber; i++) { if (panes[i].name === paneName) { return panes[i].canvas } } }, _getBusinessRange: function(paneName, axisName) { var foundRange, i, ranges = this.businessRanges || [], rangesNumber = ranges.length; for (i = 0; i < rangesNumber; i++) { if (ranges[i].val.pane === paneName && ranges[i].val.axis === axisName) { foundRange = ranges[i]; break } } if (!foundRange) { for (i = 0; i < rangesNumber; i++) { if (ranges[i].val.pane === paneName) { foundRange = ranges[i]; break } } } return foundRange }, _transformArgument: function(translate, scale) { var settings, clipSettings, that = this, rotated = that._isRotated(), panesClipRects = that._panesClipRects; if (!that._transformed) { that._transformed = true; that._labelsGroup.remove(); that._resetIsReady(); _each(that.series || [], function(i, s) { s.applyClip() }) } if (rotated) { settings = { translateY: translate, scaleY: scale }; clipSettings = { translateY: -translate / scale, scaleY: 1 / scale } } else { settings = { translateX: translate, scaleX: scale }; clipSettings = { translateX: -translate / scale, scaleX: 1 / scale } } applyClipSettings(panesClipRects.base, clipSettings); applyClipSettings(panesClipRects.wide, clipSettings); that._seriesGroup.attr(settings); that._scrollBar && that._scrollBar.transform(-translate, scale) }, _resetTransform: function() { var that = this, settings = { translateX: 0, translateY: 0, scaleX: null, scaleY: null }, panesClipRects = that._panesClipRects; applyClipSettings(panesClipRects.base, settings); applyClipSettings(panesClipRects.wide, settings); that._seriesGroup.attr(settings); _each(that.series || [], function(i, s) { s.resetClip() }); that._transformed = false }, _getTrackerSettings: function() { var that = this, themeManager = that._themeManager; return _extend(this.callBase(), { chart: that, zoomingMode: themeManager.getOptions("zoomingMode"), scrollingMode: themeManager.getOptions("scrollingMode"), rotated: that._isRotated(), crosshair: that._getCrosshairOptions().enabled ? that._crosshair : null }) }, _resolveLabelOverlappingStack: function() { var that = this, isRotated = that._isRotated(), shiftDirection = isRotated ? function(box, length) { return { x: box.x - length, y: box.y } } : function(box, length) { return { x: box.x, y: box.y - length } }; _each(that._getStackPoints(), function(_, stacks) { _each(stacks, function(_, points) { overlapping.resolveLabelOverlappingInOneDirection(points, that._getCommonCanvas(), isRotated, shiftDirection) }) }) }, _getStackPoints: function() { var stackPoints = {}, visibleSeries = this._getVisibleSeries(); _each(visibleSeries, function(_, singleSeries) { var points = singleSeries.getPoints(), stackName = singleSeries.getStackName() || null; _each(points, function(_, point) { var argument = point.argument; if (!stackPoints[argument]) { stackPoints[argument] = {} } if (!stackPoints[argument][stackName]) { stackPoints[argument][stackName] = [] } stackPoints[argument][stackName].push(point) }) }); return stackPoints }, _getCrosshairOptions: function() { return this._getOption("crosshair") }, zoomArgument: function(min, max, gesturesUsed) { var bounds, zoomArg, that = this; if (!_isDefined(min) && !_isDefined(max)) { return } if (!gesturesUsed) { that._eventTrigger("zoomStart") } zoomArg = that._argumentAxes[0].zoom(min, max, gesturesUsed); that._zoomMinArg = zoomArg.min; that._zoomMaxArg = zoomArg.max; that._notApplyMargins = gesturesUsed; that._doRender({ force: true, drawTitle: false, drawLegend: false, adjustAxes: false, animate: false }); bounds = that.getVisibleArgumentBounds(); that._eventTrigger("zoomEnd", { rangeStart: bounds.minVisible, rangeEnd: bounds.maxVisible }) }, _resetZoom: function() { var that = this; that._zoomMinArg = that._zoomMaxArg = that._notApplyMargins = void 0; that._argumentAxes[0] && that._argumentAxes[0].resetZoom() }, getVisibleArgumentBounds: function() { var translator = this._argumentAxes[0].getTranslator(), range = translator.getBusinessRange(), isDiscrete = "discrete" === range.axisType, categories = range.categories; return { minVisible: isDiscrete ? range.minVisible || categories[0] : range.minVisible, maxVisible: isDiscrete ? range.maxVisible || categories[categories.length - 1] : range.maxVisible } } }); dxChart.addPlugin(__webpack_require__( /*! ./chart_components/shutter_zoom */ 583)); registerComponent("dxChart", dxChart); module.exports = dxChart; module.exports._test_prepareSegmentRectPoints = function() { var original = prepareSegmentRectPoints.original || prepareSegmentRectPoints; if (arguments[0]) { prepareSegmentRectPoints = arguments[0] } prepareSegmentRectPoints.original = original; prepareSegmentRectPoints.restore = function() { prepareSegmentRectPoints = original }; return prepareSegmentRectPoints } }, /*!***********************************************!*\ !*** ./js/viz/chart_components/base_chart.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, eventUtils = __webpack_require__( /*! ../../events/utils */ 71), BaseWidget = __webpack_require__( /*! ../core/base_widget */ 515), legendModule = __webpack_require__( /*! ../components/legend */ 521), dataValidatorModule = __webpack_require__( /*! ../components/data_validator */ 523), seriesModule = __webpack_require__( /*! ../series/base_series */ 525), chartThemeManagerModule = __webpack_require__( /*! ../components/chart_theme_manager */ 549), LayoutManagerModule = __webpack_require__( /*! ./layout_manager */ 555), trackerModule = __webpack_require__( /*! ./tracker */ 556), headerBlockModule = __webpack_require__( /*! ./header_block */ 557), REINIT_REFRESH_ACTION = "_reinit", REINIT_DATA_SOURCE_REFRESH_ACTION = "_updateDataSource", DATA_INIT_REFRESH_ACTION = "_dataInit", FORCE_RENDER_REFRESH_ACTION = "_forceRender", RESIZE_REFRESH_ACTION = "_resize", ACTIONS_BY_PRIORITY = [REINIT_REFRESH_ACTION, REINIT_DATA_SOURCE_REFRESH_ACTION, DATA_INIT_REFRESH_ACTION, FORCE_RENDER_REFRESH_ACTION, RESIZE_REFRESH_ACTION], vizUtils = __webpack_require__( /*! ../core/utils */ 509), _noop = commonUtils.noop, _map = vizUtils.map, _each = $.each, _extend = extend, _isArray = Array.isArray, _isDefined = commonUtils.isDefined, _setCanvasValues = vizUtils.setCanvasValues, DEFAULT_OPACITY = .3, REFRESH_SERIES_DATA_INIT_ACTION_OPTIONS = ["series", "commonSeriesSettings", "containerBackgroundColor", "dataPrepareSettings", "seriesSelectionMode", "pointSelectionMode", "useAggregation", "synchronizeMultiAxes"], REFRESH_SERIES_FAMILIES_ACTION_OPTIONS = ["equalBarWidth", "minBubbleSize", "maxBubbleSize", "barWidth", "negativesAsZeroes", "negativesAsZeros"], FORCE_RENDER_REFRESH_ACTION_OPTIONS = ["adaptiveLayout", "crosshair", "resolveLabelOverlapping", "adjustOnZoom", "zoomingMode", "scrollingMode"]; function checkHeightLabelsInCanvas(points, canvas, isRotated) { var labels, label, allLabelsAreInvisible, commonLabelSize = 0, canvasSize = canvas.end - canvas.start; for (var i = 0; i < points.length; i++) { labels = points[i].getLabels(); allLabelsAreInvisible = true; for (var j = 0; j < labels.length; j++) { label = labels[j]; if (label.isVisible()) { commonLabelSize += label.getBoundingRect()[isRotated ? "width" : "height"]; allLabelsAreInvisible = false } } if (allLabelsAreInvisible) { points[i] = null } } if (canvasSize > 0) { while (commonLabelSize > canvasSize) { commonLabelSize -= killSmallValues(points, isRotated) } } } function killSmallValues(points, isRotated) { var indexOfPoint, smallestValuePoint = { originalValue: 1 / 0 }, bBox = 0; _each(points, function(index, point) { if (point && smallestValuePoint.originalValue >= point.originalValue) { smallestValuePoint = point; indexOfPoint = index } }); if (null !== indexOfPoint) { points[indexOfPoint].getLabels().forEach(function(label) { bBox += label.getBoundingRect()[isRotated ? "width" : "height"]; label.hide() }); points[indexOfPoint] = null; return bBox } return 0 } function resolveLabelOverlappingInOneDirection(points, canvas, isRotated, shiftFunction) { var rollingStocks = [], stubCanvas = { start: isRotated ? canvas.left : canvas.top, end: isRotated ? canvas.width - canvas.right : canvas.height - canvas.bottom }, hasStackedSeries = false; checkHeightLabelsInCanvas(points, stubCanvas, isRotated); points.forEach(function(p) { if (!p) { return } hasStackedSeries = hasStackedSeries || p.series.isStackedSeries() || p.series.isFullStackedSeries(); p.getLabels().forEach(function(l) { l.isVisible() && rollingStocks.push(new RollingStock(l, isRotated, shiftFunction)) }) }); if (hasStackedSeries) { !isRotated && rollingStocks.reverse() } else { rollingStocks.sort(function(a, b) { return a.getInitialPosition() - b.getInitialPosition() }) } if (!checkStackOverlap(rollingStocks)) { return } rollingStocks.reverse(); moveRollingStock(rollingStocks, stubCanvas) } function overlapRollingStock(firstRolling, secondRolling) { if (!firstRolling || !secondRolling) { return } return firstRolling.getBoundingRect().end > secondRolling.getBoundingRect().start } function checkStackOverlap(rollingStocks) { var i, currentRollingStock, overlap, root; for (i = 0; i < rollingStocks.length - 1; i++) { currentRollingStock = root || rollingStocks[i]; if (overlapRollingStock(currentRollingStock, rollingStocks[i + 1])) { currentRollingStock.toChain(rollingStocks[i + 1]); rollingStocks[i + 1] = null; root = currentRollingStock; overlap = true } else { root = null } } return overlap } function moveRollingStock(rollingStocks, canvas) { var i, j, currentRollingStock, nextRollingStock, currentBBox, nextBBox; for (i = 0; i < rollingStocks.length; i++) { currentRollingStock = rollingStocks[i]; if (rollingStocksIsOut(currentRollingStock, canvas)) { currentBBox = currentRollingStock.getBoundingRect(); for (j = i + 1; j < rollingStocks.length; j++) { nextRollingStock = rollingStocks[j]; if (!nextRollingStock) { continue } nextBBox = nextRollingStock.getBoundingRect(); if (nextBBox.end > currentBBox.start - (currentBBox.end - canvas.end)) { nextRollingStock.toChain(currentRollingStock); rollingStocks[i] = currentRollingStock = null; break } } } currentRollingStock && currentRollingStock.setRollingStockInCanvas(canvas) } } function rollingStocksIsOut(rollingStock, canvas) { return rollingStock && rollingStock.getBoundingRect().end > canvas.end } function RollingStock(label, isRotated, shiftFunction) { var bBox = label.getBoundingRect(); this.labels = [label]; this.shiftFunction = shiftFunction; this._bBox = { start: isRotated ? bBox.x : bBox.y, width: isRotated ? bBox.width : bBox.height, end: isRotated ? bBox.x + bBox.width : bBox.y + bBox.height }; this._initialPosition = isRotated ? bBox.x : bBox.y; return this } RollingStock.prototype = { toChain: function(nextRollingStock) { var nextRollingStockBBox = nextRollingStock.getBoundingRect(); nextRollingStock.shift(nextRollingStockBBox.start - this._bBox.end); this._changeBoxWidth(nextRollingStockBBox.width); this.labels = this.labels.concat(nextRollingStock.labels) }, getBoundingRect: function() { return this._bBox }, shift: function(shiftLength) { var shiftFunction = this.shiftFunction; _each(this.labels, function(index, label) { var bBox = label.getBoundingRect(), coords = shiftFunction(bBox, shiftLength); label.shift(coords.x, coords.y) }); this._bBox.end -= shiftLength; this._bBox.start -= shiftLength }, setRollingStockInCanvas: function(canvas) { if (this._bBox.end > canvas.end) { this.shift(this._bBox.end - canvas.end) } }, getInitialPosition: function() { return this._initialPosition }, _changeBoxWidth: function(width) { this._bBox.end += width; this._bBox.width += width } }; function getLegendFields(name) { return { nameField: name + "Name", colorField: name + "Color", indexField: name + "Index" } } function getLegendSettings(legendDataField) { var formatObjectFields = getLegendFields(legendDataField); return { getFormatObject: function(data) { var res = {}; res[formatObjectFields.indexField] = data.id; res[formatObjectFields.colorField] = data.states.normal.fill; res[formatObjectFields.nameField] = data.text; return res }, textField: formatObjectFields.nameField } } function setTemplateFields(data, templateData, series) { _each(data, function(_, data) { _each(series.getTemplateFields(), function(_, field) { data[field.templateField] = data[field.originalField] }); templateData.push(data) }); series.updateTemplateFieldNames() } function checkOverlapping(firstRect, secondRect) { return (firstRect.x <= secondRect.x && secondRect.x <= firstRect.x + firstRect.width || firstRect.x >= secondRect.x && firstRect.x <= secondRect.x + secondRect.width) && (firstRect.y <= secondRect.y && secondRect.y <= firstRect.y + firstRect.height || firstRect.y >= secondRect.y && firstRect.y <= secondRect.y + secondRect.height) } var overlapping = { resolveLabelOverlappingInOneDirection: resolveLabelOverlappingInOneDirection }; function suppressCommonLayout(layout) { layout.forward = function(rect) { return rect }; layout.backward = _noop } var BaseChart = BaseWidget.inherit({ _eventsMap: { onSeriesClick: { name: "seriesClick" }, onPointClick: { name: "pointClick" }, onArgumentAxisClick: { name: "argumentAxisClick" }, onLegendClick: { name: "legendClick" }, onSeriesSelectionChanged: { name: "seriesSelectionChanged" }, onPointSelectionChanged: { name: "pointSelectionChanged" }, onSeriesHoverChanged: { name: "seriesHoverChanged" }, onPointHoverChanged: { name: "pointHoverChanged" }, onDone: { name: "done" }, onZoomStart: { name: "zoomStart" }, onZoomEnd: { name: "zoomEnd" } }, _rootClassPrefix: "dxc", _rootClass: "dxc-chart", _init: function() { this._savedBusinessRange = {}; this.callBase.apply(this, arguments) }, _initialChanges: ["REINIT"], _themeDependentChanges: ["REFRESH_SERIES_REINIT"], _createThemeManager: function() { var option = this.option(), themeManager = new chartThemeManagerModule.ThemeManager(option, this._chartType); themeManager.setTheme(option.theme, option.rtlEnabled); return themeManager }, _initCore: function() { var that = this; suppressCommonLayout(that._layout); that._canvasClipRect = that._renderer.clipRect(); that._createHtmlStructure(); that._headerBlock = new headerBlockModule.HeaderBlock; that._createLegend(); that._createTracker(); that._needHandleRenderComplete = true; that.layoutManager = new LayoutManagerModule.LayoutManager; that._createScrollBar(); that._$element.on("contextmenu", function(event) { that.eventType = "contextmenu"; if (eventUtils.isTouchEvent(event) || eventUtils.isPointerEvent(event)) { event.preventDefault() } }).on("MSHoldVisual", function(event) { that.eventType = "MSHoldVisual"; event.preventDefault() }) }, _getLayoutItems: commonUtils.noop, _layoutManagerOptions: function() { return this._themeManager.getOptions("adaptiveLayout") }, _reinit: function() { var that = this; _setCanvasValues(that._canvas); that._reinitAxes(); that._skipRender = true; that._updateDataSource(); if (!that.series) { that._dataSpecificInit(false) } that._skipRender = false; that._correctAxes(); that._forceRender() }, _correctAxes: _noop, _createHtmlStructure: function() { var that = this, renderer = that._renderer, root = renderer.root; that._backgroundRect = renderer.rect().attr({ fill: "gray", opacity: 1e-4 }).append(root); that._panesBackgroundGroup = renderer.g().attr({ "class": "dxc-background" }).append(root); that._stripsGroup = renderer.g().attr({ "class": "dxc-strips-group" }).linkOn(root, "strips"); that._gridGroup = renderer.g().attr({ "class": "dxc-grids-group" }).linkOn(root, "grids"); that._axesGroup = renderer.g().attr({ "class": "dxc-axes-group" }).linkOn(root, "axes"); that._constantLinesGroup = renderer.g().attr({ "class": "dxc-constant-lines-group" }).linkOn(root, "constant-lines"); that._labelAxesGroup = renderer.g().attr({ "class": "dxc-strips-labels-group" }).linkOn(root, "strips-labels"); that._panesBorderGroup = renderer.g().attr({ "class": "dxc-border" }).linkOn(root, "border"); that._seriesGroup = renderer.g().attr({ "class": "dxc-series-group" }).linkOn(root, "series"); that._labelsGroup = renderer.g().attr({ "class": "dxc-labels-group" }).linkOn(root, "labels"); that._crosshairCursorGroup = renderer.g().attr({ "class": "dxc-crosshair-cursor" }).linkOn(root, "crosshair"); that._legendGroup = renderer.g().attr({ "class": "dxc-legend", "clip-path": that._getCanvasClipRectID() }).linkOn(root, "legend"); that._scrollBarGroup = renderer.g().attr({ "class": "dxc-scroll-bar" }).linkOn(root, "scroll-bar") }, _disposeObjectsInArray: function(propName, fieldNames) { _each(this[propName] || [], function(_, item) { if (fieldNames && item) { _each(fieldNames, function(_, field) { item[field] && item[field].dispose() }) } else { item && item.dispose() } }); this[propName] = null }, _disposeCore: function() { var that = this, disposeObject = function(propName) { if (that[propName]) { that[propName].dispose(); that[propName] = null } }, unlinkGroup = function(name) { that[name].linkOff() }, disposeObjectsInArray = this._disposeObjectsInArray; that._renderer.stopAllAnimations(); that.businessRanges = null; disposeObjectsInArray.call(that, "series"); disposeObject("_headerBlock"); disposeObject("_tracker"); disposeObject("_crosshair"); that.layoutManager = that._userOptions = that._canvas = that._groupsData = null; unlinkGroup("_stripsGroup"); unlinkGroup("_gridGroup"); unlinkGroup("_axesGroup"); unlinkGroup("_constantLinesGroup"); unlinkGroup("_labelAxesGroup"); unlinkGroup("_panesBorderGroup"); unlinkGroup("_seriesGroup"); unlinkGroup("_labelsGroup"); unlinkGroup("_crosshairCursorGroup"); unlinkGroup("_legendGroup"); unlinkGroup("_scrollBarGroup"); disposeObject("_canvasClipRect"); disposeObject("_panesBackgroundGroup"); disposeObject("_backgroundRect"); disposeObject("_stripsGroup"); disposeObject("_gridGroup"); disposeObject("_axesGroup"); disposeObject("_constantLinesGroup"); disposeObject("_labelAxesGroup"); disposeObject("_panesBorderGroup"); disposeObject("_seriesGroup"); disposeObject("_labelsGroup"); disposeObject("_crosshairCursorGroup"); disposeObject("_legendGroup"); disposeObject("_scrollBarGroup") }, _getAnimationOptions: function() { return this._themeManager.getOptions("animation") }, _getDefaultSize: function() { return { width: 400, height: 400 } }, _getOption: function(name) { return this._themeManager.getOptions(name) }, _applySize: function() { this._processRefreshData(RESIZE_REFRESH_ACTION) }, _resize: function() { this._doRender(this.__renderOptions || { animate: false, isResize: true }) }, _trackerType: "ChartTracker", _createTracker: function() { var that = this; that._tracker = new trackerModule[that._trackerType]({ seriesGroup: that._seriesGroup, renderer: that._renderer, tooltip: that._tooltip, legend: that._legend, eventTrigger: that._eventTrigger }) }, _getTrackerSettings: function() { return this._getSelectionModes() }, _getSelectionModes: function() { var themeManager = this._themeManager; return { seriesSelectionMode: themeManager.getOptions("seriesSelectionMode"), pointSelectionMode: themeManager.getOptions("pointSelectionMode") } }, _updateTracker: function(trackerCanvases) { var that = this; that._tracker.update(that._getTrackerSettings()); that._tracker.setCanvases({ left: 0, right: that._canvas.width, top: 0, bottom: that._canvas.height }, trackerCanvases) }, _doRender: function(_options) { var drawOptions, recreateCanvas, that = this; if ( /*!that._initialized || */ that._skipRender) { return } if (0 === that._canvas.width && 0 === that._canvas.height) { return } that._resetIsReady(); drawOptions = that._prepareDrawOptions(_options); recreateCanvas = drawOptions.recreateCanvas; that.__originalCanvas = that._canvas; that._canvas = extend({}, that._canvas); if (recreateCanvas) { that.__currentCanvas = that._canvas } else { that._canvas = that.__currentCanvas } that.DEBUG_canvas = that._canvas; recreateCanvas && that._updateCanvasClipRect(that._canvas); that._renderer.stopAllAnimations(true); _setCanvasValues(that._canvas); that._cleanGroups(); that._renderElements(drawOptions) }, _renderElements: function(drawOptions) { var argBusinessRange, zoomMinArg, zoomMaxArg, that = this, preparedOptions = that._prepareToRender(drawOptions), isRotated = that._isRotated(), isLegendInside = that._isLegendInside(), trackerCanvases = [], layoutTargets = that._getLayoutTargets(), dirtyCanvas = extend({}, that._canvas), drawElements = [], layoutCanvas = drawOptions.drawTitle && drawOptions.drawLegend && drawOptions.adjustAxes; that.DEBUG_dirtyCanvas = dirtyCanvas; if (layoutCanvas) { drawElements = that._getDrawElements(drawOptions, isLegendInside) } that._renderer.lock(); that.layoutManager.setOptions(that._layoutManagerOptions()); that.layoutManager.layoutElements(drawElements, that._canvas, function(sizeShortage) { that._renderAxes(drawOptions, preparedOptions, isRotated); sizeShortage && that._shrinkAxes(drawOptions, sizeShortage) }, layoutTargets, isRotated); layoutCanvas && that._updateCanvasClipRect(dirtyCanvas); that._applyClipRects(preparedOptions); that._appendSeriesGroups(); that._createCrosshairCursor(); _each(layoutTargets, function() { var canvas = this.canvas; trackerCanvases.push({ left: canvas.left, right: canvas.width - canvas.right, top: canvas.top, bottom: canvas.height - canvas.bottom }) }); if (that._scrollBar) { argBusinessRange = that._argumentAxes[0].getTranslator().getBusinessRange(); if ("discrete" === argBusinessRange.axisType && argBusinessRange.categories && argBusinessRange.categories.length <= 1) { zoomMinArg = zoomMaxArg = void 0 } else { zoomMinArg = argBusinessRange.minVisible; zoomMaxArg = argBusinessRange.maxVisible } that._scrollBar.init(argBusinessRange).setPosition(zoomMinArg, zoomMaxArg) } that._updateTracker(trackerCanvases); that._updateLegendPosition(drawOptions, isLegendInside); that._renderSeries(drawOptions, isRotated, isLegendInside); that._renderer.unlock() }, _createCrosshairCursor: _noop, _appendSeriesGroups: function() { this._seriesGroup.linkAppend(); this._labelsGroup.linkAppend(); this._appendAdditionalSeriesGroups() }, _renderSeries: function(drawOptions, isRotated, isLegendInside) { this._calculateSeriesLayout(drawOptions, isRotated); this._renderSeriesElements(drawOptions, isRotated, isLegendInside) }, _calculateSeriesLayout: function(drawOptions, isRotated) { drawOptions.hideLayoutLabels = this.layoutManager.needMoreSpaceForPanesCanvas(this._getLayoutTargets(), isRotated) && !this._themeManager.getOptions("adaptiveLayout").keepLabels; this._updateSeriesDimensions(drawOptions); this._canvas = this.__originalCanvas }, _renderSeriesElements: function(drawOptions, isRotated, isLegendInside) { var i, singleSeries, that = this, series = that.series, seriesLength = series.length, resolveLabelOverlapping = that._themeManager.getOptions("resolveLabelOverlapping"); for (i = 0; i < seriesLength; i++) { singleSeries = series[i]; that._applyExtraSettings(singleSeries, drawOptions); singleSeries.draw(drawOptions.animate && singleSeries.getPoints().length <= drawOptions.animationPointsLimit && that._renderer.animationEnabled(), drawOptions.hideLayoutLabels, that._getLegendCallBack(singleSeries)) } "none" !== resolveLabelOverlapping && that._resolveLabelOverlapping(resolveLabelOverlapping); that._adjustSeries(); that._renderTrackers(isLegendInside); that._tracker.repairTooltip(); that._drawn(); that._renderCompleteHandler() }, _resolveLabelOverlapping: function(resolveLabelOverlapping) { var func; switch (resolveLabelOverlapping) { case "stack": func = this._resolveLabelOverlappingStack; break; case "hide": func = this._resolveLabelOverlappingHide; break; case "shift": func = this._resolveLabelOverlappingShift } commonUtils.isFunction(func) && func.call(this) }, _getVisibleSeries: function() { return commonUtils.grep(this.getAllSeries(), function(series) { return series.isVisible() }) }, _resolveLabelOverlappingHide: function() { var currentLabel, nextLabel, currentLabelRect, nextLabelRect, i, j, points, labels = [], series = this._getVisibleSeries(); for (i = 0; i < series.length; i++) { points = series[i].getVisiblePoints(); for (j = 0; j < points.length; j++) { labels = labels.concat(points[j].getLabels()) } } for (i = 0; i < labels.length; i++) { currentLabel = labels[i]; currentLabelRect = currentLabel.getBoundingRect(); if (!currentLabel.isVisible()) { continue } for (j = i + 1; j < labels.length; j++) { nextLabel = labels[j]; nextLabelRect = nextLabel.getBoundingRect(); if (checkOverlapping(currentLabelRect, nextLabelRect)) { nextLabel.hide() } } } }, _cleanGroups: function() { var that = this; that._stripsGroup.linkRemove().clear(); that._gridGroup.linkRemove().clear(); that._axesGroup.linkRemove().clear(); that._constantLinesGroup.linkRemove().clear(); that._labelAxesGroup.linkRemove().clear(); that._labelsGroup.linkRemove().clear(); that._crosshairCursorGroup.linkRemove().clear() }, _createLegend: function() { var that = this, legendSettings = getLegendSettings(that._legendDataField); that._legend = new legendModule.Legend({ renderer: that._renderer, group: that._legendGroup, backgroundClass: "dxc-border", itemGroupClass: "dxc-item", textField: legendSettings.textField, getFormatObject: legendSettings.getFormatObject }) }, _updateLegend: function() { var that = this, themeManager = that._themeManager, legendOptions = themeManager.getOptions("legend"), legendData = that._getLegendData(); legendOptions.containerBackgroundColor = themeManager.getOptions("containerBackgroundColor"); legendOptions._incidentOccurred = that._incidentOccurred; that._legend.update(legendData, legendOptions) }, _prepareDrawOptions: function(drawOptions) { var options, animationOptions = this._getAnimationOptions(); options = extend({}, { force: false, adjustAxes: true, drawLegend: true, drawTitle: true, animate: animationOptions.enabled, animationPointsLimit: animationOptions.maxPointCountSupported }, drawOptions, this.__renderOptions); if (!_isDefined(options.recreateCanvas)) { options.recreateCanvas = options.adjustAxes && options.drawLegend && options.drawTitle } return options }, _processRefreshData: function(newRefreshAction) { var currentRefreshActionPosition = inArray(this._currentRefreshData, ACTIONS_BY_PRIORITY), newRefreshActionPosition = inArray(newRefreshAction, ACTIONS_BY_PRIORITY); if (!this._currentRefreshData || currentRefreshActionPosition >= 0 && newRefreshActionPosition < currentRefreshActionPosition) { this._currentRefreshData = newRefreshAction } }, _getLegendData: function() { return _map(this._getLegendTargets(), function(item) { var legendData = item.legendData, style = item.getLegendStyles, opacity = style.normal.opacity; if (!item.visible) { if (!_isDefined(opacity) || opacity > DEFAULT_OPACITY) { opacity = DEFAULT_OPACITY } legendData.textOpacity = DEFAULT_OPACITY } legendData.states = { hover: style.hover, selection: style.selection, normal: _extend({}, style.normal, { opacity: opacity }) }; return legendData }) }, _getLegendOptions: function(item) { return { legendData: { text: item[this._legendItemTextField], argument: item.argument, id: item.index, argumentIndex: item.argumentIndex }, getLegendStyles: item.getLegendStyles(), visible: item.isVisible() } }, _disposeSeries: function() { var that = this; _each(that.series || [], function(_, series) { series.dispose() }); that.series = null; _each(that.seriesFamilies || [], function(_, family) { family.dispose() }); that.seriesFamilies = null; that._needHandleRenderComplete = true }, _optionChanged: function(arg) { this._themeManager.resetOptions(arg.name); this.callBase.apply(this, arguments) }, _applyChanges: function() { var that = this; that._themeManager.update(that._options); that.callBase.apply(that, arguments); that._doRefresh() }, _optionChangesMap: { animation: "ANIMATION", dataSource: "DATA_SOURCE", palette: "PALETTE", legend: "DATA_INIT", seriesTemplate: "DATA_INIT", "export": "FORCE_RENDER", valueAxis: "AXES_AND_PANES", argumentAxis: "AXES_AND_PANES", commonAxisSettings: "AXES_AND_PANES", panes: "AXES_AND_PANES", defaultPane: "AXES_AND_PANES", rotated: "ROTATED", customizePoint: "REFRESH_SERIES_REINIT", customizeLabel: "REFRESH_SERIES_REINIT", scrollBar: "SCROLL_BAR" }, _customChangesOrder: ["ANIMATION", "DATA_SOURCE", "PALETTE", "REFRESH_SERIES_DATA_INIT", "DATA_INIT", "REFRESH_SERIES_FAMILIES", "FORCE_RENDER", "AXES_AND_PANES", "ROTATED", "REFRESH_SERIES_REINIT", "SCROLL_BAR", "CHART_TOOLTIP", "REINIT"], _change_ANIMATION: function() { this._renderer.updateAnimationOptions(this._getAnimationOptions()) }, _change_DATA_SOURCE: function() { this._needHandleRenderComplete = true; this._processRefreshData(REINIT_DATA_SOURCE_REFRESH_ACTION) }, _change_PALETTE: function() { this._themeManager.updatePalette(this.option("palette")); this._refreshSeries(DATA_INIT_REFRESH_ACTION) }, _change_REFRESH_SERIES_DATA_INIT: function() { this._refreshSeries(DATA_INIT_REFRESH_ACTION) }, _change_DATA_INIT: function() { this._processRefreshData(DATA_INIT_REFRESH_ACTION) }, _change_REFRESH_SERIES_FAMILIES: function() { this._processSeriesFamilies(); this._populateBusinessRange(); this._processRefreshData(FORCE_RENDER_REFRESH_ACTION) }, _change_FORCE_RENDER: function() { this._processRefreshData(FORCE_RENDER_REFRESH_ACTION) }, _change_AXES_AND_PANES: function() { this._refreshSeries(REINIT_REFRESH_ACTION) }, _change_ROTATED: function() { this._createScrollBar(); this._refreshSeries(REINIT_REFRESH_ACTION) }, _change_REFRESH_SERIES_REINIT: function() { this._refreshSeries(REINIT_REFRESH_ACTION) }, _change_SCROLL_BAR: function() { this._createScrollBar(); this._processRefreshData(FORCE_RENDER_REFRESH_ACTION) }, _change_CHART_TOOLTIP: function() { this._organizeStackPoints() }, _change_REINIT: function() { this._processRefreshData(REINIT_REFRESH_ACTION) }, _refreshSeries: function(actionName) { this._disposeSeries(); this._processRefreshData(actionName) }, _doRefresh: function() { var methodName = this._currentRefreshData; if (methodName) { this._currentRefreshData = null; this._renderer.stopAllAnimations(true); this[methodName]() } }, _updateCanvasClipRect: function(canvas) { var width, height, that = this; width = Math.max(canvas.width - canvas.left - canvas.right, 0); height = Math.max(canvas.height - canvas.top - canvas.bottom, 0); that._canvasClipRect.attr({ x: canvas.left, y: canvas.top, width: width, height: height }); that._backgroundRect.attr({ x: canvas.left, y: canvas.top, width: width, height: height }) }, _getCanvasClipRectID: function() { return this._canvasClipRect.id }, _dataSourceChangedHandler: function() { this._resetZoom(); this._dataInit() }, _dataInit: function() { this._dataSpecificInit(true) }, _dataSpecificInit: function(needRedraw) { var that = this; that.series = that.series || that._populateSeries(); that._repopulateSeries(); that._seriesPopulatedHandlerCore(); that._populateBusinessRange(); that._tracker.updateSeries(that.series); that._updateLegend(); needRedraw && that._forceRender() }, _forceRender: function() { this._doRender({ force: true }) }, _repopulateSeries: function() { var parsedData, that = this, themeManager = that._themeManager, data = that._dataSourceItems(), dataValidatorOptions = themeManager.getOptions("dataPrepareSettings"), seriesTemplate = themeManager.getOptions("seriesTemplate"); if (seriesTemplate) { that._templatedSeries = vizUtils.processSeriesTemplate(seriesTemplate, data); that._populateSeries(); delete that._templatedSeries; data = that.templateData || data } that._groupSeries(); parsedData = dataValidatorModule.validateData(data, that._groupsData, that._incidentOccurred, dataValidatorOptions); themeManager.resetPalette(); that.series.forEach(function(singleSeries) { singleSeries.updateData(parsedData[singleSeries.getArgumentField()]); that._processSingleSeries(singleSeries) }); that._organizeStackPoints() }, _organizeStackPoints: function() { var that = this, themeManager = that._themeManager, sharedTooltip = themeManager.getOptions("tooltip").shared, stackPoints = {}; _each(that.series || [], function(_, singleSeries) { that._resetStackPoints(singleSeries); sharedTooltip && that._prepareStackPoints(singleSeries, stackPoints) }) }, _renderCompleteHandler: function() { var that = this, allSeriesInited = true; if (that._needHandleRenderComplete) { _each(that.series, function(_, s) { allSeriesInited = allSeriesInited && s.canRenderCompleteHandle() }); if (allSeriesInited) { that._needHandleRenderComplete = false; that._eventTrigger("done", { target: that }) } } }, _getDrawElements: function(drawOptions, legendHasInsidePosition) { var legendOptions, that = this, drawElements = [], exportOptions = that._themeManager.getOptions("export"), titleOptions = that._title.getLayoutOptions() || {}, headerElements = []; if (that._exportMenu && exportOptions.enabled) { headerElements.push(that._exportMenu); drawElements.push(that._headerBlock) } if (drawOptions.drawTitle) { "bottom" !== titleOptions.verticalAlignment && headerElements.length ? headerElements.push(that._title) : drawElements.push(that._title) } if (drawOptions.drawLegend && that._legend) { that._legendGroup.linkAppend(); if (!legendHasInsidePosition) { legendOptions = that._legend.getLayoutOptions(); if (1 === headerElements.length && "bottom" !== legendOptions.verticalAlignment && "vertical" === legendOptions.cutSide) { headerElements.push(that._legend) } else { drawElements.push(that._legend) } } } if (headerElements.length) { that._headerBlock.update(headerElements, that._canvas) } return drawElements }, _resetZoom: _noop, _dataIsReady: function() { return _isDefined(this.option("dataSource")) && this._dataIsLoaded() }, _populateSeries: function() { var particularSeriesOptions, particularSeries, seriesTheme, data, i, eventPipe, that = this, themeManager = that._themeManager, hasSeriesTemplate = !!themeManager.getOptions("seriesTemplate"), seriesOptions = hasSeriesTemplate ? that._templatedSeries : that.option("series"), allSeriesOptions = _isArray(seriesOptions) ? seriesOptions : seriesOptions ? [seriesOptions] : [], extraOptions = that._getExtraOptions(), seriesVisibilityChanged = function() { that._specialProcessSeries(); that._populateBusinessRange(); that._renderer.stopAllAnimations(true); that._updateLegend(); that._doRender({ force: true }) }; that._disposeSeries(); that.series = []; that.templateData = []; themeManager.resetPalette(); eventPipe = function(data) { that.series.forEach(function(currentSeries) { currentSeries.notify(data) }) }; for (i = 0; i < allSeriesOptions.length; i++) { particularSeriesOptions = _extend(true, {}, allSeriesOptions[i], extraOptions); if (!particularSeriesOptions.name) { particularSeriesOptions.name = "Series " + (i + 1).toString() } data = particularSeriesOptions.data; particularSeriesOptions.data = null; particularSeriesOptions.rotated = that._isRotated(); particularSeriesOptions.customizePoint = themeManager.getOptions("customizePoint"); particularSeriesOptions.customizeLabel = themeManager.getOptions("customizeLabel"); particularSeriesOptions.visibilityChanged = seriesVisibilityChanged; particularSeriesOptions.incidentOccurred = that._incidentOccurred; seriesTheme = themeManager.getOptions("series", particularSeriesOptions); if (!that._checkPaneName(seriesTheme)) { continue } particularSeries = new seriesModule.Series({ renderer: that._renderer, seriesGroup: that._seriesGroup, labelsGroup: that._labelsGroup, eventTrigger: that._eventTrigger, commonSeriesModes: that._getSelectionModes(), eventPipe: eventPipe, argumentAxis: that._getArgumentAxis(), valueAxis: that._getValueAxis(seriesTheme.pane, seriesTheme.axis) }, seriesTheme); if (!particularSeries.isUpdated) { that._incidentOccurred("E2101", [seriesTheme.type]) } else { particularSeries.index = that.series.length; that._processSingleSeries(particularSeries); that.series.push(particularSeries); if (hasSeriesTemplate) { setTemplateFields(data, that.templateData, particularSeries) } } } return that.series }, getAllSeries: function() { return this.series.slice() }, getSeriesByName: function(name) { var found = null; _each(this.series, function(i, singleSeries) { if (singleSeries.name === name) { found = singleSeries; return false } }); return found }, getSeriesByPos: function(pos) { return this.series[pos] }, clearSelection: function() { this._tracker.clearSelection() }, hideTooltip: function() { this._tracker._hideTooltip() }, render: function(renderOptions) { var that = this; that.__renderOptions = renderOptions; that.__forceRender = renderOptions && renderOptions.force; that.callBase.apply(that, arguments); that.__renderOptions = that.__forceRender = null; return that } }); REFRESH_SERIES_DATA_INIT_ACTION_OPTIONS.forEach(function(name) { BaseChart.prototype._optionChangesMap[name] = "REFRESH_SERIES_DATA_INIT" }); FORCE_RENDER_REFRESH_ACTION_OPTIONS.forEach(function(name) { BaseChart.prototype._optionChangesMap[name] = "FORCE_RENDER" }); REFRESH_SERIES_FAMILIES_ACTION_OPTIONS.forEach(function(name) { BaseChart.prototype._optionChangesMap[name] = "REFRESH_SERIES_FAMILIES" }); exports.overlapping = overlapping; exports.BaseChart = BaseChart; BaseChart.addPlugin(__webpack_require__( /*! ../core/export */ 511).plugin); BaseChart.addPlugin(__webpack_require__( /*! ../core/title */ 558).plugin); BaseChart.addPlugin(__webpack_require__( /*! ../core/tooltip */ 559).plugin); BaseChart.addPlugin(__webpack_require__( /*! ../core/loading_indicator */ 560).plugin); BaseChart.addPlugin(__webpack_require__( /*! ../core/data_source */ 561).plugin); var _change_TITLE = BaseChart.prototype._change_TITLE; BaseChart.prototype._change_TITLE = function() { _change_TITLE.apply(this, arguments); this._change(["FORCE_RENDER"]) }; var _change_TOOLTIP = BaseChart.prototype._change_TOOLTIP; BaseChart.prototype._change_TOOLTIP = function() { _change_TOOLTIP.apply(this, arguments); this._change(["CHART_TOOLTIP"]) } }, /*!************************************!*\ !*** ./js/viz/core/base_widget.js ***! \************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, version = __webpack_require__( /*! ../../core/version */ 19), _windowResizeCallbacks = __webpack_require__( /*! ../../core/utils/window */ 44).resizeCallbacks, _stringFormat = __webpack_require__( /*! ../../core/utils/string */ 18).format, _isObject = __webpack_require__( /*! ../../core/utils/common */ 14).isObject, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _floor = Math.floor, DOMComponent = __webpack_require__( /*! ../../core/dom_component */ 43), helpers = __webpack_require__( /*! ./helpers */ 516), _parseScalar = __webpack_require__( /*! ./utils */ 509).parseScalar, errors = __webpack_require__( /*! ./errors_warnings */ 517), _log = errors.log, rendererModule = __webpack_require__( /*! ./renderers/renderer */ 518), _Layout = __webpack_require__( /*! ./layout */ 520), OPTION_RTL_ENABLED = "rtlEnabled", _option = DOMComponent.prototype.option; function getTrue() { return true } function getFalse() { return false } function areCanvasesDifferent(canvas1, canvas2) { return !(canvas1.width === canvas2.width && canvas1.height === canvas2.height && canvas1.left === canvas2.left && canvas1.top === canvas2.top && canvas1.right === canvas2.right && canvas1.bottom === canvas2.bottom) } function createResizeHandler(callback) { var timeout, handler = function() { clearTimeout(timeout); timeout = setTimeout(callback, 100) }; handler.dispose = function() { clearTimeout(timeout); return this }; return handler } function defaultOnIncidentOccurred(e) { _log.apply(null, [e.target.id].concat(e.target.args || [])) } var createIncidentOccurred = function(widgetName, eventTrigger) { return incidentOccurred; function incidentOccurred(id, args) { eventTrigger("incidentOccurred", { target: { id: id, type: "E" === id[0] ? "error" : "warning", args: args, text: _stringFormat.apply(null, [errors.ERROR_MESSAGES[id]].concat(args || [])), widget: widgetName, version: version } }) } }; function pickPositiveValue(value, defaultValue) { return Number(value > 0 ? value : defaultValue || 0) } module.exports = DOMComponent.inherit({ _eventsMap: { onIncidentOccurred: { name: "incidentOccurred" }, onDrawn: { name: "drawn" } }, _getDefaultOptions: function() { return extend(this.callBase(), { onIncidentOccurred: defaultOnIncidentOccurred }) }, _useLinks: true, _init: function() { var linkTarget, that = this; that.callBase.apply(that, arguments); that._changesLocker = 0; that._changes = helpers.changes(); that._suspendChanges(); that._themeManager = that._createThemeManager(); that._themeManager.setCallback(function() { that._requestChange(that._themeDependentChanges) }); that._renderElementAttributes(); that._initRenderer(); linkTarget = that._useLinks && that._renderer.root; linkTarget && linkTarget.enableLinks().virtualLink("core").virtualLink("peripheral"); that._renderVisibilityChange(); that._initEventTrigger(); that._incidentOccurred = createIncidentOccurred(that.NAME, that._eventTrigger); that._layout = new _Layout; linkTarget && linkTarget.linkAfter("core"); that._initPlugins(); that._initCore(); linkTarget && linkTarget.linkAfter(); that._change(that._initialChanges); that._resumeChanges() }, _initialChanges: ["LAYOUT", "RESIZE_HANDLER", "THEME"], _initPlugins: function() { var that = this; $.each(that._plugins, function(_, plugin) { plugin.init.call(that) }) }, _disposePlugins: function() { var that = this; $.each(that._plugins.slice().reverse(), function(_, plugin) { plugin.dispose.call(that) }) }, _change: function(codes) { this._changes.add(codes) }, _suspendChanges: function() { ++this._changesLocker }, _resumeChanges: function() { var that = this; if (0 === --that._changesLocker && that._changes.count() > 0 && !that._applyingChanges) { that._renderer.lock(); that._applyingChanges = true; that._applyChanges(); that._changes.reset(); that._applyingChanges = false; that._renderer.unlock(); if (that._optionsQueue) { that._applyQueuedOptions() } } }, _applyQueuedOptions: function() { var that = this, queue = that._optionsQueue; that._optionsQueue = null; that.beginUpdate(); $.each(queue, function(_, action) { action() }); that.endUpdate() }, _requestChange: function(codes) { this._suspendChanges(); this._change(codes); this._resumeChanges() }, _applyChanges: function() { var i, that = this, changes = that._changes, order = that._totalChangesOrder, ii = order.length; for (i = 0; i < ii; ++i) { if (changes.has(order[i])) { that["_change_" + order[i]]() } } }, _optionChangesOrder: ["EVENTS", "THEME", "RENDERER", "RESIZE_HANDLER"], _layoutChangesOrder: ["ELEMENT_ATTR", "CONTAINER_SIZE", "LAYOUT"], _customChangesOrder: [], _change_EVENTS: function() { this._eventTrigger.applyChanges() }, _change_THEME: function() { this._setThemeAndRtl() }, _change_RENDERER: function() { this._setRendererOptions() }, _change_RESIZE_HANDLER: function() { this._setupResizeHandler() }, _change_ELEMENT_ATTR: function() { this._renderElementAttributes(); this._change(["CONTAINER_SIZE"]) }, _change_CONTAINER_SIZE: function() { this._updateSize() }, _change_LAYOUT: function() { this._setContentSize() }, _themeDependentChanges: ["RENDERER"], _initRenderer: function() { var that = this; that._canvas = that._calculateCanvas(); that._renderer = new rendererModule.Renderer({ cssClass: that._rootClassPrefix + " " + that._rootClass, pathModified: that.option("pathModified"), container: that._$element[0] }); that._renderer.resize(that._canvas.width, that._canvas.height) }, _disposeRenderer: function() { this._useLinks && this._renderer.root.checkLinks(); this._renderer.dispose() }, _getAnimationOptions: noop, render: function() { this._requestChange(["CONTAINER_SIZE"]); this._onRender() }, _onRender: noop, _dispose: function() { var that = this; that.callBase.apply(that, arguments); that._removeResizeHandler(); that._layout.dispose(); that._eventTrigger.dispose(); that._disposeCore(); that._disposePlugins(); that._disposeRenderer(); that._themeManager.dispose(); that._themeManager = that._renderer = that._eventTrigger = null }, _initEventTrigger: function() { var that = this; that._eventTrigger = createEventTrigger(that._eventsMap, function(name) { return that._createActionByOption(name) }) }, _calculateCanvas: function() { var that = this, size = that.option("size") || {}, margin = that.option("margin") || {}, defaultCanvas = that._getDefaultSize() || {}, canvas = { width: size.width <= 0 ? 0 : _floor(pickPositiveValue(size.width, that._$element.width() || defaultCanvas.width)), height: size.height <= 0 ? 0 : _floor(pickPositiveValue(size.height, that._$element.height() || defaultCanvas.height)), left: pickPositiveValue(margin.left, defaultCanvas.left || 0), top: pickPositiveValue(margin.top, defaultCanvas.top || 0), right: pickPositiveValue(margin.right, defaultCanvas.right || 0), bottom: pickPositiveValue(margin.bottom, defaultCanvas.bottom || 0) }; if (canvas.width - canvas.left - canvas.right <= 0 || canvas.height - canvas.top - canvas.bottom <= 0) { canvas = { width: 0, height: 0 } } return canvas }, _updateSize: function() { var that = this, canvas = that._calculateCanvas(); if (areCanvasesDifferent(that._canvas, canvas) || that.__forceRender) { that._canvas = canvas; that._renderer.resize(canvas.width, canvas.height); that._change(["LAYOUT"]) } }, _setContentSize: function() { var nextRect, canvas = this._canvas, layout = this._layout, rect = canvas.width > 0 && canvas.height > 0 ? [canvas.left, canvas.top, canvas.width - canvas.right, canvas.height - canvas.bottom] : [0, 0, 0, 0]; rect = layout.forward(rect); nextRect = this._applySize(rect) || rect; layout.backward(nextRect) }, DEBUG_getCanvas: function() { return this._canvas }, DEBUG_getEventTrigger: function() { return this._eventTrigger }, _getOption: function(name, isScalar) { var theme = this._themeManager.theme(name), option = this.option(name); return isScalar ? void 0 !== option ? option : theme : extend(true, {}, theme, option) }, _setupResizeHandler: function() { if (_parseScalar(this._getOption("redrawOnResize", true), true)) { this._addResizeHandler() } else { this._removeResizeHandler() } }, _addResizeHandler: function() { var that = this; if (!that._resizeHandler) { that._resizeHandler = createResizeHandler(function() { that._requestChange(["CONTAINER_SIZE"]) }); _windowResizeCallbacks.add(that._resizeHandler) } }, _removeResizeHandler: function() { if (this._resizeHandler) { _windowResizeCallbacks.remove(this._resizeHandler); this._resizeHandler.dispose(); this._resizeHandler = null } }, _onBeginUpdate: noop, beginUpdate: function() { var that = this; if (that._initialized && 0 === that._updateLockCount) { that._onBeginUpdate(); that._suspendChanges() } that.callBase.apply(that, arguments); return that }, endUpdate: function() { var that = this, initialized = that._initialized; that.callBase.apply(that, arguments); if (initialized && 0 === that._updateLockCount) { that._resumeChanges() } return that }, option: function(name) { var that = this; if (that._initialized && that._applyingChanges && (arguments.length > 1 || _isObject(name))) { that._optionsQueue = that._optionsQueue || []; that._optionsQueue.push(that._getActionForUpdating(arguments)) } else { return _option.apply(that, arguments) } }, _getActionForUpdating: function(args) { var that = this; return that._deprecatedOptionsSuppressed ? function() { that._suppressDeprecatedWarnings(); _option.apply(that, args); that._resumeDeprecatedWarnings() } : function() { _option.apply(that, args) } }, _clean: noop, _render: noop, _optionChanged: function(arg) { var that = this; if (that._eventTrigger.change(arg.name)) { that._change(["EVENTS"]) } else { if (that._optionChangesMap[arg.name]) { that._change([that._optionChangesMap[arg.name]]) } else { that.callBase.apply(that, arguments) } } }, _optionChangesMap: { size: "CONTAINER_SIZE", margin: "CONTAINER_SIZE", redrawOnResize: "RESIZE_HANDLER", theme: "THEME", rtlEnabled: "THEME", encodeHtml: "THEME", elementAttr: "ELEMENT_ATTR" }, _visibilityChanged: function() { this.render() }, _setThemeAndRtl: function() { this._themeManager.setTheme(this.option("theme"), this.option(OPTION_RTL_ENABLED)) }, _getRendererOptions: function() { return { rtl: this.option(OPTION_RTL_ENABLED), encodeHtml: this.option("encodeHtml"), animation: this._getAnimationOptions() } }, _setRendererOptions: function() { this._renderer.setOptions(this._getRendererOptions()) }, svg: function() { return this._renderer.svg() }, getSize: function() { var canvas = this._canvas || {}; return { width: canvas.width, height: canvas.height } }, isReady: getFalse, _dataIsReady: getTrue, _resetIsReady: function() { this.isReady = getFalse }, _drawn: function() { var that = this; that.isReady = getFalse; if (that._dataIsReady()) { that._renderer.onEndAnimation(function() { that.isReady = getTrue }) } that._eventTrigger("drawn", {}) } }); helpers.replaceInherit(module.exports); function createEventTrigger(eventsMap, callbackGetter) { var triggers = {}; $.each(eventsMap, function(name, info) { if (info.name) { createEvent(name) } }); var changes; triggerEvent.change = function(name) { var eventInfo = eventsMap[name]; if (eventInfo) { (changes = changes || {})[name] = eventInfo } return !!eventInfo }; triggerEvent.applyChanges = function() { if (changes) { $.each(changes, function(name, eventInfo) { createEvent(eventInfo.newName || name) }); changes = null } }; triggerEvent.dispose = function() { eventsMap = callbackGetter = triggers = null }; return triggerEvent; function createEvent(name) { var eventInfo = eventsMap[name]; triggers[eventInfo.name] = callbackGetter(name) } function triggerEvent(name, arg, complete) { triggers[name](arg); complete && complete() } } module.exports.DEBUG_createEventTrigger = createEventTrigger; module.exports.DEBUG_createIncidentOccurred = createIncidentOccurred; module.exports.DEBUG_stub_createIncidentOccurred = function(stub) { createIncidentOccurred = stub }; module.exports.DEBUG_restore_createIncidentOccurred = function() { createIncidentOccurred = module.exports.DEBUG_createIncidentOccurred }; module.exports.DEBUG_createResizeHandler = createResizeHandler }, /*!********************************!*\ !*** ./js/viz/core/helpers.js ***! \********************************/ function(module, exports, __webpack_require__) { var _extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend; function Flags() { this.reset() } Flags.prototype = { constructor: Flags, add: function(codes) { var i, ii = codes.length, flags = this._flags; for (i = 0; i < ii; ++i) { flags[codes[i]] = 1 } this._k += ii }, has: function(code) { return this._flags[code] > 0 }, count: function() { return this._k }, reset: function() { this._flags = {}; this._k = 0 } }; function combineMaps(baseMap, thisMap) { return baseMap !== thisMap ? _extend({}, baseMap, thisMap) : _extend({}, baseMap) } function combineLists(baseList, thisList) { return baseList !== thisList ? baseList.concat(thisList) : baseList.slice() } function buildTotalChanges(proto) { proto._totalChangesOrder = proto._optionChangesOrder.concat(proto._layoutChangesOrder, proto._customChangesOrder) } function addChange(settings) { var proto = this.prototype, code = settings.code; proto["_change_" + code] = settings.handler; if (settings.isThemeDependent) { proto._themeDependentChanges.push(code) } if (settings.option) { proto._optionChangesMap[settings.option] = code }(settings.isOptionChange ? proto._optionChangesOrder : proto._customChangesOrder).push(code); buildTotalChanges(proto) } function addPlugin(plugin) { this.prototype._plugins.push(plugin); if (plugin.members) { _extend(this.prototype, plugin.members) } if (plugin.customize) { plugin.customize(this) } } exports.replaceInherit = function(widget) { var _inherit = widget.inherit; widget.inherit = function() { var proto = this.prototype, plugins = proto._plugins, eventsMap = proto._eventsMap, initialChanges = proto._initialChanges, themeDependentChanges = proto._themeDependentChanges, optionChangesMap = proto._optionChangesMap, optionChangesOrder = proto._optionChangesOrder, layoutChangesOrder = proto._layoutChangesOrder, customChangesOrder = proto._customChangesOrder, result = _inherit.apply(this, arguments); proto = result.prototype; proto._plugins = combineLists(plugins, proto._plugins); proto._eventsMap = combineMaps(eventsMap, proto._eventsMap); proto._initialChanges = combineLists(initialChanges, proto._initialChanges); proto._themeDependentChanges = combineLists(themeDependentChanges, proto._themeDependentChanges); proto._optionChangesMap = combineMaps(optionChangesMap, proto._optionChangesMap); proto._optionChangesOrder = combineLists(optionChangesOrder, proto._optionChangesOrder); proto._layoutChangesOrder = combineLists(layoutChangesOrder, proto._layoutChangesOrder); proto._customChangesOrder = combineLists(customChangesOrder, proto._customChangesOrder); buildTotalChanges(proto); result.addPlugin = addPlugin; return result }; widget.prototype._plugins = []; widget.addChange = addChange; widget.addPlugin = addPlugin }; exports.changes = function() { return new Flags } }, /*!****************************************!*\ !*** ./js/viz/core/errors_warnings.js ***! \****************************************/ function(module, exports, __webpack_require__) { var errorUtils = __webpack_require__( /*! ../../core/utils/error */ 8), errors = __webpack_require__( /*! ../../core/errors */ 7); module.exports = errorUtils(errors.ERROR_MESSAGES, { E2001: "Invalid data source", E2002: "Axis type and data type are incompatible", E2003: 'The "{0}" data source field contains data of unsupported type', E2004: 'The "{0}" data source field is inconsistent', E2101: "Unknown series type: {0}", E2102: "Ambiguity occurred between two value axes with the same name", E2103: 'The "{0}" option is given an invalid value. Assign a function instead', E2104: "Invalid logarithm base", E2105: 'Invalid value of a "{0}"', E2106: "Invalid visible range", E2202: "Invalid {0} scale value", E2203: "The range you are trying to set is invalid", W2002: "The {0} data field is absent", W2003: "Tick interval is too small", W2101: 'The "{0}" pane does not exist; the last pane is used by default', W2102: 'A value axis with the "{0}" name was created automatically', W2103: "The chart title was hidden due to the container size", W2104: "The legend was hidden due to the container size", W2105: 'The title of the "{0}" axis was hidden due to the container size', W2106: 'The labels of the "{0}" axis were hidden due to the container size', W2107: "The export menu was hidden due to the container size", W2301: "Invalid value range" }) }, /*!*******************************************!*\ !*** ./js/viz/core/renderers/renderer.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../../core/renderer */ 9), jQuery = __webpack_require__( /*! jquery */ 10), commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), getSvgMarkup = __webpack_require__( /*! ../../../core/utils/svg */ 42).getSvgMarkup, doc = document, animation = __webpack_require__( /*! ./animation */ 519), math = Math, mathMin = math.min, mathMax = math.max, mathFloor = math.floor, mathRound = math.round, mathSin = math.sin, mathCos = math.cos, mathAbs = math.abs, mathPI = math.PI, _isDefined = commonUtils.isDefined, vizUtils = __webpack_require__( /*! ../utils */ 509), _normalizeEnum = vizUtils.normalizeEnum, _normalizeBBox = vizUtils.normalizeBBox, _rotateBBox = vizUtils.rotateBBox, PI_DIV_180 = mathPI / 180, _parseInt = parseInt, SHARPING_CORRECTION = .5, ARC_COORD_PREC = 5; var pxAddingExceptions = { "column-count": true, "fill-opacity": true, "flex-grow": true, "flex-shrink": true, "font-weight": true, "line-height": true, opacity: true, order: true, orphans: true, widows: true, "z-index": true, zoom: true }; var KEY_TEXT = "text", KEY_STROKE = "stroke", KEY_STROKE_WIDTH = "stroke-width", KEY_STROKE_OPACITY = "stroke-opacity", KEY_FONT_SIZE = "font-size", KEY_FONT_STYLE = "font-style", KEY_FONT_WEIGHT = "font-weight", KEY_TEXT_DECORATION = "text-decoration", NONE = "none"; var objectCreate = function() { if (!Object.create) { return function(proto) { var F = function() {}; F.prototype = proto; return new F } } else { return function(proto) { return Object.create(proto) } } }(); var DEFAULTS = { scaleX: 1, scaleY: 1 }; var backupContainer = doc.createElement("div"), backupCounter = 0; backupContainer.style.left = "-9999px"; backupContainer.style.position = "absolute"; function backupRoot(root) { if (0 === backupCounter) { doc.body.appendChild(backupContainer) }++backupCounter; root.append({ element: backupContainer }) } function restoreRoot(root, container) { root.append({ element: container }); --backupCounter; if (0 === backupCounter) { doc.body.removeChild(backupContainer) } } var getNextDefsSvgId = function() { var numDefsSvgElements = 1; return function() { return "DevExpress_" + numDefsSvgElements++ } }(); function isObjectArgument(value) { return value && "string" !== typeof value } function createElement(tagName) { return doc.createElementNS("http://www.w3.org/2000/svg", tagName) } function getFuncIri(id, pathModified) { return null !== id ? "url(" + (pathModified ? window.location.href.split("#")[0] : "") + "#" + id + ")" : id } function extend(target, source) { var key; for (key in source) { target[key] = source[key] } return target } function roundValue(value, exp) { value = value.toString().split("e"); value = mathRound(+(value[0] + "e" + (value[1] ? +value[1] + exp : exp))); value = value.toString().split("e"); return +(value[0] + "e" + (value[1] ? +value[1] - exp : -exp)) } var preserveAspectRatioMap = { full: NONE, lefttop: "xMinYMin", leftcenter: "xMinYMid", leftbottom: "xMinYMax", centertop: "xMidYMin", center: "xMidYMid", centerbottom: "xMidYMax", righttop: "xMaxYMin", rightcenter: "xMaxYMid", rightbottom: "xMaxYMax" }; function normalizeArcParams(x, y, innerR, outerR, startAngle, endAngle) { var isCircle, noArc = true, angleDiff = roundValue(endAngle, 3) - roundValue(startAngle, 3); if (angleDiff) { if (mathAbs(angleDiff) % 360 === 0) { startAngle = 0; endAngle = 360; isCircle = true; endAngle -= .01 } if (startAngle > 360) { startAngle %= 360 } if (endAngle > 360) { endAngle %= 360 } if (startAngle > endAngle) { startAngle -= 360 } noArc = false } startAngle *= PI_DIV_180; endAngle *= PI_DIV_180; return [x, y, mathMin(outerR, innerR), mathMax(outerR, innerR), mathCos(startAngle), mathSin(startAngle), mathCos(endAngle), mathSin(endAngle), isCircle, mathFloor(mathAbs(endAngle - startAngle) / mathPI) % 2 ? "1" : "0", noArc] } var buildArcPath = function(x, y, innerR, outerR, startAngleCos, startAngleSin, endAngleCos, endAngleSin, isCircle, longFlag) { return ["M", (x + outerR * startAngleCos).toFixed(ARC_COORD_PREC), (y - outerR * startAngleSin).toFixed(ARC_COORD_PREC), "A", outerR.toFixed(ARC_COORD_PREC), outerR.toFixed(ARC_COORD_PREC), 0, longFlag, 0, (x + outerR * endAngleCos).toFixed(ARC_COORD_PREC), (y - outerR * endAngleSin).toFixed(ARC_COORD_PREC), isCircle ? "M" : "L", (x + innerR * endAngleCos).toFixed(5), (y - innerR * endAngleSin).toFixed(ARC_COORD_PREC), "A", innerR.toFixed(ARC_COORD_PREC), innerR.toFixed(ARC_COORD_PREC), 0, longFlag, 1, (x + innerR * startAngleCos).toFixed(ARC_COORD_PREC), (y - innerR * startAngleSin).toFixed(ARC_COORD_PREC), "Z"].join(" ") }; function buildPathSegments(points, type) { var list = [ ["M", 0, 0] ]; switch (type) { case "line": list = buildLineSegments(points); break; case "area": list = buildLineSegments(points, true); break; case "bezier": list = buildCurveSegments(points); break; case "bezierarea": list = buildCurveSegments(points, true) } return list } function buildLineSegments(points, close) { return buildSegments(points, buildSimpleLineSegment, close) } function buildCurveSegments(points, close) { return buildSegments(points, buildSimpleCurveSegment, close) } function buildSegments(points, buildSimpleSegment, close) { var i, ii, list = []; if (points[0] && points[0].length) { for (i = 0, ii = points.length; i < ii; ++i) { buildSimpleSegment(points[i], close, list) } } else { buildSimpleSegment(points, close, list) } return list } function buildSimpleLineSegment(points, close, list) { var i = 0, k0 = list.length, k = k0, ii = (points || []).length; if (ii) { if (void 0 !== points[0].x) { for (; i < ii;) { list[k++] = ["L", points[i].x, points[i++].y] } } else { for (; i < ii;) { list[k++] = ["L", points[i++], points[i++]] } } list[k0][0] = "M" } else { list[k] = ["M", 0, 0] } close && list.push(["Z"]); return list } function buildSimpleCurveSegment(points, close, list) { var i, k = list.length, ii = (points || []).length; if (ii) { if (void 0 !== points[0].x) { list[k++] = ["M", points[0].x, points[0].y]; for (i = 1; i < ii;) { list[k++] = ["C", points[i].x, points[i++].y, points[i].x, points[i++].y, points[i].x, points[i++].y] } } else { list[k++] = ["M", points[0], points[1]]; for (i = 2; i < ii;) { list[k++] = ["C", points[i++], points[i++], points[i++], points[i++], points[i++], points[i++]] } } } else { list[k] = ["M", 0, 0] } close && list.push(["Z"]); return list } function combinePathParam(segments) { var i, segment, j, jj, d = [], k = 0, ii = segments.length; for (i = 0; i < ii; ++i) { segment = segments[i]; for (j = 0, jj = segment.length; j < jj; ++j) { d[k++] = segment[j] } } return d.join(" ") } function compensateSegments(oldSegments, newSegments, type) { var i, originalNewSegments, oldLength = oldSegments.length, newLength = newSegments.length, makeEqualSegments = type.indexOf("area") !== -1 ? makeEqualAreaSegments : makeEqualLineSegments; if (0 === oldLength) { for (i = 0; i < newLength; i++) { oldSegments.push(newSegments[i].slice(0)) } } else { if (oldLength < newLength) { makeEqualSegments(oldSegments, newSegments, type) } else { if (oldLength > newLength) { originalNewSegments = newSegments.slice(0); makeEqualSegments(newSegments, oldSegments, type) } } } return originalNewSegments } function prepareConstSegment(constSeg, type) { var x = constSeg[constSeg.length - 2], y = constSeg[constSeg.length - 1]; switch (type) { case "line": case "area": constSeg[0] = "L"; break; case "bezier": case "bezierarea": constSeg[0] = "C"; constSeg[1] = constSeg[3] = constSeg[5] = x; constSeg[2] = constSeg[4] = constSeg[6] = y } } function makeEqualLineSegments(short, long, type) { var constSeg = short[short.length - 1].slice(), i = short.length; prepareConstSegment(constSeg, type); for (; i < long.length; i++) { short[i] = constSeg.slice(0) } } function makeEqualAreaSegments(short, long, type) { var i, head, constsSeg1, constsSeg2, shortLength = short.length, longLength = long.length; if ((shortLength - 1) % 2 === 0 && (longLength - 1) % 2 === 0) { i = (shortLength - 1) / 2 - 1; head = short.slice(0, i + 1); constsSeg1 = head[head.length - 1].slice(0); constsSeg2 = short.slice(i + 1)[0].slice(0); prepareConstSegment(constsSeg1, type); prepareConstSegment(constsSeg2, type); for (var j = i; j < (longLength - 1) / 2 - 1; j++) { short.splice(j + 1, 0, constsSeg1); short.splice(j + 3, 0, constsSeg2) } } } function baseCss(that, styles) { var key, value, elemStyles = that._styles, str = ""; styles = styles || {}; for (key in styles) { value = styles[key]; if (_isDefined(value)) { if ("number" === typeof value && !pxAddingExceptions[key]) { value += "px" } elemStyles[key] = "" !== value ? value : null } } for (key in elemStyles) { value = elemStyles[key]; if (value) { str += key + ":" + value + ";" } } str && that.element.setAttribute("style", str); return that } function fixFuncIri(wrapper, attribute) { var element = wrapper.element, id = wrapper.attr(attribute); if (id && id.indexOf("DevExpress") !== -1) { element.removeAttribute(attribute); element.setAttribute(attribute, getFuncIri(id, wrapper.renderer.pathModified)) } } function baseAttr(that, attrs) { attrs = attrs || {}; var key, value, hasTransformations, recalculateDashStyle, sw, i, settings = that._settings, attributes = {}, elem = that.element, renderer = that.renderer, rtl = renderer.rtl; if (!isObjectArgument(attrs)) { if (attrs in settings) { return settings[attrs] } if (attrs in DEFAULTS) { return DEFAULTS[attrs] } return 0 } extend(attributes, attrs); for (key in attributes) { value = attributes[key]; if (void 0 === value) { continue } settings[key] = value; if ("align" === key) { key = "text-anchor"; value = { left: rtl ? "end" : "start", center: "middle", right: rtl ? "start" : "end" }[value] || null } else { if ("dashStyle" === key) { recalculateDashStyle = true; continue } else { if (key === KEY_STROKE_WIDTH) { recalculateDashStyle = true } else { if (value && ("fill" === key || "clip-path" === key || "filter" === key) && value.indexOf("DevExpress") !== -1) { that._addFixIRICallback(); value = getFuncIri(value, renderer.pathModified) } else { if (/^(translate(X|Y)|rotate[XY]?|scale(X|Y)|sharp)$/i.test(key)) { hasTransformations = true; continue } else { if (/^(x|y|d)$/i.test(key)) { hasTransformations = true } } } } } } if (null === value) { elem.removeAttribute(key) } else { elem.setAttribute(key, value) } } if (recalculateDashStyle && "dashStyle" in settings) { value = settings.dashStyle; sw = ("_originalSW" in that ? that._originalSW : settings[KEY_STROKE_WIDTH]) || 1; key = "stroke-dasharray"; value = null === value ? "" : _normalizeEnum(value); if ("" === value || "solid" === value || value === NONE) { that.element.removeAttribute(key) } else { value = value.replace(/longdash/g, "8,3,").replace(/dash/g, "4,3,").replace(/dot/g, "1,3,").replace(/,$/, "").split(","); i = value.length; while (i--) { value[i] = _parseInt(value[i]) * sw } that.element.setAttribute(key, value.join(",")) } } if (hasTransformations) { that._applyTransformation() } return that } function pathAttr(attrs) { var segments, that = this; if (isObjectArgument(attrs)) { attrs = extend({}, attrs); segments = attrs.segments; if ("points" in attrs) { segments = buildPathSegments(attrs.points, that.type); delete attrs.points } if (segments) { attrs.d = combinePathParam(segments); that.segments = segments; delete attrs.segments } } return baseAttr(that, attrs) } function arcAttr(attrs) { var x, y, innerRadius, outerRadius, startAngle, endAngle, settings = this._settings; if (isObjectArgument(attrs)) { attrs = extend({}, attrs); if ("x" in attrs || "y" in attrs || "innerRadius" in attrs || "outerRadius" in attrs || "startAngle" in attrs || "endAngle" in attrs) { settings.x = x = "x" in attrs ? attrs.x : settings.x; delete attrs.x; settings.y = y = "y" in attrs ? attrs.y : settings.y; delete attrs.y; settings.innerRadius = innerRadius = "innerRadius" in attrs ? attrs.innerRadius : settings.innerRadius; delete attrs.innerRadius; settings.outerRadius = outerRadius = "outerRadius" in attrs ? attrs.outerRadius : settings.outerRadius; delete attrs.outerRadius; settings.startAngle = startAngle = "startAngle" in attrs ? attrs.startAngle : settings.startAngle; delete attrs.startAngle; settings.endAngle = endAngle = "endAngle" in attrs ? attrs.endAngle : settings.endAngle; delete attrs.endAngle; attrs.d = buildArcPath.apply(null, normalizeArcParams(x, y, innerRadius, outerRadius, startAngle, endAngle)) } } return baseAttr(this, attrs) } function rectAttr(attrs) { var x, y, width, height, sw, maxSW, newSW, that = this; if (isObjectArgument(attrs)) { attrs = extend({}, attrs); if (void 0 !== attrs.x || void 0 !== attrs.y || void 0 !== attrs.width || void 0 !== attrs.height || void 0 !== attrs[KEY_STROKE_WIDTH]) { void 0 !== attrs.x ? x = that._originalX = attrs.x : x = that._originalX || 0; void 0 !== attrs.y ? y = that._originalY = attrs.y : y = that._originalY || 0; void 0 !== attrs.width ? width = that._originalWidth = attrs.width : width = that._originalWidth || 0; void 0 !== attrs.height ? height = that._originalHeight = attrs.height : height = that._originalHeight || 0; void 0 !== attrs[KEY_STROKE_WIDTH] ? sw = that._originalSW = attrs[KEY_STROKE_WIDTH] : sw = that._originalSW; maxSW = ~~((width < height ? width : height) / 2); newSW = (sw || 0) < maxSW ? sw || 0 : maxSW; attrs.x = x + newSW / 2; attrs.y = y + newSW / 2; attrs.width = width - newSW; attrs.height = height - newSW; ((sw || 0) !== newSW || !(0 === newSW && void 0 === sw)) && (attrs[KEY_STROKE_WIDTH] = newSW) } if ("sharp" in attrs) { delete attrs.sharp } } return baseAttr(that, attrs) } function textAttr(attrs) { var settings, isResetRequired, wasStroked, isStroked, that = this; if (!isObjectArgument(attrs)) { return baseAttr(that, attrs) } attrs = extend({}, attrs); settings = that._settings; wasStroked = _isDefined(settings[KEY_STROKE]) && _isDefined(settings[KEY_STROKE_WIDTH]); if (void 0 !== attrs[KEY_TEXT]) { settings[KEY_TEXT] = attrs[KEY_TEXT]; delete attrs[KEY_TEXT]; isResetRequired = true } if (void 0 !== attrs[KEY_STROKE]) { settings[KEY_STROKE] = attrs[KEY_STROKE]; delete attrs[KEY_STROKE] } if (void 0 !== attrs[KEY_STROKE_WIDTH]) { settings[KEY_STROKE_WIDTH] = attrs[KEY_STROKE_WIDTH]; delete attrs[KEY_STROKE_WIDTH] } if (void 0 !== attrs[KEY_STROKE_OPACITY]) { settings[KEY_STROKE_OPACITY] = attrs[KEY_STROKE_OPACITY]; delete attrs[KEY_STROKE_OPACITY] } isStroked = _isDefined(settings[KEY_STROKE]) && _isDefined(settings[KEY_STROKE_WIDTH]); baseAttr(that, attrs); isResetRequired = isResetRequired || isStroked !== wasStroked && settings[KEY_TEXT]; if (isResetRequired) { createTextNodes(that, settings.text, isStroked); that._hasEllipsis = false } if (isResetRequired || void 0 !== attrs.x || void 0 !== attrs.y) { locateTextNodes(that) } if (isStroked) { strokeTextNodes(that) } return that } function textCss(styles) { styles = styles || {}; baseCss(this, styles); if (KEY_FONT_SIZE in styles) { locateTextNodes(this) } return this } function orderHtmlTree(list, line, node, parentStyle, parentClassName) { var style, realStyle, i, ii, nodes; if (void 0 !== node.wholeText) { list.push({ value: node.wholeText, style: parentStyle, className: parentClassName, line: line, height: parentStyle[KEY_FONT_SIZE] || 0 }) } else { if ("BR" === node.tagName) { ++line } else { if (node.nodeType === Node.ELEMENT_NODE) { extend(style = {}, parentStyle); switch (node.tagName) { case "B": case "STRONG": style[KEY_FONT_WEIGHT] = "bold"; break; case "I": case "EM": style[KEY_FONT_STYLE] = "italic"; break; case "U": style[KEY_TEXT_DECORATION] = "underline" } realStyle = node.style; realStyle.color && (style.fill = realStyle.color); realStyle.fontSize && (style[KEY_FONT_SIZE] = _parseInt(realStyle.fontSize, 10)); realStyle.fontStyle && (style[KEY_FONT_STYLE] = realStyle.fontStyle); realStyle.fontWeight && (style[KEY_FONT_WEIGHT] = realStyle.fontWeight); realStyle.textDecoration && (style[KEY_TEXT_DECORATION] = realStyle.textDecoration); for (i = 0, nodes = node.childNodes, ii = nodes.length; i < ii; ++i) { line = orderHtmlTree(list, line, nodes[i], style, node.className || parentClassName) } } } } return line } function adjustLineHeights(items) { var i, ii, item, currentItem = items[0]; for (i = 1, ii = items.length; i < ii; ++i) { item = items[i]; if (item.line === currentItem.line) { currentItem.height = mathMax(currentItem.height, item.height); currentItem.inherits = currentItem.inherits || 0 === item.height; item.height = NaN } else { currentItem = item } } } function removeExtraAttrs(html) { var findTagAttrs = /(?:<[a-z0-9])+(?:[\s\S]*?>)/gi, findStyleAttrWithValue = /(\S*\s*)=\s*(["'])(?:(?!\2).)*\2\s?/gi; return html.replace(findTagAttrs, function(allTagAttrs) { return allTagAttrs.replace(findStyleAttrWithValue, function(currentAttr, attrName) { var lowerCaseAttrName = attrName.toLowerCase(); return "style" === lowerCaseAttrName || "class" === lowerCaseAttrName ? currentAttr : "" }) }) } function parseHTML(text) { var items = [], div = doc.createElement("div"); div.innerHTML = text.replace(/\r/g, "").replace(/\n/g, "<br/>"); orderHtmlTree(items, 0, div, {}, ""); adjustLineHeights(items); return items } function parseMultiline(text) { var texts = text.replace(/\r/g, "").split("\n"), i = 0, items = []; for (; i < texts.length; i++) { items.push({ value: texts[i], height: 0 }) } return items } function createTspans(items, element, fieldName) { var i, ii, item; for (i = 0, ii = items.length; i < ii; ++i) { item = items[i]; item[fieldName] = createElement("tspan"); item[fieldName].appendChild(doc.createTextNode(item.value)); item.style && baseCss({ element: item[fieldName], _styles: {} }, item.style); item.className && item[fieldName].setAttribute("class", item.className); element.appendChild(item[fieldName]) } } function applyEllipsis(maxWidth) { var lines, i, ii, lineParts, j, jj, text, ellipsis, ellipsisWidth, that = this, hasEllipsis = false; if (that._hasEllipsis) { that.attr({ text: that._settings.text }) } ellipsis = that.renderer.text("...").attr(that._styles).append(that.renderer.root); ellipsisWidth = ellipsis.getBBox().width; if (that._getElementBBox().width > maxWidth) { if (maxWidth - ellipsisWidth < 0) { maxWidth = 0 } else { maxWidth -= ellipsisWidth } lines = prepareLines(that.element, that._texts, maxWidth); for (i = 0, ii = lines.length; i < ii; ++i) { lineParts = lines[i].parts; if (1 === lines[i].commonLength) { continue } for (j = 0, jj = lineParts.length; j < jj; ++j) { text = lineParts[j]; if (_isDefined(text.endIndex)) { setNewText(text, text.endIndex); hasEllipsis = true } else { if (text.startBox > maxWidth) { removeTextSpan(text) } } } } } ellipsis.remove(); that._hasEllipsis = hasEllipsis; return hasEllipsis } function getIndexForEllipsis(text, maxWidth, startBox, endBox) { var k, kk; if (startBox <= maxWidth && endBox > maxWidth) { for (k = 1, kk = text.value.length; k <= kk; ++k) { if (startBox + text.tspan.getSubStringLength(0, k) > maxWidth) { return k - 1 } } } } function prepareLines(element, texts, maxWidth) { var i, ii, text, startBox, endBox, lines = []; if (texts) { for (i = 0, ii = texts.length; i < ii; ++i) { text = texts[i]; if (!lines[text.line]) { text.startBox = startBox = 0; lines.push({ commonLength: text.value.length, parts: [text] }) } else { text.startBox = startBox; lines[text.line].parts.push(text); lines[text.line].commonLength += text.value.length } endBox = startBox + text.tspan.getSubStringLength(0, text.value.length); text.endIndex = getIndexForEllipsis(text, maxWidth, startBox, endBox); startBox = endBox } } else { text = { value: element.textContent, tspan: element }; text.startBox = startBox = 0; endBox = text.value.length ? startBox + text.tspan.getSubStringLength(0, text.value.length) : 0; text.endIndex = getIndexForEllipsis(text, maxWidth, startBox, endBox); lines = [{ commonLength: element.textContent.length, parts: [text] }] } return lines } function setNewText(text, index) { var newText = text.value.substr(0, index) + "..."; text.tspan.textContent = newText; text.stroke && (text.stroke.textContent = newText) } function removeTextSpan(text) { text.tspan.parentNode.removeChild(text.tspan); text.stroke && text.stroke.parentNode.removeChild(text.stroke) } function createTextNodes(wrapper, text, isStroked) { var items, parsedHtml; wrapper._texts = null; wrapper.clear(); if (null === text) { return } text = "" + text; if (!wrapper.renderer.encodeHtml && (/<[a-z][\s\S]*>/i.test(text) || text.indexOf("&") !== -1)) { parsedHtml = removeExtraAttrs(text); items = parseHTML(parsedHtml); wrapper.DEBUG_parsedHtml = parsedHtml } else { if (text.indexOf("\n") !== -1) { items = parseMultiline(text) } else { if (isStroked) { items = [{ value: text, height: 0 }] } } } if (items) { if (items.length) { wrapper._texts = items; if (isStroked) { createTspans(items, wrapper.element, KEY_STROKE) } createTspans(items, wrapper.element, "tspan") } } else { wrapper.element.appendChild(doc.createTextNode(text)) } } function setTextNodeAttribute(item, name, value) { item.tspan.setAttribute(name, value); item.stroke && item.stroke.setAttribute(name, value) } function locateTextNodes(wrapper) { if (!wrapper._texts) { return } var i, ii, items = wrapper._texts, x = wrapper._settings.x, lineHeight = _parseInt(wrapper._styles[KEY_FONT_SIZE], 10) || 12, item = items[0]; setTextNodeAttribute(item, "x", x); setTextNodeAttribute(item, "y", wrapper._settings.y); for (i = 1, ii = items.length; i < ii; ++i) { item = items[i]; if (item.height >= 0) { setTextNodeAttribute(item, "x", x); setTextNodeAttribute(item, "dy", item.inherits ? mathMax(item.height, lineHeight) : item.height || lineHeight) } } } function strokeTextNodes(wrapper) { if (!wrapper._texts) { return } var tspan, i, ii, items = wrapper._texts, stroke = wrapper._settings[KEY_STROKE], strokeWidth = wrapper._settings[KEY_STROKE_WIDTH], strokeOpacity = wrapper._settings[KEY_STROKE_OPACITY] || 1; for (i = 0, ii = items.length; i < ii; ++i) { tspan = items[i].stroke; tspan.setAttribute(KEY_STROKE, stroke); tspan.setAttribute(KEY_STROKE_WIDTH, strokeWidth); tspan.setAttribute(KEY_STROKE_OPACITY, strokeOpacity); tspan.setAttribute("stroke-linejoin", "round") } } function baseAnimate(that, params, options, complete) { options = options || {}; var key, value, renderer = that.renderer, settings = that._settings, animationParams = {}; var defaults = { translateX: 0, translateY: 0, scaleX: 1, scaleY: 1, rotate: 0, rotateX: 0, rotateY: 0 }; if (complete) { options.complete = complete } if (renderer.animationEnabled()) { for (key in params) { value = params[key]; if (/^(translate(X|Y)|rotate[XY]?|scale(X|Y))$/i.test(key)) { animationParams.transform = animationParams.transform || { from: {}, to: {} }; animationParams.transform.from[key] = key in settings ? Number(settings[key].toFixed(3)) : defaults[key]; animationParams.transform.to[key] = value } else { if ("arc" === key || "segments" === key) { animationParams[key] = value } else { animationParams[key] = { from: key in settings ? settings[key] : parseFloat(that.element.getAttribute(key) || 0), to: value } } } } renderer.animateElement(that, animationParams, extend(extend({}, renderer._animation), options)) } else { options.step && options.step.call(that, 1, 1); options.complete && options.complete.call(that); that.attr(params) } return that } function pathAnimate(params, options, complete) { var newSegments, endSegments, that = this, curSegments = that.segments || []; if (that.renderer.animationEnabled() && "points" in params) { newSegments = buildPathSegments(params.points, that.type); endSegments = compensateSegments(curSegments, newSegments, that.type); params.segments = { from: curSegments, to: newSegments, end: endSegments }; delete params.points } return baseAnimate(that, params, options, complete) } function arcAnimate(params, options, complete) { var that = this, settings = that._settings, arcParams = { from: {}, to: {} }; if (that.renderer.animationEnabled() && ("x" in params || "y" in params || "innerRadius" in params || "outerRadius" in params || "startAngle" in params || "endAngle" in params)) { arcParams.from.x = settings.x || 0; arcParams.from.y = settings.y || 0; arcParams.from.innerRadius = settings.innerRadius || 0; arcParams.from.outerRadius = settings.outerRadius || 0; arcParams.from.startAngle = settings.startAngle || 0; arcParams.from.endAngle = settings.endAngle || 0; arcParams.to.x = "x" in params ? params.x : settings.x; delete params.x; arcParams.to.y = "y" in params ? params.y : settings.y; delete params.y; arcParams.to.innerRadius = "innerRadius" in params ? params.innerRadius : settings.innerRadius; delete params.innerRadius; arcParams.to.outerRadius = "outerRadius" in params ? params.outerRadius : settings.outerRadius; delete params.outerRadius; arcParams.to.startAngle = "startAngle" in params ? params.startAngle : settings.startAngle; delete params.startAngle; arcParams.to.endAngle = "endAngle" in params ? params.endAngle : settings.endAngle; delete params.endAngle; params.arc = arcParams } return baseAnimate(that, params, options, complete) } exports.DEBUG_set_getNextDefsSvgId = function(newFunction) { getNextDefsSvgId = newFunction }; exports.DEBUG_removeBackupContainer = function() { if (backupCounter) { backupCounter = 0; doc.body.removeChild(backupContainer) } }; function buildLink(target, parameters) { var obj = { is: false, name: parameters.name || parameters, after: parameters.after }; if (target) { obj.to = target } else { obj.virtual = true } return obj } function SvgElement(renderer, tagName, type) { var that = this; that.renderer = renderer; that.element = createElement(tagName); that._settings = {}; that._styles = {}; if ("path" === tagName) { that.type = type || "line" } } exports.SvgElement = SvgElement; SvgElement.prototype = { constructor: SvgElement, _getJQElement: function() { return this._$element || (this._$element = jQuery(this.element)) }, _addFixIRICallback: function() { var that = this; that._fixFuncIri = function() { fixFuncIri(that, "fill"); fixFuncIri(that, "clip-path"); fixFuncIri(that, "filter") }; fixFuncIriCallbacks.add(that._fixFuncIri); that._addFixIRICallback = function() {} }, dispose: function() { fixFuncIriCallbacks.remove(this._fixFuncIri); this._getJQElement().remove(); return this }, append: function(parent) { (parent || this.renderer.root).element.appendChild(this.element); return this }, remove: function() { var element = this.element; element.parentNode && element.parentNode.removeChild(element); return this }, enableLinks: function() { this._links = []; return this }, checkLinks: function() { var i, count = 0, links = this._links, ii = links.length; for (i = 0; i < ii; ++i) { if (!links[i]._link.virtual) { ++count } } if (count > 0) { throw new Error("There are non disposed links!") } }, virtualLink: function(parameters) { linkItem({ _link: buildLink(null, parameters) }, this); return this }, linkAfter: function(name) { this._linkAfter = name; return this }, linkOn: function(target, parameters) { this._link = buildLink(target, parameters); linkItem(this, target); return this }, linkOff: function() { unlinkItem(this); this._link = null; return this }, linkAppend: function() { var i, next, link = this._link, items = link.to._links; for (i = link.i + 1; (next = items[i]) && !next._link.is; ++i) {} this._insert(link.to, next); link.is = true; return this }, _insert: function(parent, next) { parent.element.insertBefore(this.element, next ? next.element : null) }, linkRemove: function() { this.remove(); this._link.is = false; return this }, clear: function() { this._getJQElement().empty(); return this }, toBackground: function() { var elem = this.element, parent = elem.parentNode; parent && parent.insertBefore(elem, parent.firstChild); return this }, toForeground: function() { var elem = this.element, parent = elem.parentNode; parent && parent.appendChild(elem); return this }, attr: function(attrs) { return baseAttr(this, attrs) }, smartAttr: function(attrs) { var that = this; if (attrs.hatching) { attrs = extend({}, attrs); attrs.fill = that._hatching = that.renderer.lockHatching(attrs.fill, attrs.hatching, that._hatching); delete attrs.hatching } else { if (that._hatching) { that.renderer.releaseHatching(that._hatching); that._hatching = null } } return that.attr(attrs) }, css: function(styles) { return baseCss(this, styles) }, animate: function(params, options, complete) { return baseAnimate(this, params, options, complete) }, sharp: function(pos) { return this.attr({ sharp: pos || true }) }, _applyTransformation: function() { var scaleXDefined, scaleYDefined, rotateX, rotateY, tr = this._settings, transformations = [], sharpMode = tr.sharp, strokeOdd = tr[KEY_STROKE_WIDTH] % 2, correctionX = strokeOdd && ("h" === sharpMode || true === sharpMode) ? SHARPING_CORRECTION : 0, correctionY = strokeOdd && ("v" === sharpMode || true === sharpMode) ? SHARPING_CORRECTION : 0; transformations.push("translate(" + ((tr.translateX || 0) + correctionX) + "," + ((tr.translateY || 0) + correctionY) + ")"); if (tr.rotate) { if ("rotateX" in tr) { rotateX = tr.rotateX } else { rotateX = tr.x } if ("rotateY" in tr) { rotateY = tr.rotateY } else { rotateY = tr.y } transformations.push("rotate(" + tr.rotate + "," + (rotateX || 0) + "," + (rotateY || 0) + ")") } scaleXDefined = _isDefined(tr.scaleX); scaleYDefined = _isDefined(tr.scaleY); if (scaleXDefined || scaleYDefined) { transformations.push("scale(" + (scaleXDefined ? tr.scaleX : 1) + "," + (scaleYDefined ? tr.scaleY : 1) + ")") } if (transformations.length) { this.element.setAttribute("transform", transformations.join(" ")) } }, move: function(x, y, animate, animOptions) { var obj = {}; _isDefined(x) && (obj.translateX = x); _isDefined(y) && (obj.translateY = y); if (!animate) { this.attr(obj) } else { this.animate(obj, animOptions) } return this }, rotate: function(angle, x, y, animate, animOptions) { var obj = { rotate: angle || 0 }; _isDefined(x) && (obj.rotateX = x); _isDefined(y) && (obj.rotateY = y); if (!animate) { this.attr(obj) } else { this.animate(obj, animOptions) } return this }, _getElementBBox: function() { var bBox, elem = this.element; try { bBox = elem.getBBox && elem.getBBox() } catch (e) {} return bBox || { x: 0, y: 0, width: elem.offsetWidth || 0, height: elem.offsetHeight || 0 } }, getBBox: function() { var transformation = this._settings, bBox = this._getElementBBox(); if (transformation.rotate) { bBox = _rotateBBox(bBox, [("rotateX" in transformation ? transformation.rotateX : transformation.x) || 0, ("rotateY" in transformation ? transformation.rotateY : transformation.y) || 0], -transformation.rotate) } else { bBox = _normalizeBBox(bBox) } return bBox }, markup: function() { return getSvgMarkup(this.element) }, getOffset: function() { return this._getJQElement().offset() }, stopAnimation: function(disableComplete) { var animation = this.animation; animation && animation.stop(disableComplete); return this }, setTitle: function(text) { var titleElem = createElement("title"); titleElem.textContent = text || ""; this.element.appendChild(titleElem) }, data: function(obj, val) { var key, elem = this.element; if (void 0 !== val) { elem[obj] = val } else { for (key in obj) { elem[key] = obj[key] } } return this }, on: function() { jQuery.fn.on.apply(this._getJQElement(), arguments); return this }, off: function() { jQuery.fn.off.apply(this._getJQElement(), arguments); return this }, trigger: function() { jQuery.fn.trigger.apply(this._getJQElement(), arguments); return this } }; function PathSvgElement(renderer, type) { SvgElement.call(this, renderer, "path", type) } exports.PathSvgElement = PathSvgElement; PathSvgElement.prototype = objectCreate(SvgElement.prototype); extend(PathSvgElement.prototype, { constructor: PathSvgElement, attr: pathAttr, animate: pathAnimate }); function ArcSvgElement(renderer) { SvgElement.call(this, renderer, "path", "arc") } exports.ArcSvgElement = ArcSvgElement; ArcSvgElement.prototype = objectCreate(SvgElement.prototype); extend(ArcSvgElement.prototype, { constructor: ArcSvgElement, attr: arcAttr, animate: arcAnimate }); function RectSvgElement(renderer) { SvgElement.call(this, renderer, "rect") } exports.RectSvgElement = RectSvgElement; RectSvgElement.prototype = objectCreate(SvgElement.prototype); extend(RectSvgElement.prototype, { constructor: RectSvgElement, attr: rectAttr }); function TextSvgElement(renderer) { SvgElement.call(this, renderer, "text") } exports.TextSvgElement = TextSvgElement; TextSvgElement.prototype = objectCreate(SvgElement.prototype); extend(TextSvgElement.prototype, { constructor: TextSvgElement, attr: textAttr, css: textCss, applyEllipsis: applyEllipsis }); function updateIndexes(items, k) { var i, item; for (i = k; !!(item = items[i]); ++i) { item._link.i = i } } function linkItem(target, container) { var i, item, items = container._links, key = target._link.after = target._link.after || container._linkAfter; if (key) { for (i = 0; (item = items[i]) && item._link.name !== key; ++i) {} if (item) { for (++i; (item = items[i]) && item._link.after === key; ++i) {} } } else { i = items.length } items.splice(i, 0, target); updateIndexes(items, i) } function unlinkItem(target) { var i, items = target._link.to._links; for (i = 0; items[i] !== target; ++i) {} items.splice(i, 1); updateIndexes(items, i) } function Renderer(options) { var that = this; that.root = that._createElement("svg", { xmlns: "http://www.w3.org/2000/svg", "xmlns:xlink": "http://www.w3.org/1999/xlink", version: "1.1", fill: NONE, stroke: NONE, "stroke-width": 0 }).attr({ "class": options.cssClass }).css({ "line-height": "normal", "-ms-user-select": NONE, "-moz-user-select": NONE, "-webkit-user-select": NONE, "-webkit-tap-highlight-color": "rgba(0, 0, 0, 0)", display: "block", overflow: "hidden" }); that._init(); that.pathModified = !!options.pathModified; that._$container = $(options.container); that.root.append({ element: options.container }); that._locker = 0; that._backed = false } exports.Renderer = Renderer; Renderer.prototype = { constructor: Renderer, _init: function() { var that = this; that._defs = that._createElement("defs").append(that.root); that._animationController = new animation.AnimationController(that.root.element); that._animation = { enabled: true, duration: 1e3, easing: "easeOutCubic" } }, setOptions: function(options) { var that = this; that.rtl = !!options.rtl; that.encodeHtml = !!options.encodeHtml; that.updateAnimationOptions(options.animation || {}); that.root.attr({ direction: that.rtl ? "rtl" : "ltr" }); return that }, _createElement: function(tagName, attr, type) { var elem = new exports.SvgElement(this, tagName, type); attr && elem.attr(attr); return elem }, lock: function() { var that = this; if (0 === that._locker) { that._backed = !that._$container.is(":visible"); if (that._backed) { backupRoot(that.root) } }++that._locker; return that }, unlock: function() { var that = this; --that._locker; if (0 === that._locker) { if (that._backed) { restoreRoot(that.root, that._$container[0]) } that._backed = false } return that }, resize: function(width, height) { if (width >= 0 && height >= 0) { this.root.attr({ width: width, height: height }) } return this }, dispose: function() { var key, that = this; that.root.dispose(); that._defs.dispose(); that._animationController.dispose(); for (key in that) { that[key] = null } return that }, animationEnabled: function() { return !!this._animation.enabled }, updateAnimationOptions: function(newOptions) { extend(this._animation, newOptions); return this }, stopAllAnimations: function(lock) { this._animationController[lock ? "lock" : "stop"](); return this }, animateElement: function(element, params, options) { this._animationController.animateElement(element, params, options); return this }, svg: function() { return this.root.markup() }, getRootOffset: function() { return this.root.getOffset() }, onEndAnimation: function(endAnimation) { this._animationController.onEndAnimation(endAnimation) }, rect: function(x, y, width, height) { var elem = new exports.RectSvgElement(this); return elem.attr({ x: x || 0, y: y || 0, width: width || 0, height: height || 0 }) }, simpleRect: function() { return this._createElement("rect") }, circle: function(x, y, r) { return this._createElement("circle", { cx: x || 0, cy: y || 0, r: r || 0 }) }, g: function() { return this._createElement("g") }, image: function(x, y, w, h, href, location) { var image = this._createElement("image", { x: x || 0, y: y || 0, width: w || 0, height: h || 0, preserveAspectRatio: preserveAspectRatioMap[_normalizeEnum(location)] || NONE }); image.element.setAttributeNS("http://www.w3.org/1999/xlink", "href", href || ""); return image }, path: function(points, type) { var elem = new exports.PathSvgElement(this, type); return elem.attr({ points: points || [] }) }, arc: function(x, y, innerRadius, outerRadius, startAngle, endAngle) { var elem = new exports.ArcSvgElement(this); return elem.attr({ x: x || 0, y: y || 0, innerRadius: innerRadius || 0, outerRadius: outerRadius || 0, startAngle: startAngle || 0, endAngle: endAngle || 0 }) }, text: function(text, x, y) { var elem = new exports.TextSvgElement(this); return elem.attr({ text: text, x: x || 0, y: y || 0 }) }, pattern: function(color, hatching, _id) { hatching = hatching || {}; var id, d, pattern, rect, path, that = this, step = hatching.step || 6, stepTo2 = step / 2, stepBy15 = 1.5 * step, direction = _normalizeEnum(hatching.direction); if ("right" !== direction && "left" !== direction) { return { id: color, append: function() { return this }, clear: function() {}, dispose: function() {}, remove: function() {} } } id = _id || getNextDefsSvgId(); d = "right" === direction ? "M " + stepTo2 + " " + -stepTo2 + " L " + -stepTo2 + " " + stepTo2 + " M 0 " + step + " L " + step + " 0 M " + stepBy15 + " " + stepTo2 + " L " + stepTo2 + " " + stepBy15 : "M 0 0 L " + step + " " + step + " M " + -stepTo2 + " " + stepTo2 + " L " + stepTo2 + " " + stepBy15 + " M " + stepTo2 + " " + -stepTo2 + " L " + stepBy15 + " " + stepTo2; pattern = that._createElement("pattern", { id: id, width: step, height: step, patternUnits: "userSpaceOnUse" }).append(that._defs); pattern.id = id; rect = that.rect(0, 0, step, step).attr({ fill: color, opacity: hatching.opacity }).append(pattern); path = new exports.PathSvgElement(this).attr({ d: d, "stroke-width": hatching.width || 1, stroke: color }).append(pattern); pattern.rect = rect; pattern.path = path; return pattern }, clipRect: function(x, y, width, height) { var that = this, id = getNextDefsSvgId(), clipPath = that._createElement("clipPath", { id: id }).append(that._defs), rect = that.rect(x, y, width, height).append(clipPath); rect.id = id; rect.clipPath = clipPath; rect.remove = function() { throw "Not implemented" }; rect.dispose = function() { clipPath.dispose(); clipPath = null; return this }; return rect }, shadowFilter: function(x, y, width, height, offsetX, offsetY, blur, color, opacity) { var that = this, id = getNextDefsSvgId(), filter = that._createElement("filter", { id: id, x: x || 0, y: y || 0, width: width || 0, height: height || 0 }).append(that._defs), gaussianBlur = that._createElement("feGaussianBlur", { "in": "SourceGraphic", result: "gaussianBlurResult", stdDeviation: blur || 0 }).append(filter), offset = that._createElement("feOffset", { "in": "gaussianBlurResult", result: "offsetResult", dx: offsetX || 0, dy: offsetY || 0 }).append(filter), flood = that._createElement("feFlood", { result: "floodResult", "flood-color": color || "", "flood-opacity": opacity }).append(filter), composite = that._createElement("feComposite", { "in": "floodResult", in2: "offsetResult", operator: "in", result: "compositeResult" }).append(filter), finalComposite = that._createElement("feComposite", { "in": "SourceGraphic", in2: "compositeResult", operator: "over" }).append(filter); filter.id = id; filter.gaussianBlur = gaussianBlur; filter.offset = offset; filter.flood = flood; filter.composite = composite; filter.finalComposite = finalComposite; filter.attr = function(attrs) { var that = this, filterAttrs = {}, offsetAttrs = {}, floodAttrs = {}; "x" in attrs && (filterAttrs.x = attrs.x); "y" in attrs && (filterAttrs.y = attrs.y); "width" in attrs && (filterAttrs.width = attrs.width); "height" in attrs && (filterAttrs.height = attrs.height); baseAttr(that, filterAttrs); "blur" in attrs && that.gaussianBlur.attr({ stdDeviation: attrs.blur }); "offsetX" in attrs && (offsetAttrs.dx = attrs.offsetX); "offsetY" in attrs && (offsetAttrs.dy = attrs.offsetY); that.offset.attr(offsetAttrs); "color" in attrs && (floodAttrs["flood-color"] = attrs.color); "opacity" in attrs && (floodAttrs["flood-opacity"] = attrs.opacity); that.flood.attr(floodAttrs); return that }; return filter }, brightFilter: function(type, slope) { var that = this, id = getNextDefsSvgId(), filter = that._createElement("filter", { id: id }).append(that._defs), componentTransferElement = that._createElement("feComponentTransfer").append(filter), attrs = { type: type, slope: slope }; filter.id = id; that._createElement("feFuncR", attrs).append(componentTransferElement); that._createElement("feFuncG", attrs).append(componentTransferElement); that._createElement("feFuncB", attrs).append(componentTransferElement); return filter }, getGrayScaleFilter: function() { if (this._grayScaleFilter) { return this._grayScaleFilter } var that = this, id = getNextDefsSvgId(), filter = that._createElement("filter", { id: id }).append(that._defs); that._createElement("feColorMatrix").attr({ type: "matrix", values: "0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 0.6 0" }).append(filter); filter.id = id; that._grayScaleFilter = filter; return filter }, initHatching: function() { var name, storage = this._hatchingStorage = this._hatchingStorage || { byHash: {}, baseId: getNextDefsSvgId() }, byHash = storage.byHash; for (name in byHash) { byHash[name].pattern.dispose() } storage.byHash = {}; storage.refToHash = {}; storage.nextId = 0 }, lockHatching: function(color, hatching, ref) { var storageItem, pattern, storage = this._hatchingStorage, hash = getHatchingHash(color, hatching); if (storage.refToHash[ref] !== hash) { if (ref) { this.releaseHatching(ref) } storageItem = storage.byHash[hash]; if (!storageItem) { pattern = this.pattern(color, hatching, storage.baseId + "-hatching-" + storage.nextId++); storageItem = storage.byHash[hash] = { pattern: pattern, count: 0 }; storage.refToHash[pattern.id] = hash }++storageItem.count; ref = storageItem.pattern.id } return ref }, releaseHatching: function(ref) { var storage = this._hatchingStorage, hash = storage.refToHash[ref], storageItem = storage.byHash[hash]; if (0 === --storageItem.count) { storageItem.pattern.dispose(); delete storage.byHash[hash]; delete storage.refToHash[ref] } } }; function getHatchingHash(color, hatching) { return "@" + color + "::" + hatching.step + ":" + hatching.width + ":" + hatching.opacity + ":" + hatching.direction } var fixFuncIriCallbacks = function() { var callbacks = []; return { add: function(fn) { callbacks.push(fn) }, remove: function(fn) { callbacks = callbacks.filter(function(el) { return el !== fn }) }, fire: function() { callbacks.forEach(function(fn) { fn() }) } } }(); exports.refreshPaths = function() { fixFuncIriCallbacks.fire() } }, /*!********************************************!*\ !*** ./js/viz/core/renderers/animation.js ***! \********************************************/ function(module, exports, __webpack_require__) { var animationFrame = __webpack_require__( /*! ../../../animation/frame */ 59), noop = function() {}, easingFunctions = { easeOutCubic: function(pos, start, end) { return 1 === pos ? end : (1 - Math.pow(1 - pos, 3)) * (end - start) + +start }, linear: function(pos, start, end) { return 1 === pos ? end : pos * (end - start) + +start } }; exports.easingFunctions = easingFunctions; var animationSvgStep = { segments: function(elem, params, progress, easing, currentParams) { var curSeg, seg, i, j, from = params.from, to = params.to, segments = []; for (i = 0; i < from.length; i++) { curSeg = from[i]; seg = [curSeg[0]]; if (curSeg.length > 1) { for (j = 1; j < curSeg.length; j++) { seg.push(easing(progress, curSeg[j], to[i][j])) } } segments.push(seg) } currentParams.segments = params.end && 1 === progress ? params.end : segments; elem.attr({ segments: segments }) }, arc: function(elem, params, progress, easing) { var from = params.from, to = params.to, current = {}; for (var i in from) { current[i] = easing(progress, from[i], to[i]) } elem.attr(current) }, transform: function(elem, params, progress, easing, currentParams) { var from = params.from, to = params.to, current = {}; for (var i in from) { current[i] = currentParams[i] = easing(progress, from[i], to[i]) } elem.attr(current) }, base: function(elem, params, progress, easing, currentParams, attributeName) { var obj = {}; obj[attributeName] = currentParams[attributeName] = easing(progress, params.from, params.to); elem.attr(obj) }, _: noop, complete: function(element, currentSettings) { element.attr(currentSettings) } }; function step(now) { var attrName, that = this, animateStep = that._animateStep; that._progress = that._calcProgress(now); for (attrName in that.params) { var anim = animateStep[attrName] || animateStep.base; anim(that.element, that.params[attrName], that._progress, that._easing, that._currentParams, attrName) } that.options.step && that.options.step(that._easing(that._progress, 0, 1), that._progress); if (1 === that._progress) { return that.stop() } return true } function delayTick(now) { if (now - this._startTime >= this.delay) { this.tick = step } return true } function start(now) { this._startTime = now; this.tick = this.delay ? delayTick : step; return true } function Animation(element, params, options) { var that = this; that._progress = 0; that.element = element; that.params = params; that.options = options; that.duration = options.partitionDuration ? options.duration * options.partitionDuration : options.duration; that.delay = options.delay && options.duration * options.delay || 0; that._animateStep = options.animateStep || animationSvgStep; that._easing = easingFunctions[options.easing] || easingFunctions.easeOutCubic; that._currentParams = {}; that.tick = start } Animation.prototype = { _calcProgress: function(now) { return Math.min(1, (now - this.delay - this._startTime) / this.duration) }, stop: function(disableComplete) { var that = this, options = that.options, animateStep = that._animateStep; that.stop = that.tick = noop; animateStep.complete && animateStep.complete(that.element, that._currentParams); options.complete && !disableComplete && options.complete() } }; function AnimationController(element) { var that = this; that._animationCount = 0; that._timerId = null; that._animations = {}; that.element = element } exports.AnimationController = AnimationController; AnimationController.prototype = { _loop: function() { var an, that = this, animations = that._animations, activeAnimation = 0, now = (new Date).getTime(), endAnimation = that._endAnimation; for (an in animations) { if (!animations[an].tick(now)) { delete animations[an] } activeAnimation++ } if (0 === activeAnimation) { that.stop(); that._endAnimationTimer = endAnimation && setTimeout(function() { if (0 === that._animationCount) { endAnimation(); that._endAnimation = null } }); return } that._timerId = animationFrame.requestAnimationFrame.call(null, function() { that._loop() }, that.element) }, addAnimation: function(animation) { var that = this; that._animations[that._animationCount++] = animation; clearTimeout(that._endAnimationTimer); if (!that._timerId) { clearTimeout(that._startDelay); that._startDelay = setTimeout(function() { that._timerId = 1; that._loop() }, 0) } }, animateElement: function(elem, params, options) { if (elem && params && options) { elem.animation && elem.animation.stop(); this.addAnimation(elem.animation = new Animation(elem, params, options)) } }, onEndAnimation: function(endAnimation) { this._animationCount ? this._endAnimation = endAnimation : endAnimation() }, dispose: function() { this.stop(); this.element = null }, stop: function() { var that = this; that._animations = {}; that._animationCount = 0; animationFrame.cancelAnimationFrame(that._timerId); clearTimeout(that._startDelay); clearTimeout(that._endAnimationTimer); that._timerId = null }, lock: function() { var an, unstoppable, hasUnstoppableInAnimations, animations = this._animations; for (an in animations) { unstoppable = animations[an].options.unstoppable; hasUnstoppableInAnimations = hasUnstoppableInAnimations || unstoppable; if (!unstoppable) { animations[an].stop(true); delete animations[an] } }!hasUnstoppableInAnimations && this.stop() } }; exports.animationSvgStep = animationSvgStep; exports.Animation = Animation; exports.noop = noop }, /*!*******************************!*\ !*** ./js/viz/core/layout.js ***! \*******************************/ function(module, exports, __webpack_require__) { var _normalizeEnum = __webpack_require__( /*! ./utils */ 509).normalizeEnum, _min = Math.min, _max = Math.max, ALIGN_START = 0, ALIGN_MIDDLE = 1, ALIGN_END = 2, horizontalAlignmentMap = { left: ALIGN_START, center: ALIGN_MIDDLE, right: ALIGN_END }, verticalAlignmentMap = { top: ALIGN_START, center: ALIGN_MIDDLE, bottom: ALIGN_END }, sideMap = { horizontal: 0, vertical: 1 }, slicersMap = {}; slicersMap[ALIGN_START] = function(a, b, size) { return [a, _min(b, a + size)] }; slicersMap[ALIGN_MIDDLE] = function(a, b, size) { return [_max(a, (a + b - size) / 2), _min(b, (a + b + size) / 2)] }; slicersMap[ALIGN_END] = function(a, b, size) { return [_max(a, b - size), b] }; function pickValue(value, map, defaultValue) { var val = _normalizeEnum(value); return val in map ? map[val] : defaultValue } function normalizeLayoutOptions(options) { var side = pickValue(options.side, sideMap, 1), alignment = [pickValue(options.horizontalAlignment, horizontalAlignmentMap, ALIGN_MIDDLE), pickValue(options.verticalAlignment, verticalAlignmentMap, ALIGN_START)]; return { side: side, primary: bringToEdge(alignment[side]), secondary: alignment[1 - side], weak: options.weak } } function bringToEdge(primary) { return primary < 2 ? 0 : 2 } function getConjugateSide(side) { return 1 - side } function getOppositeAlignment(alignment) { return 2 - alignment } function getSlice(alignment, a, b, size) { return slicersMap[alignment](a, b, size) } function getShrink(alignment, size) { return (alignment > 0 ? -1 : 1) * size } function processForward(item, rect) { var side = item.side, size = item.element.measure([rect[2] - rect[0], rect[3] - rect[1]]), isValid = size[side] < rect[2 + side] - rect[side]; if (isValid) { rect[item.primary + side] += getShrink(item.primary, size[side]); item.size = size } return isValid } function processBackward(item, rect) { var primarySide = item.side, secondarySide = getConjugateSide(primarySide), itemRect = [], secondary = getSlice(item.secondary, rect[secondarySide], rect[2 + secondarySide], item.size[secondarySide]); itemRect[primarySide] = itemRect[2 + primarySide] = rect[item.primary + primarySide]; itemRect[item.primary + primarySide] = rect[item.primary + primarySide] -= getShrink(item.primary, item.size[primarySide]); itemRect[secondarySide] = secondary[0]; itemRect[2 + secondarySide] = secondary[1]; item.element.move(itemRect) } function Layout() { this._targets = [] } Layout.prototype = { constructor: Layout, dispose: function() { this._targets = null }, add: function(target) { this._targets.push(target) }, forward: function(targetRect) { var i, rect = targetRect.slice(), targets = createTargets(this._targets), ii = targets.length, cache = []; for (i = 0; i < ii; ++i) { if (processForward(targets[i], rect)) { cache.push(targets[i]) } } this._cache = cache.reverse(); return rect }, backward: function(targetRect) { var i, rect = targetRect.slice(), targets = this._cache, ii = targets.length; for (i = 0; i < ii; ++i) { processBackward(targets[i], rect) } this._cache = null } }; function createTargets(targets) { var i, layout, ii = targets.length, collection = []; for (i = 0; i < ii; ++i) { layout = targets[i].layoutOptions(); if (layout) { layout = normalizeLayoutOptions(layout); layout.element = targets[i]; collection.push(layout) } } processWeakItems(collection); return collection } function processWeakItems(collection) { var i, ii, j, weakItem, isProcessed = true; while (isProcessed) { isProcessed = false; ii = collection.length; for (i = 0; i < ii; ++i) { if (collection[i].weak) { weakItem = collection[i]; for (j = 0; j < ii; ++j) { if (i !== j && weakItem.side === collection[j].side && weakItem.primary === collection[j].primary) { collection[_min(i, j)] = makePair(collection[_min(i, j)], collection[_max(i, j)]); collection.splice(_max(i, j), 1); isProcessed = true; break } } if (isProcessed) { break } } } } } function makePair(first, second) { return { side: first.side, primary: first.primary, secondary: first.secondary === second.secondary ? first.secondary : bringToEdge(first.secondary) || bringToEdge(second.secondary), element: new PairElement(first, second) } } function PairElement(first, second) { this._first = first; this._second = second } PairElement.prototype.measure = function(targetSize) { var secondSize, first = this._first, second = this._second, size = targetSize.slice(), primarySide = first.side, secondarySide = getConjugateSide(primarySide), firstSize = first.element.measure(size.slice()); size[secondarySide] -= firstSize[secondarySide]; secondSize = second.element.measure(size.slice()); size[primarySide] = _max(firstSize[primarySide], secondSize[primarySide]); if (first.secondary === second.secondary) { size[secondarySide] = firstSize[secondarySide] + secondSize[secondarySide] } else { if (first.secondary === ALIGN_MIDDLE || second.secondary === ALIGN_MIDDLE) { size[secondarySide] = targetSize[secondarySide] / 2 + (first.secondary === ALIGN_MIDDLE ? firstSize : secondSize)[secondarySide] / 2 } else { size[secondarySide] = targetSize[secondarySide] } } first.size = firstSize; second.size = secondSize; return size }; PairElement.prototype.move = function(targetRect) { var primary, secondary, rect, first = this._first, second = this._second, primarySide = first.side, secondarySide = getConjugateSide(primarySide), alignment = first.secondary === second.secondary ? bringToEdge(first.secondary) : first.secondary === ALIGN_MIDDLE ? getOppositeAlignment(bringToEdge(second.secondary)) : bringToEdge(first.secondary); primary = getSlice(ALIGN_MIDDLE, targetRect[primarySide], targetRect[2 + primarySide], first.size[primarySide]); secondary = getSlice(alignment, targetRect[secondarySide], targetRect[2 + secondarySide], first.size[secondarySide]); rect = []; rect[primarySide] = primary[0]; rect[2 + primarySide] = primary[1]; rect[secondarySide] = secondary[0]; rect[2 + secondarySide] = secondary[1]; first.element.move(rect); primary = getSlice(ALIGN_MIDDLE, targetRect[primarySide], targetRect[2 + primarySide], second.size[primarySide]); secondary = getSlice(getOppositeAlignment(alignment), targetRect[secondarySide], targetRect[2 + secondarySide], targetRect[2 + secondarySide] - targetRect[secondarySide] - first.size[secondarySide]); secondary = getSlice(getOppositeAlignment(alignment), secondary[0], secondary[1], second.size[secondarySide]); rect = []; rect[primarySide] = primary[0]; rect[2 + primarySide] = primary[1]; rect[secondarySide] = secondary[0]; rect[2 + secondarySide] = secondary[1]; second.element.move(rect) }; module.exports = Layout }, /*!*************************************!*\ !*** ./js/viz/components/legend.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), vizUtils = __webpack_require__( /*! ../core/utils */ 509), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, layoutElementModule = __webpack_require__( /*! ../core/layout_element */ 522), _Number = Number, _math = Math, _round = _math.round, _max = _math.max, _min = _math.min, _ceil = _math.ceil, objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), _isDefined = commonUtils.isDefined, _isFunction = commonUtils.isFunction, _enumParser = vizUtils.enumParser, _normalizeEnum = vizUtils.normalizeEnum, _extend = extend, _each = $.each, DEFAULT_MARGIN = 10, DEFAULT_MARKER_HATCHING_WIDTH = 2, DEFAULT_MARKER_HATCHING_STEP = 5, CENTER = "center", RIGHT = "right", LEFT = "left", TOP = "top", BOTTOM = "bottom", HORIZONTAL = "horizontal", VERTICAL = "vertical", INSIDE = "inside", OUTSIDE = "outside", NONE = "none", HEIGHT = "height", WIDTH = "width", parseHorizontalAlignment = _enumParser([LEFT, CENTER, RIGHT]), parseVerticalAlignment = _enumParser([TOP, BOTTOM]), parseOrientation = _enumParser([VERTICAL, HORIZONTAL]), parseItemTextPosition = _enumParser([LEFT, RIGHT, TOP, BOTTOM]), parsePosition = _enumParser([OUTSIDE, INSIDE]), parseItemsAlignment = _enumParser([LEFT, CENTER, RIGHT]); function getState(state, color) { if (!state) { return } var hatching, direction = state.hatching.direction, colorFromAction = state.fill; color = colorFromAction === NONE ? color : colorFromAction; direction = !direction || direction === NONE ? RIGHT : direction; hatching = _extend({}, state.hatching, { direction: direction, step: DEFAULT_MARKER_HATCHING_STEP, width: DEFAULT_MARKER_HATCHING_WIDTH }); return { fill: color, hatching: hatching } } function parseMargins(options) { var margin = options.margin; if (margin >= 0) { margin = _Number(options.margin); margin = { top: margin, bottom: margin, left: margin, right: margin } } else { margin = { top: margin.top >= 0 ? _Number(margin.top) : DEFAULT_MARGIN, bottom: margin.bottom >= 0 ? _Number(margin.bottom) : DEFAULT_MARGIN, left: margin.left >= 0 ? _Number(margin.left) : DEFAULT_MARGIN, right: margin.right >= 0 ? _Number(margin.right) : DEFAULT_MARGIN } } options.margin = margin } function getSizeItem(options, markerSize, labelBBox) { var width, height, defaultXMargin = 7, defaultTopMargin = 4; switch (options.itemTextPosition) { case LEFT: case RIGHT: width = markerSize + defaultXMargin + labelBBox.width; height = _max(markerSize, labelBBox.height); break; case TOP: case BOTTOM: width = _max(markerSize, labelBBox.width); height = markerSize + defaultTopMargin + labelBBox.height } return { width: width, height: height } } function calculateBBoxLabelAndMarker(markerBBox, labelBBox) { var bBox = {}; bBox.left = _min(markerBBox.x, labelBBox.x); bBox.top = _min(markerBBox.y, labelBBox.y); bBox.right = _max(markerBBox.x + markerBBox.width, labelBBox.x + labelBBox.width); bBox.bottom = _max(markerBBox.y + markerBBox.height, labelBBox.y + labelBBox.height); return bBox } function applyMarkerState(id, idToIndexMap, items, stateName) { var item = idToIndexMap && items[idToIndexMap[id]]; if (item) { item.marker.smartAttr(item.states[stateName]) } } function parseOptions(options, textField) { if (!options) { return null } var debug = __webpack_require__( /*! ../../core/utils/console */ 13).debug; debug.assertParam(options.visible, "Visibility was not passed"); debug.assertParam(options.markerSize, "markerSize was not passed"); debug.assertParam(options.font.color, "fontColor was not passed"); debug.assertParam(options.font.family, "fontFamily was not passed"); debug.assertParam(options.font.size, "fontSize was not passed"); debug.assertParam(options.paddingLeftRight, "paddingLeftRight was not passed"); debug.assertParam(options.paddingTopBottom, "paddingTopBottom was not passed"); debug.assertParam(options.columnItemSpacing, "columnItemSpacing was not passed"); debug.assertParam(options.rowItemSpacing, "rowItemSpacing was not passed"); parseMargins(options); options.horizontalAlignment = parseHorizontalAlignment(options.horizontalAlignment, RIGHT); options.verticalAlignment = parseVerticalAlignment(options.verticalAlignment, options.horizontalAlignment === CENTER ? BOTTOM : TOP); options.orientation = parseOrientation(options.orientation, options.horizontalAlignment === CENTER ? HORIZONTAL : VERTICAL); options.itemTextPosition = parseItemTextPosition(options.itemTextPosition, options.orientation === HORIZONTAL ? BOTTOM : RIGHT); options.position = parsePosition(options.position, OUTSIDE); options.itemsAlignment = parseItemsAlignment(options.itemsAlignment, null); options.hoverMode = _normalizeEnum(options.hoverMode); options.customizeText = _isFunction(options.customizeText) ? options.customizeText : function() { return this[textField] }; options.customizeHint = _isFunction(options.customizeHint) ? options.customizeHint : commonUtils.noop; options._incidentOccurred = options._incidentOccurred || commonUtils.noop; return options } function createSquareMarker(renderer, size) { return renderer.rect(0, 0, size, size) } function createCircleMarker(renderer, size) { return renderer.circle(size / 2, size / 2, size / 2) } function isCircle(type) { return "circle" === _normalizeEnum(type) } function inRect(rect, x, y) { return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom } function checkLinesSize(lines, layoutOptions, countItems) { var position = { x: 0, y: 0 }, maxMeasureLength = 0, maxAltMeasureLength = 0; _each(lines, function(i, line) { var firstItem = line[0]; _each(line, function(_, item) { var offset = item.offset || layoutOptions.spacing; position[layoutOptions.direction] += item[layoutOptions.measure] + offset; maxMeasureLength = _max(maxMeasureLength, position[layoutOptions.direction]) }); position[layoutOptions.direction] = 0; position[layoutOptions.altDirection] += firstItem[layoutOptions.altMeasure] + firstItem.altOffset || layoutOptions.altSpacing; maxAltMeasureLength = _max(maxAltMeasureLength, position[layoutOptions.altDirection]) }); if (maxMeasureLength > layoutOptions.length) { layoutOptions.countItem = decreaseItemCount(layoutOptions, countItems); return true } } function decreaseItemCount(layoutOptions, countItems) { layoutOptions.altCountItem++; return _ceil(countItems / layoutOptions.altCountItem) } function getLineLength(line, layoutOptions) { var lineLength = 0; _each(line, function(_, item) { var offset = item.offset || layoutOptions.spacing; lineLength += item[layoutOptions.measure] + offset }); return lineLength } function getMaxLineLength(lines, layoutOptions) { var maxLineLength = 0; _each(lines, function(_, line) { maxLineLength = _max(maxLineLength, getLineLength(line, layoutOptions)) }); return maxLineLength } function getInitPositionForDirection(line, layoutOptions, maxLineLength) { var initPosition, lineLength = getLineLength(line, layoutOptions); switch (layoutOptions.itemsAlignment) { case RIGHT: initPosition = maxLineLength - lineLength; break; case CENTER: initPosition = (maxLineLength - lineLength) / 2; break; default: initPosition = 0 } return initPosition } function getPos(layoutOptions) { switch (layoutOptions.itemTextPosition) { case BOTTOM: return { horizontal: CENTER, vertical: TOP }; case TOP: return { horizontal: CENTER, vertical: BOTTOM }; case LEFT: return { horizontal: RIGHT, vertical: CENTER }; case RIGHT: return { horizontal: LEFT, vertical: CENTER } } } function getLines(lines, layoutOptions, itemIndex) { var tableLine = {}; if (itemIndex % layoutOptions.countItem === 0) { if (layoutOptions.markerOffset) { lines.push([], []) } else { lines.push([]) } } if (layoutOptions.markerOffset) { tableLine.firstLine = lines[lines.length - 1]; tableLine.secondLine = lines[lines.length - 2] } else { tableLine.firstLine = tableLine.secondLine = lines[lines.length - 1] } return tableLine } function setMaxInLine(line, measure) { var maxLineSize = 0; _each(line, function(_, item) { if (!item) { return } maxLineSize = _max(maxLineSize, item[measure]) }); _each(line, function(_, item) { if (!item) { return } item[measure] = maxLineSize }) } function transpose(array) { var i, j, width = array.length, height = array[0].length, transposeArray = []; for (i = 0; i < height; i++) { transposeArray[i] = []; for (j = 0; j < width; j++) { transposeArray[i][j] = array[j][i] } } return transposeArray } function getAlign(position) { switch (position) { case TOP: case BOTTOM: return CENTER; case LEFT: return RIGHT; case RIGHT: return LEFT } } var getMarkerCreator = function(type) { return isCircle(type) ? createCircleMarker : createSquareMarker }; var _Legend = exports.Legend = function(settings) { var that = this; that._renderer = settings.renderer; that._legendGroup = settings.group; that._backgroundClass = settings.backgroundClass; that._itemGroupClass = settings.itemGroupClass; that._textField = settings.textField; that._getCustomizeObject = settings.getFormatObject }; var legendPrototype = _Legend.prototype = objectUtils.clone(layoutElementModule.LayoutElement.prototype); extend(legendPrototype, { constructor: _Legend, getOptions: function() { return this._options }, update: function(data, options) { var that = this; that._data = data; that._boundingRect = { width: 0, height: 0, x: 0, y: 0 }; that._options = parseOptions(options, that._textField); return that }, draw: function(width, height) { var that = this, options = that._options, renderer = that._renderer, items = that._data; this._size = { width: width, height: height }; that.erase(); if (!(options && options.visible && items && items.length)) { return that } that._insideLegendGroup = renderer.g().append(that._legendGroup); that._createBackground(); that._createItems(that._getItemData()); that._locateElements(options); that._finalUpdate(options); if (that.getLayoutOptions().width > width || that.getLayoutOptions().height > height) { that._options._incidentOccurred("W2104"); that.erase() } return that }, probeDraw: function(width, height) { return this.draw(width, height) }, _createItems: function(items) { var bBox, that = this, options = that._options, initMarkerSize = options.markerSize, renderer = that._renderer, maxBBoxHeight = 0, createMarker = getMarkerCreator(options.markerShape || options.markerType); that._markersId = {}; that._items = vizUtils.map(items, function(dataItem, i) { var group = that._insideLegendGroup, markerSize = _Number(dataItem.size > 0 ? dataItem.size : initMarkerSize), stateOfDataItem = dataItem.states, normalState = stateOfDataItem.normal, normalStateFill = normalState.fill, marker = createMarker(renderer, markerSize).attr({ fill: normalStateFill || options.markerColor, opacity: normalState.opacity }).append(group), label = that._createLabel(dataItem, group), states = { normal: { fill: normalStateFill }, hovered: getState(stateOfDataItem.hover, normalStateFill), selected: getState(stateOfDataItem.selection, normalStateFill) }, labelBBox = label.getBBox(); if (void 0 !== dataItem.id) { that._markersId[dataItem.id] = i } bBox = getSizeItem(options, markerSize, labelBBox); maxBBoxHeight = _max(maxBBoxHeight, bBox.height); that._createHint(dataItem, label); return { label: label, labelBBox: labelBBox, group: group, bBox: bBox, marker: marker, markerSize: markerSize, tracker: { id: dataItem.id, argument: dataItem.argument, argumentIndex: dataItem.argumentIndex }, states: states, itemTextPosition: options.itemTextPosition, markerOffset: 0, bBoxes: [] } }); if (options.equalRowHeight) { _each(that._items, function(_, item) { item.bBox.height = maxBBoxHeight }) } }, _getItemData: function() { var items = this._data; if (this._options.inverted) { items = items.slice().reverse() } return items }, _finalUpdate: function(options) { this._adjustBackgroundSettings(options); this._setBoundingRect(options.margin) }, erase: function() { var that = this, insideLegendGroup = that._insideLegendGroup; insideLegendGroup && insideLegendGroup.dispose(); that._insideLegendGroup = that._x1 = that._x2 = that._y2 = that._y2 = null; return that }, _locateElements: function(locationOptions) { this._moveInInitialValues(); this._locateRowsColumns(locationOptions) }, _moveInInitialValues: function() { var that = this; that._legendGroup && that._legendGroup.move(0, 0); that._background && that._background.attr({ x: 0, y: 0, width: 0, height: 0 }) }, applySelected: function(id) { applyMarkerState(id, this._markersId, this._items, "selected"); return this }, applyHover: function(id) { applyMarkerState(id, this._markersId, this._items, "hovered"); return this }, resetItem: function(id) { applyMarkerState(id, this._markersId, this._items, "normal"); return this }, _createLabel: function(data, group) { var labelFormatObject = this._getCustomizeObject(data), align = getAlign(this._options.itemTextPosition), text = this._options.customizeText.call(labelFormatObject, labelFormatObject), fontStyle = _isDefined(data.textOpacity) ? _extend({}, this._options.font, { opacity: data.textOpacity }) : this._options.font; return this._renderer.text(text, 0, 0).css(vizUtils.patchFontOptions(fontStyle)).attr({ align: align }).append(group) }, _createHint: function(data, label) { var labelFormatObject = this._getCustomizeObject(data), text = this._options.customizeHint.call(labelFormatObject, labelFormatObject); if (_isDefined(text) && "" !== text) { label.setTitle(text) } }, _createBackground: function() { var that = this, isInside = that._options.position === INSIDE, color = that._options.backgroundColor, fill = color || (isInside ? that._options.containerBackgroundColor : NONE); if (that._options.border.visible || (isInside || color) && color !== NONE) { that._background = that._renderer.rect(0, 0, 0, 0).attr({ fill: fill, "class": that._backgroundClass }).append(that._insideLegendGroup) } }, _locateRowsColumns: function() { var lines, that = this, iteration = 0, layoutOptions = that._getItemsLayoutOptions(), countItems = that._items.length; do { lines = []; that._createLines(lines, layoutOptions); that._alignLines(lines, layoutOptions); iteration++ } while (checkLinesSize(lines, layoutOptions, countItems) && iteration < countItems); that._applyItemPosition(lines, layoutOptions) }, _createLines: function(lines, layoutOptions) { _each(this._items, function(i, item) { var firstItem, secondItem, tableLine = getLines(lines, layoutOptions, i), labelBox = { width: item.labelBBox.width, height: item.labelBBox.height, element: item.label, bBox: item.labelBBox, pos: getPos(layoutOptions), itemIndex: i }, markerBox = { width: item.markerSize, height: item.markerSize, element: item.marker, pos: { horizontal: CENTER, vertical: CENTER }, bBox: { width: item.markerSize, height: item.markerSize, x: 0, y: 0 }, itemIndex: i }, offsetDirection = layoutOptions.markerOffset ? "altOffset" : "offset"; if (layoutOptions.inverseLabelPosition) { firstItem = labelBox; secondItem = markerBox } else { firstItem = markerBox; secondItem = labelBox } firstItem[offsetDirection] = layoutOptions.labelOffset; tableLine.secondLine.push(firstItem); tableLine.firstLine.push(secondItem) }) }, _alignLines: function(lines, layoutOptions) { var i, measure = layoutOptions.altMeasure; _each(lines, processLine); measure = layoutOptions.measure; if (layoutOptions.itemsAlignment) { if (layoutOptions.markerOffset) { for (i = 0; i < lines.length;) { _each(transpose([lines[i++], lines[i++]]), processLine) } } } else { _each(transpose(lines), processLine) } function processLine(_, line) { setMaxInLine(line, measure) } }, _applyItemPosition: function(lines, layoutOptions) { var that = this, position = { x: 0, y: 0 }, maxLineLength = getMaxLineLength(lines, layoutOptions); _each(lines, function(i, line) { var firstItem = line[0], altOffset = firstItem.altOffset || layoutOptions.altSpacing; position[layoutOptions.direction] = getInitPositionForDirection(line, layoutOptions, maxLineLength); _each(line, function(_, item) { var offset = item.offset || layoutOptions.spacing, wrap = new layoutElementModule.WrapperLayoutElement(item.element, item.bBox), itemBBox = new layoutElementModule.WrapperLayoutElement(null, { x: position.x, y: position.y, width: item.width, height: item.height }), itemLegend = that._items[item.itemIndex]; wrap.position({ of: itemBBox, my: item.pos, at: item.pos }); itemLegend.bBoxes.push(itemBBox); position[layoutOptions.direction] += item[layoutOptions.measure] + offset }); position[layoutOptions.altDirection] += firstItem[layoutOptions.altMeasure] + altOffset }); _each(this._items, function(_, item) { var itemBBox = calculateBBoxLabelAndMarker(item.bBoxes[0].getLayoutOptions(), item.bBoxes[1].getLayoutOptions()), horizontal = that._options.columnItemSpacing / 2, vertical = that._options.rowItemSpacing / 2; item.tracker.left = itemBBox.left - horizontal; item.tracker.right = itemBBox.right + horizontal; item.tracker.top = itemBBox.top - vertical; item.tracker.bottom = itemBBox.bottom + vertical }) }, _getItemsLayoutOptions: function() { var that = this, options = that._options, orientation = options.orientation, layoutOptions = { itemsAlignment: options.itemsAlignment, orientation: options.orientation }, width = that._size.width - (that._background ? 2 * options.paddingLeftRight : 0), height = that._size.height - (that._background ? 2 * options.paddingTopBottom : 0); if (orientation === HORIZONTAL) { layoutOptions.length = width; layoutOptions.spacing = options.columnItemSpacing; layoutOptions.direction = "x"; layoutOptions.measure = WIDTH; layoutOptions.altMeasure = HEIGHT; layoutOptions.altDirection = "y"; layoutOptions.altSpacing = options.rowItemSpacing; layoutOptions.countItem = options.columnCount; layoutOptions.altCountItem = options.rowCount; layoutOptions.marginTextLabel = 4; layoutOptions.labelOffset = 7; if (options.itemTextPosition === BOTTOM || options.itemTextPosition === TOP) { layoutOptions.labelOffset = 4; layoutOptions.markerOffset = true } } else { layoutOptions.length = height; layoutOptions.spacing = options.rowItemSpacing; layoutOptions.direction = "y"; layoutOptions.measure = HEIGHT; layoutOptions.altMeasure = WIDTH; layoutOptions.altDirection = "x"; layoutOptions.altSpacing = options.columnItemSpacing; layoutOptions.countItem = options.rowCount; layoutOptions.altCountItem = options.columnCount; layoutOptions.marginTextLabel = 7; layoutOptions.labelOffset = 4; if (options.itemTextPosition === RIGHT || options.itemTextPosition === LEFT) { layoutOptions.labelOffset = 7; layoutOptions.markerOffset = true } } if (!layoutOptions.countItem) { if (layoutOptions.altCountItem) { layoutOptions.countItem = _ceil(that._items.length / layoutOptions.altCountItem) } else { layoutOptions.countItem = that._items.length } } if (options.itemTextPosition === TOP || options.itemTextPosition === LEFT) { layoutOptions.inverseLabelPosition = true } layoutOptions.itemTextPosition = options.itemTextPosition; layoutOptions.altCountItem = layoutOptions.altCountItem || _ceil(that._items.length / layoutOptions.countItem); return layoutOptions }, _adjustBackgroundSettings: function(locationOptions) { if (!this._background) { return } var border = locationOptions.border, legendBox = this._insideLegendGroup.getBBox(), backgroundSettings = { x: _round(legendBox.x - locationOptions.paddingLeftRight), y: _round(legendBox.y - locationOptions.paddingTopBottom), width: _round(legendBox.width) + 2 * locationOptions.paddingLeftRight, height: _round(legendBox.height) + 2 * locationOptions.paddingTopBottom, opacity: locationOptions.backgroundOpacity }; if (border.visible && border.width && border.color && border.color !== NONE) { backgroundSettings["stroke-width"] = border.width; backgroundSettings.stroke = border.color; backgroundSettings["stroke-opacity"] = border.opacity; backgroundSettings.dashStyle = border.dashStyle; backgroundSettings.rx = border.cornerRadius || 0; backgroundSettings.ry = border.cornerRadius || 0 } this._background.attr(backgroundSettings) }, _setBoundingRect: function(margin) { if (!this._insideLegendGroup) { return } var box = this._insideLegendGroup.getBBox(); box.height += margin.top + margin.bottom; box.width += margin.left + margin.right; box.x -= margin.left; box.y -= margin.top; this._boundingRect = box }, getActionCallback: function(point) { var that = this; if (that._options.visible) { return function(act) { that[act](point.index) } } else { return commonUtils.noop } }, getLayoutOptions: function() { var options = this._options, boundingRect = this._insideLegendGroup ? this._boundingRect : { width: 0, height: 0, x: 0, y: 0 }; if (options) { boundingRect.verticalAlignment = options.verticalAlignment; boundingRect.horizontalAlignment = options.horizontalAlignment; if (options.orientation === HORIZONTAL) { boundingRect.cutLayoutSide = options.verticalAlignment; boundingRect.cutSide = "vertical" } else { if (options.horizontalAlignment === CENTER) { boundingRect.cutLayoutSide = options.verticalAlignment; boundingRect.cutSide = "vertical" } else { boundingRect.cutLayoutSide = options.horizontalAlignment; boundingRect.cutSide = "horizontal" } } boundingRect.position = { horizontal: options.horizontalAlignment, vertical: options.verticalAlignment }; return boundingRect } return null }, shift: function(x, y) { var that = this, box = {}; if (that._insideLegendGroup) { that._insideLegendGroup.attr({ translateX: x - that._boundingRect.x, translateY: y - that._boundingRect.y }); box = that._legendGroup.getBBox() } that._x1 = box.x; that._y1 = box.y; that._x2 = box.x + box.width; that._y2 = box.y + box.height; return that }, getPosition: function() { return this._options.position }, coordsIn: function(x, y) { return x >= this._x1 && x <= this._x2 && y >= this._y1 && y <= this._y2 }, getItemByCoord: function(x, y) { var items = this._items, legendGroup = this._insideLegendGroup; x -= legendGroup.attr("translateX"); y -= legendGroup.attr("translateY"); for (var i = 0; i < items.length; i++) { if (inRect(items[i].tracker, x, y)) { return items[i].tracker } } return null }, dispose: function() { var that = this; that._legendGroup = that._insideLegendGroup = that._renderer = that._options = that._data = that._items = null; return that } }); var __getMarkerCreator = getMarkerCreator; exports._DEBUG_stubMarkerCreator = function(callback) { getMarkerCreator = function() { return callback } }; exports._DEBUG_restoreMarkerCreator = function() { getMarkerCreator = __getMarkerCreator } }, /*!***************************************!*\ !*** ./js/viz/core/layout_element.js ***! \***************************************/ function(module, exports, __webpack_require__) { var noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, _round = Math.round, objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), defaultOffset = { horizontal: 0, vertical: 0 }, alignFactors = { center: .5, right: 1, bottom: 1, left: 0, top: 0 }; function LayoutElement(options) { this._options = options } LayoutElement.prototype = { constructor: LayoutElement, position: function(options) { var that = this, ofBBox = options.of.getLayoutOptions(), myBBox = that.getLayoutOptions(), at = options.at, my = options.my, offset = options.offset || defaultOffset, shiftX = -alignFactors[my.horizontal] * myBBox.width + ofBBox.x + alignFactors[at.horizontal] * ofBBox.width + parseInt(offset.horizontal), shiftY = -alignFactors[my.vertical] * myBBox.height + ofBBox.y + alignFactors[at.vertical] * ofBBox.height + parseInt(offset.vertical); that.shift(_round(shiftX), _round(shiftY)) }, getLayoutOptions: noop }; function WrapperLayoutElement(renderElement, bBox) { this._renderElement = renderElement; this._cacheBBox = bBox } var wrapperLayoutElementPrototype = WrapperLayoutElement.prototype = objectUtils.clone(LayoutElement.prototype); wrapperLayoutElementPrototype.constructor = WrapperLayoutElement; wrapperLayoutElementPrototype.getLayoutOptions = function() { return this._cacheBBox || this._renderElement.getBBox() }; wrapperLayoutElementPrototype.shift = function(shiftX, shiftY) { var bBox = this.getLayoutOptions(); this._renderElement.move(_round(shiftX - bBox.x), _round(shiftY - bBox.y)) }; exports.LayoutElement = LayoutElement; exports.WrapperLayoutElement = WrapperLayoutElement }, /*!*********************************************!*\ !*** ./js/viz/components/data_validator.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), STRING = "string", NUMERIC = "numeric", DATETIME = "datetime", DISCRETE = "discrete", SEMIDISCRETE = "semidiscrete", CONTINUOUS = "continuous", LOGARITHMIC = "logarithmic", VALUE_TYPE = "valueType", ARGUMENT_TYPE = "argumentType", axisTypeParser = __webpack_require__( /*! ../core/utils */ 509).enumParser([STRING, NUMERIC, DATETIME]), _getParser = __webpack_require__( /*! ./parse_utils */ 524).getParser, _isDefined = commonUtils.isDefined, _isFunction = commonUtils.isFunction, _isArray = Array.isArray, _isString = commonUtils.isString, _isDate = commonUtils.isDate, _isNumber = commonUtils.isNumeric, _isObject = commonUtils.isObject; function groupingValues(data, others, valueField, index) { if (index >= 0) { data.slice(index).forEach(function(cell) { if (_isDefined(cell[valueField])) { others[valueField] += cell[valueField]; cell[valueField] = cell["original" + valueField] = void 0 } }) } } function processGroups(groups) { groups.forEach(function(group) { group.valueType = group.valueAxisType = null; group.series.forEach(function(series) { series.updateDataType({}) }); group.valueAxis && group.valueAxis.resetTypes(VALUE_TYPE) }) } function resetArgumentAxes(axes) { axes && axes.forEach(function(axis) { axis.resetTypes(ARGUMENT_TYPE) }) } function parseCategories(categories, parser) { var newArray = []; categories.forEach(function(category) { var parsedCategory = parser(category); void 0 !== parsedCategory && newArray.push(parsedCategory) }); return newArray } function parseAxisCategories(groupsData, parsers) { var argumentCategories = groupsData.argumentOptions && groupsData.argumentOptions.categories, valueParser = parsers[1]; groupsData.groups.forEach(function(valueGroup) { var categories = valueGroup.valueOptions && valueGroup.valueOptions.categories; if (categories) { valueGroup.valueOptions.categories = parseCategories(categories, valueParser) } }); if (argumentCategories) { groupsData.argumentOptions.categories = parseCategories(argumentCategories, parsers[0]) } } function filterForLogAxis(val, field, incidentOccurred) { if (val <= 0 && null !== val) { incidentOccurred("E2004", [field]); val = null } return val } function eigen(x) { return x } function getType(unit, type) { var result = type; if (type === STRING || _isString(unit)) { result = STRING } else { if (type === DATETIME || _isDate(unit)) { result = DATETIME } else { if (_isNumber(unit)) { result = NUMERIC } } } return result } function correctAxisType(type, axisType, hasCategories, incidentOccurred) { if (type === STRING && (axisType === CONTINUOUS || axisType === LOGARITHMIC || axisType === SEMIDISCRETE)) { incidentOccurred("E2002") } return axisType === LOGARITHMIC ? LOGARITHMIC : hasCategories || axisType === DISCRETE || type === STRING ? DISCRETE : axisType === SEMIDISCRETE ? SEMIDISCRETE : CONTINUOUS } function validUnit(unit, field, incidentOccurred) { if (unit) { incidentOccurred(!_isNumber(unit) && !_isDate(unit) && !_isString(unit) ? "E2003" : "E2004", [field]) } } function createParserUnit(type, axisType, ignoreEmptyPoints, skipFields, incidentOccurred) { var parser = type ? _getParser(type) : eigen, filter = axisType === LOGARITHMIC ? filterForLogAxis : eigen, filterInfinity = axisType !== DISCRETE ? function(x) { return isFinite(x) || void 0 === x ? x : null } : eigen, filterNulls = ignoreEmptyPoints ? function(x) { return null === x ? void 0 : x } : eigen; return function(unit, field) { var filterLogValues = function(x) { return filter(x, field, incidentOccurred) }, parseUnit = filterNulls(filterLogValues(filterInfinity(parser(unit)))); if (void 0 === parseUnit) { skipFields[field] = (skipFields[field] || 0) + 1; validUnit(unit, field, incidentOccurred) } return parseUnit } } function prepareParsers(groupsData, skipFields, incidentOccurred) { var sizeParser, valueParser, ignoreEmptyPoints, argumentParser = createParserUnit(groupsData.argumentType, groupsData.argumentAxisType, false, skipFields, incidentOccurred), categoryParsers = [argumentParser], cache = {}, list = []; groupsData.groups.forEach(function(group) { group.series.forEach(function(series) { ignoreEmptyPoints = series.getOptions().ignoreEmptyPoints; valueParser = createParserUnit(group.valueType, group.valueAxisType, ignoreEmptyPoints, skipFields, incidentOccurred); sizeParser = createParserUnit(NUMERIC, CONTINUOUS, ignoreEmptyPoints, skipFields, incidentOccurred); cache[series.getArgumentField()] = argumentParser; series.getValueFields().forEach(function(field) { !categoryParsers[1] && (categoryParsers[1] = valueParser); cache[field] = valueParser }); if (series.getSizeField()) { cache[series.getSizeField()] = sizeParser } if (series.getTagField()) { cache[series.getTagField()] = eigen } }) }); for (var field in cache) { list.push([field, cache[field]]) } list.length && parseAxisCategories(groupsData, categoryParsers); return list } function getParsedCell(cell, parsers) { var i, field, value, ii = parsers.length, obj = {}; for (i = 0; i < ii; ++i) { field = parsers[i][0]; value = cell[field]; obj[field] = parsers[i][1](value, field); obj["original" + field] = value } return obj } function parse(data, parsers) { var i, parsedData = [], ii = data.length; parsedData.length = ii; for (i = 0; i < ii; ++i) { parsedData[i] = getParsedCell(data[i], parsers) } return parsedData } function findIndexByThreshold(data, valueField, threshold) { var i, value, ii = data.length; for (i = 0; i < ii; ++i) { value = data[i][valueField]; if (_isDefined(value) && threshold > value) { break } } return i } function groupMinSlices(originalData, argumentField, valueField, smallValuesGrouping) { smallValuesGrouping = smallValuesGrouping || {}; var data, mode = smallValuesGrouping.mode, others = {}; if (!mode || "none" === mode) { return } others[argumentField] = String(smallValuesGrouping.groupName || "others"); others[valueField] = 0; data = originalData.slice(); data.sort(function(a, b) { var isA = _isDefined(a[valueField]) ? 1 : 0, isB = _isDefined(b[valueField]) ? 1 : 0; return isA && isB ? b[valueField] - a[valueField] : isB - isA }); groupingValues(data, others, valueField, "smallValueThreshold" === mode ? findIndexByThreshold(data, valueField, smallValuesGrouping.threshold) : smallValuesGrouping.topCount); others[valueField] && originalData.push(others) } function groupPieData(data, groupsData) { var firstSeries = groupsData.groups[0] && groupsData.groups[0].series[0], isPie = firstSeries && ("pie" === firstSeries.type || "doughnut" === firstSeries.type || "donut" === firstSeries.type); if (!isPie) { return } groupsData.groups.forEach(function(group) { group.series.forEach(function(series) { groupMinSlices(data, series.getArgumentField(), series.getValueFields()[0], series.getOptions().smallValuesGrouping) }) }) } function addUniqueItemToCollection(item, collection, itemsHash) { if (!itemsHash[item]) { collection.push(item); itemsHash[item] = true } } function getUniqueArgumentFields(groupsData) { var uniqueArgumentFields = [], hash = {}; groupsData.groups.forEach(function(group) { group.series.forEach(function(series) { addUniqueItemToCollection(series.getArgumentField(), uniqueArgumentFields, hash) }) }); return uniqueArgumentFields } function sort(a, b) { var result = a - b; if (isNaN(result)) { if (!_isDefined(a)) { return 1 } if (!_isDefined(b)) { return -1 } return 0 } return result } function sortByArgument(data, argumentField) { return data.slice().sort(function(a, b) { return sort(a[argumentField], b[argumentField]) }) } function sortByCallback(data, callback) { return data.slice().sort(callback) } function checkValueTypeOfGroup(group, cell) { group.series.forEach(function(series) { series.getValueFields().forEach(function(field) { group.valueType = getType(cell[field], group.valueType) }) }); return group.valueType } function getSortByCategories(categories) { var hash = {}; categories.forEach(function(value, i) { hash[value] = i }); return function(data, argumentField) { return data.slice().sort(function(a, b) { return hash[a[argumentField]] - hash[b[argumentField]] }) } } function sortData(data, groupsData, sortingMethodOption, uniqueArgumentFields) { var reSortCategories, dataByArguments = {}, isDiscrete = groupsData.argumentAxisType === DISCRETE, userCategories = isDiscrete && groupsData.argumentOptions && groupsData.argumentOptions.categories, sortFunction = function(data) { return data }; if (!userCategories && _isFunction(sortingMethodOption)) { data = sortByCallback(data, sortingMethodOption) } if (isDiscrete) { groupsData.categories = getCategories(data, uniqueArgumentFields, userCategories) } if (userCategories || !_isFunction(sortingMethodOption) && groupsData.argumentType === STRING) { sortFunction = getSortByCategories(groupsData.categories) } else { if (true === sortingMethodOption && groupsData.argumentType !== STRING) { sortFunction = sortByArgument; reSortCategories = isDiscrete } } uniqueArgumentFields.forEach(function(field) { dataByArguments[field] = sortFunction(data, field) }); if (reSortCategories) { groupsData.categories = groupsData.categories.sort(sort) } return dataByArguments } function checkItemExistence(collection, item) { return collection.map(function(collectionItem) { return collectionItem.valueOf() }).indexOf(item.valueOf()) === -1 } function getCategories(data, uniqueArgumentFields, userCategories) { var categories = userCategories ? userCategories.slice() : []; uniqueArgumentFields.forEach(function(field) { data.forEach(function(item) { var dataItem = item[field]; _isDefined(dataItem) && checkItemExistence(categories, dataItem) && categories.push(dataItem) }) }); return categories } function checkArgumentTypeOfGroup(series, cell, groupsData) { series.forEach(function(currentSeries) { groupsData.argumentType = getType(cell[currentSeries.getArgumentField()], groupsData.argumentType) }); return groupsData.argumentType } function checkType(data, groupsData, checkTypeForAllData) { var groupsIndexes, groupsWithUndefinedValueType = [], groupsWithUndefinedArgumentType = [], argumentTypeGroup = groupsData.argumentOptions && axisTypeParser(groupsData.argumentOptions.argumentType); groupsData.groups.forEach(function(group) { if (!group.series.length) { return } var valueTypeGroup = group.valueOptions && axisTypeParser(group.valueOptions.valueType); group.valueType = valueTypeGroup; groupsData.argumentType = argumentTypeGroup; !valueTypeGroup && groupsWithUndefinedValueType.push(group); !argumentTypeGroup && groupsWithUndefinedArgumentType.push(group) }); if (groupsWithUndefinedValueType.length || groupsWithUndefinedArgumentType.length) { groupsIndexes = groupsWithUndefinedValueType.map(function(_, index) { return index }); data.some(function(cell) { var defineArg; groupsWithUndefinedValueType.forEach(function(group, groupIndex) { if (checkValueTypeOfGroup(group, cell) && groupsIndexes.indexOf(groupIndex) >= 0) { groupsIndexes.splice(groupIndex, 1) } }); if (!defineArg) { groupsWithUndefinedArgumentType.forEach(function(group) { defineArg = checkArgumentTypeOfGroup(group.series, cell, groupsData) }) } if (!checkTypeForAllData && defineArg && 0 === groupsIndexes.length) { return true } }) } } function checkAxisType(groupsData, incidentOccurred) { var argumentOptions = groupsData.argumentOptions || {}, userArgumentCategories = argumentOptions && argumentOptions.categories || [], argumentAxisType = correctAxisType(groupsData.argumentType, argumentOptions.type, !!userArgumentCategories.length, incidentOccurred); groupsData.groups.forEach(function(group) { var valueOptions = group.valueOptions || {}, valueCategories = valueOptions.categories || [], valueAxisType = correctAxisType(group.valueType, valueOptions.type, !!valueCategories.length, incidentOccurred); group.series.forEach(function(series) { var optionsSeries = {}; optionsSeries.argumentAxisType = argumentAxisType; optionsSeries.valueAxisType = valueAxisType; groupsData.argumentAxisType = groupsData.argumentAxisType || optionsSeries.argumentAxisType; group.valueAxisType = group.valueAxisType || optionsSeries.valueAxisType; optionsSeries.argumentType = groupsData.argumentType; optionsSeries.valueType = group.valueType; optionsSeries.showZero = valueOptions.showZero; series.updateDataType(optionsSeries) }); group.valueAxisType = group.valueAxisType || valueAxisType; if (group.valueAxis) { group.valueAxis.setTypes(group.valueAxisType, group.valueType, VALUE_TYPE); group.valueAxis.validate(false) } }); groupsData.argumentAxisType = groupsData.argumentAxisType || argumentAxisType; if (groupsData.argumentAxes) { groupsData.argumentAxes.forEach(function(axis) { axis.setTypes(groupsData.argumentAxisType, groupsData.argumentType, ARGUMENT_TYPE); axis.validate(true) }) } } function verifyData(source, incidentOccurred) { var i, ii, k, item, data = [], sourceIsDefined = _isDefined(source), hasError = sourceIsDefined && !_isArray(source); if (sourceIsDefined && !hasError) { for (i = 0, ii = source.length, k = 0; i < ii; ++i) { item = source[i]; if (_isObject(item)) { data[k++] = item } else { if (item) { hasError = true } } } } if (hasError) { incidentOccurred("E2001") } return data } function validateData(data, groupsData, incidentOccurred, options) { var dataByArgumentFields, field, skipFields = {}; data = verifyData(data, incidentOccurred); groupsData.argumentType = groupsData.argumentAxisType = null; processGroups(groupsData.groups); resetArgumentAxes(groupsData.argumentAxes); checkType(data, groupsData, options.checkTypeForAllData); checkAxisType(groupsData, incidentOccurred); if (options.convertToAxisDataType) { data = parse(data, prepareParsers(groupsData, skipFields, incidentOccurred)) } groupPieData(data, groupsData); dataByArgumentFields = sortData(data, groupsData, options.sortingMethod, getUniqueArgumentFields(groupsData)); for (field in skipFields) { if (skipFields[field] === data.length) { incidentOccurred("W2002", [field]) } } return dataByArgumentFields } exports.validateData = validateData }, /*!******************************************!*\ !*** ./js/viz/components/parse_utils.js ***! \******************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), dateSerialization = __webpack_require__( /*! ../../core/utils/date_serialization */ 259), isDefined = commonUtils.isDefined, parsers = { string: function(val) { return isDefined(val) ? "" + val : val }, numeric: function(val) { if (!isDefined(val)) { return val } var parsedVal = Number(val); if (isNaN(parsedVal)) { parsedVal = void 0 } return parsedVal }, datetime: function(val) { if (!isDefined(val)) { return val } var parsedVal, numVal = Number(val); if (!isNaN(numVal)) { parsedVal = new Date(numVal) } else { parsedVal = dateSerialization.deserializeDate(val) } if (isNaN(Number(parsedVal))) { parsedVal = void 0 } return parsedVal } }; function correctValueType(type) { return "numeric" === type || "datetime" === type || "string" === type ? type : "" } module.exports = { correctValueType: correctValueType, getParser: function(valueType) { return parsers[correctValueType(valueType)] || commonUtils.noop } }; module.exports.parsers = parsers }, /*!**************************************!*\ !*** ./js/viz/series/base_series.js ***! \**************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), seriesNS = {}, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, pointModule = __webpack_require__( /*! ./points/base_point */ 526), _isDefined = commonUtils.isDefined, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _map = vizUtils.map, _each = $.each, _extend = extend, _isEmptyObject = typeUtils.isEmptyObject, _normalizeEnum = vizUtils.normalizeEnum, _Event = $.Event, _noop = commonUtils.noop, _inArray = inArray, states = __webpack_require__( /*! ../components/consts */ 527).states, rangeCalculator = __webpack_require__( /*! ./helpers/range_data_calculator */ 539), scatterSeries = __webpack_require__( /*! ./scatter_series */ 540), lineSeries = __webpack_require__( /*! ./line_series */ 541), areaSeries = __webpack_require__( /*! ./area_series */ 542), barSeries = __webpack_require__( /*! ./bar_series */ 543), rangeSeries = __webpack_require__( /*! ./range_series */ 544), bubbleSeries = __webpack_require__( /*! ./bubble_series */ 545), pieSeries = __webpack_require__( /*! ./pie_series */ 546), financialSeries = __webpack_require__( /*! ./financial_series */ 547), stackedSeries = __webpack_require__( /*! ./stacked_series */ 548), DISCRETE = "discrete", SELECTED_STATE = states.selectedMark, HOVER_STATE = states.hoverMark, HOVER = states.hover, NORMAL = states.normal, SELECTION = states.selection, APPLY_SELECTED = states.applySelected, APPLY_HOVER = states.applyHover, RESET_ITEM = states.resetItem, NONE_MODE = "none", INCLUDE_POINTS = "includepoints", NEAREST_POINT = "nearestpoint", SERIES_SELECTION_CHANGED = "seriesSelectionChanged", POINT_SELECTION_CHANGED = "pointSelectionChanged", SERIES_HOVER_CHANGED = "seriesHoverChanged", POINT_HOVER_CHANGED = "pointHoverChanged", ALL_SERIES_POINTS = "allseriespoints", ALL_ARGUMENT_POINTS = "allargumentpoints", POINT_HOVER = "pointHover", CLEAR_POINT_HOVER = "clearPointHover", SERIES_SELECT = "seriesSelect", POINT_SELECT = "pointSelect", POINT_DESELECT = "pointDeselect", getEmptyBusinessRange = function() { return { arg: {}, val: {} } }; function triggerEvent(element, event, point) { element && element.trigger(event, point) } seriesNS.mixins = { chart: {}, pie: {}, polar: {} }; seriesNS.mixins.chart.scatter = scatterSeries.chart; seriesNS.mixins.polar.scatter = scatterSeries.polar; extend(seriesNS.mixins.pie, pieSeries); extend(seriesNS.mixins.chart, lineSeries.chart, areaSeries.chart, barSeries.chart, rangeSeries.chart, bubbleSeries.chart, financialSeries, stackedSeries.chart); extend(seriesNS.mixins.polar, lineSeries.polar, areaSeries.polar, barSeries.polar, rangeSeries.polar, bubbleSeries.polar, stackedSeries.polar); function includePointsMode(mode) { mode = _normalizeEnum(mode); return mode === INCLUDE_POINTS || mode === ALL_SERIES_POINTS } function getLabelOptions(labelOptions, defaultColor) { var opt = labelOptions || {}, labelFont = _extend({}, opt.font) || {}, labelBorder = opt.border || {}, labelConnector = opt.connector || {}, backgroundAttr = { fill: opt.backgroundColor || defaultColor, "stroke-width": labelBorder.visible ? labelBorder.width || 0 : 0, stroke: labelBorder.visible && labelBorder.width ? labelBorder.color : "none", dashStyle: labelBorder.dashStyle }, connectorAttr = { stroke: labelConnector.visible && labelConnector.width ? labelConnector.color || defaultColor : "none", "stroke-width": labelConnector.visible ? labelConnector.width || 0 : 0 }; labelFont.color = "none" === opt.backgroundColor && "#ffffff" === _normalizeEnum(labelFont.color) && "inside" !== opt.position ? defaultColor : labelFont.color; return { alignment: opt.alignment, format: opt.format, argumentFormat: opt.argumentFormat, precision: opt.precision, argumentPrecision: opt.argumentPrecision, percentPrecision: opt.percentPrecision, customizeText: commonUtils.isFunction(opt.customizeText) ? opt.customizeText : void 0, attributes: { font: labelFont }, visible: 0 !== labelFont.size ? opt.visible : false, showForZeroValues: opt.showForZeroValues, horizontalOffset: opt.horizontalOffset, verticalOffset: opt.verticalOffset, radialOffset: opt.radialOffset, background: backgroundAttr, position: opt.position, connector: connectorAttr, rotationAngle: opt.rotationAngle } } function setPointHoverState(point, legendCallback) { point.fullState |= HOVER_STATE; point.applyView(legendCallback) } function releasePointHoverState(point, legendCallback) { point.fullState &= ~HOVER_STATE; point.applyView(legendCallback); point.releaseHoverState() } function setPointSelectedState(point, legendCallback) { point.fullState |= SELECTED_STATE; point.applyView(legendCallback) } function releasePointSelectedState(point, legendCallback) { point.fullState &= ~SELECTED_STATE; point.applyView(legendCallback) } function mergePointOptionsCore(base, extra) { var options = _extend({}, base, extra); options.border = _extend({}, base && base.border, extra && extra.border); return options } function mergePointOptions(base, extra) { var options = mergePointOptionsCore(base, extra); options.image = _extend(true, {}, base.image, extra.image); options.selectionStyle = mergePointOptionsCore(base.selectionStyle, extra.selectionStyle); options.hoverStyle = mergePointOptionsCore(base.hoverStyle, extra.hoverStyle); return options } function Series(settings, options) { var that = this; that.fullState = 0; that._extGroups = settings; that._renderer = settings.renderer; that._group = settings.renderer.g().attr({ "class": "dxc-series" }); that._eventTrigger = settings.eventTrigger; that._eventPipe = settings.eventPipe; that._seriesModes = settings.commonSeriesModes; that._valueAxis = settings.valueAxis; that.axis = that._valueAxis && that._valueAxis.name; that._argumentAxis = settings.argumentAxis; that._legendCallback = _noop; that.updateOptions(options) } exports.Series = Series; exports.mixins = seriesNS.mixins; Series.prototype = { constructor: Series, _createLegendState: _noop, getLegendStyles: function() { return this._styles.legendStyles }, _createStyles: function(options) { var that = this, mainSeriesColor = options.mainSeriesColor; that._styles = { normal: that._parseStyle(options, mainSeriesColor, mainSeriesColor), hover: that._parseStyle(options.hoverStyle || {}, mainSeriesColor, mainSeriesColor), selection: that._parseStyle(options.selectionStyle || {}, mainSeriesColor, mainSeriesColor), legendStyles: { normal: that._createLegendState(options, mainSeriesColor), hover: that._createLegendState(options.hoverStyle || {}, mainSeriesColor), selection: that._createLegendState(options.selectionStyle || {}, mainSeriesColor) } } }, setClippingParams: function(baseId, wideId, forceClipping) { this._paneClipRectID = baseId; this._widePaneClipRectID = wideId; this._forceClipping = forceClipping }, applyClip: function() { this._group.attr({ "clip-path": this._paneClipRectID }) }, resetClip: function() { this._group.attr({ "clip-path": null }) }, getTagField: function() { return this._options.tagField || "tag" }, getValueFields: _noop, getSizeField: _noop, getArgumentField: _noop, getPoints: function() { return this._points }, _createPoint: function(data, pointsArray, index) { data.index = index; var options, arg, pointByArgument, that = this, point = pointsArray[index], pointsByArgument = that.pointsByArgument; if (that._checkData(data)) { options = that._getCreatingPointOptions(data); if (point) { point.update(data, options) } else { point = new pointModule.Point(that, data, options); if (that.isSelected() && includePointsMode(that.lastSelectionMode)) { point.setView(SELECTION) } pointsArray.push(point) } if (point.hasValue()) { that.customizePoint(point, data) } arg = point.argument.valueOf(); pointByArgument = pointsByArgument[arg]; if (pointByArgument) { pointByArgument.push(point) } else { pointsByArgument[arg] = [point] } return true } }, getRangeData: function(zoomArgs, calcIntervalFunction) { if (this._visible) { var range = this._getRangeData(); this._processRange(range); return range } return getEmptyBusinessRange() }, getViewport: function() { return rangeCalculator.getViewport(this) }, _deleteGroup: function(groupName) { var group = this[groupName]; if (group) { group.dispose(); this[groupName] = null } }, _saveOldAnimationMethods: function() { var that = this; that._oldClearingAnimation = that._clearingAnimation; that._oldUpdateElement = that._updateElement; that._oldGetAffineCoordOptions = that._getAffineCoordOptions }, _deleteOldAnimationMethods: function() { this._oldClearingAnimation = null; this._oldUpdateElement = null; this._oldGetAffineCoordOptions = null }, updateOptions: function(newOptions) { var that = this, widgetType = newOptions.widgetType, oldType = that.type, newType = newOptions.type; that.type = newType && _normalizeEnum(newType.toString()); if (!that._checkType(widgetType) || that._checkPolarBarType(widgetType, newOptions)) { that.dispose(); that.isUpdated = false; return } if (oldType !== that.type) { that._firstDrawing = true; that._saveOldAnimationMethods(); that._resetType(oldType, widgetType); that._setType(that.type, widgetType) } that._options = newOptions; that._pointOptions = null; that._renderer.initHatching(); that.name = newOptions.name; that.pane = newOptions.pane; that.tag = newOptions.tag; that._createStyles(newOptions); that._updateOptions(newOptions); that._visible = newOptions.visible; that.isUpdated = true; that._createGroups() }, _disposePoints: function(points) { _each(points || [], function(_, p) { p.dispose() }) }, _correctPointsLength: function(length, points) { this._disposePoints(this._oldPoints); this._oldPoints = points.splice(length, points.length) }, getErrorBarRangeCorrector: _noop, updateDataType: function(settings) { var that = this; that.argumentType = settings.argumentType; that.valueType = settings.valueType; that.argumentAxisType = settings.argumentAxisType; that.valueAxisType = settings.valueAxisType; that.showZero = settings.showZero; return that }, getOptions: function() { return this._options }, _resetRangeData: function() { this._rangeData = getEmptyBusinessRange() }, updateData: function(data) { var that = this, points = that._originalPoints || [], lastPointIndex = 0, options = that._options, i = 0, len = data.length; that.pointsByArgument = {}; that._resetRangeData(); if (data && data.length) { that._canRenderCompleteHandle = true } that._beginUpdateData(data); while (i < len) { if (that._createPoint(that._getPointData(data[i], options), points, lastPointIndex)) { lastPointIndex++ } i++ } that._disposePoints(that._aggregatedPoints); that._aggregatedPoints = null; that._points = that._originalPoints = points; that._correctPointsLength(lastPointIndex, points); that._endUpdateData() }, getTemplateFields: function() { return this.getValueFields().concat(this.getTagField(), this.getSizeField()).map(function(field) { return { templateField: field + this.name, originalField: field } }, this) }, resamplePoints: function(canvasLength) { var categories, discreteMin, discreteMax, count, tickInterval, that = this, sizePoint = that._getPointSize(), pointsLength = that.getAllPoints().length, argumentAxis = that.getArgumentAxis(), viewport = argumentAxis.getViewport(), min = viewport && viewport.min, max = viewport && viewport.max, argTranslator = argumentAxis.getTranslator(), isDiscrete = that.argumentAxisType === DISCRETE || that.valueAxisType === DISCRETE, businessRange = argTranslator.getBusinessRange(), minMaxDefined = _isDefined(min) && _isDefined(max); if (pointsLength && pointsLength > 1) { count = canvasLength / sizePoint; count = count <= 1 ? 1 : count; if (isDiscrete) { if (that.argumentAxisType === DISCRETE) { categories = businessRange.categories; discreteMin = _inArray(min, categories); discreteMax = _inArray(max, categories); if (discreteMin !== -1 && discreteMax !== -1) { categories = categories.slice(discreteMin, discreteMax + 1) } pointsLength = categories.length } tickInterval = Math.ceil(pointsLength / count) } else { tickInterval = (minMaxDefined ? max - min : businessRange.maxVisible - businessRange.minVisible) / count } that._points = that._resample(tickInterval, min - tickInterval, max + tickInterval, minMaxDefined) } }, _removeOldSegments: function(startIndex) { var that = this; _each(that._graphics.splice(startIndex, that._graphics.length) || [], function(_, elem) { that._removeElement(elem) }); if (that._trackers) { _each(that._trackers.splice(startIndex, that._trackers.length) || [], function(_, elem) { elem.remove() }) } }, draw: function(animationEnabled, hideLayoutLabels, legendCallback) { var drawComplete, that = this; if (that._oldClearingAnimation && animationEnabled && that._firstDrawing) { drawComplete = function() { that._draw(true, hideLayoutLabels) }; that._oldClearingAnimation(drawComplete) } else { that._draw(animationEnabled, hideLayoutLabels, legendCallback) } }, _draw: function(animationEnabled, hideLayoutLabels, legendCallback) { var groupForPoint, that = this, points = that._points || [], segment = [], segmentCount = 0, firstDrawing = that._firstDrawing, closeSegment = points[0] && points[0].hasValue() && that._options.closed; that._legendCallback = legendCallback || that._legendCallback; that._graphics = that._graphics || []; that._prepareSeriesToDrawing(); if (!that._visible) { animationEnabled = false; that._group.remove(); return } that._appendInGroup(); that._applyVisibleArea(); that._setGroupsSettings(animationEnabled, firstDrawing); that._segments = []; that._drawnPoints = []; that._firstDrawing = points.length ? false : true; groupForPoint = { markers: that._markersGroup, errorBars: that._errorBarGroup }; _each(points, function(i, p) { p.translate(); if (p.hasValue()) { that._drawPoint({ point: p, groups: groupForPoint, hasAnimation: animationEnabled, firstDrawing: firstDrawing }); segment.push(p) } else { if (segment.length) { that._drawSegment(segment, animationEnabled, segmentCount++); segment = [] } } }); segment.length && that._drawSegment(segment, animationEnabled, segmentCount++, closeSegment); that._removeOldSegments(segmentCount); that._defaultSegments = that._generateDefaultSegments(); hideLayoutLabels && that.hideLabels(); animationEnabled && that._animate(firstDrawing); if (that.isSelected()) { that._changeStyle(that.lastSelectionMode, void 0, true) } else { if (that.isHovered()) { that._changeStyle(that.lastHoverMode, void 0, true) } } }, _setLabelGroupSettings: function(animationEnabled) { var settings = { "class": "dxc-labels" }; this._applyElementsClipRect(settings); this._applyClearingSettings(settings); animationEnabled && (settings.opacity = .001); this._labelsGroup.attr(settings).append(this._extGroups.labelsGroup) }, _checkType: function(widgetType) { return !!seriesNS.mixins[widgetType][this.type] }, _checkPolarBarType: function(widgetType, options) { return "polar" === widgetType && options.spiderWidget && this.type.indexOf("bar") !== -1 }, _resetType: function(seriesType, widgetType) { var methodName, methods; if (seriesType) { methods = seriesNS.mixins[widgetType][seriesType]; for (methodName in methods) { delete this[methodName] } } }, _setType: function(seriesType, widgetType) { var methodName, methods = seriesNS.mixins[widgetType][seriesType]; for (methodName in methods) { this[methodName] = methods[methodName] } }, _setPointsView: function(view, target) { this.getPoints().forEach(function(point) { if (target !== point) { point.setView(view) } }) }, _resetPointsView: function(view, target) { this.getPoints().forEach(function(point) { if (target !== point) { point.resetView(view) } }) }, _resetNearestPoint: function() { var that = this; that._nearestPoint && that._nearestPoint.resetView(HOVER); that._nearestPoint = null }, _setSelectedState: function(mode) { var that = this; that.lastSelectionMode = _normalizeEnum(mode || that._options.selectionMode); that.fullState = that.fullState | SELECTED_STATE; that._resetNearestPoint(); that._changeStyle(that.lastSelectionMode); if (that.lastSelectionMode !== NONE_MODE && that.isHovered() && includePointsMode(that.lastHoverMode)) { that._resetPointsView(HOVER) } }, _releaseSelectedState: function() { var that = this; that.fullState = that.fullState & ~SELECTED_STATE; that._changeStyle(that.lastSelectionMode, SELECTION); if (that.lastSelectionMode !== NONE_MODE && that.isHovered() && includePointsMode(that.lastHoverMode)) { that._setPointsView(HOVER) } }, isFullStackedSeries: function() { return 0 === this.type.indexOf("fullstacked") }, isStackedSeries: function() { return 0 === this.type.indexOf("stacked") }, isFinancialSeries: function() { return "stock" === this.type || "candlestick" === this.type }, _canChangeView: function() { return !this.isSelected() && _normalizeEnum(this._options.hoverMode) !== NONE_MODE }, _changeStyle: function(mode, resetView, skipPoints) { var that = this, state = that.fullState, styles = [NORMAL, HOVER, SELECTION, SELECTION]; if ("none" === that.lastHoverMode) { state &= ~HOVER_STATE } if ("none" === that.lastSelectionMode) { state &= ~SELECTED_STATE } if (includePointsMode(mode) && !skipPoints) { if (!resetView) { that._setPointsView(styles[state]) } else { that._resetPointsView(resetView) } } that._legendCallback([RESET_ITEM, APPLY_HOVER, APPLY_SELECTED, APPLY_SELECTED][state]); that._applyStyle(that._styles[styles[state]]) }, updateHover: function(x, y) { var that = this, currentNearestPoint = that._nearestPoint, point = that.isHovered() && that.lastHoverMode === NEAREST_POINT && that.getNeighborPoint(x, y); if (point !== currentNearestPoint && !(that.isSelected() && that.lastSelectionMode !== NONE_MODE)) { that._resetNearestPoint(); if (point) { point.setView(HOVER); that._nearestPoint = point } } }, _getMainAxisName: function() { return this._options.rotated ? "X" : "Y" }, areLabelsVisible: function() { return !_isDefined(this._options.maxLabelCount) || this._points.length <= this._options.maxLabelCount }, getLabelVisibility: function() { return this.areLabelsVisible() && this._options.label && this._options.label.visible }, customizePoint: function(point, pointData) { var customizeObject, pointOptions, customLabelOptions, customOptions, useLabelCustomOptions, usePointCustomOptions, that = this, options = that._options, customizePoint = options.customizePoint, customizeLabel = options.customizeLabel; if (customizeLabel && customizeLabel.call) { customizeObject = _extend({ seriesName: that.name }, pointData); customizeObject.series = that; customLabelOptions = customizeLabel.call(customizeObject, customizeObject); useLabelCustomOptions = customLabelOptions && !_isEmptyObject(customLabelOptions); customLabelOptions = useLabelCustomOptions ? _extend(true, {}, options.label, customLabelOptions) : null } if (customizePoint && customizePoint.call) { customizeObject = customizeObject || _extend({ seriesName: that.name }, pointData); customizeObject.series = that; customOptions = customizePoint.call(customizeObject, customizeObject); usePointCustomOptions = customOptions && !_isEmptyObject(customOptions) } if (useLabelCustomOptions || usePointCustomOptions) { pointOptions = that._parsePointOptions(that._preparePointOptions(customOptions), customLabelOptions || options.label, pointData); pointOptions.styles.useLabelCustomOptions = useLabelCustomOptions; pointOptions.styles.usePointCustomOptions = usePointCustomOptions; point.updateOptions(pointOptions) } }, show: function() { if (!this._visible) { this._changeVisibility(true) } }, hide: function() { if (this._visible) { this._changeVisibility(false) } }, _changeVisibility: function(visibility) { var that = this; that._visible = that._options.visible = visibility; that._updatePointsVisibility(); that.hidePointTooltip(); that._options.visibilityChanged() }, _updatePointsVisibility: _noop, hideLabels: function() { _each(this._points, function(_, point) { point._label.hide() }) }, _parsePointOptions: function(pointOptions, labelOptions, data) { var that = this, options = that._options, styles = that._createPointStyles(pointOptions, data), parsedOptions = _extend({}, pointOptions, { type: options.type, rotated: options.rotated, styles: styles, widgetType: options.widgetType, visibilityChanged: options.visibilityChanged }); parsedOptions.label = getLabelOptions(labelOptions, styles.normal.fill); if (that.areErrorBarsVisible()) { parsedOptions.errorBars = options.valueErrorBar } return parsedOptions }, _preparePointOptions: function(customOptions) { var pointOptions = this._getOptionsForPoint(); return customOptions ? mergePointOptions(pointOptions, customOptions) : pointOptions }, _getMarkerGroupOptions: function() { return _extend(false, {}, this._getOptionsForPoint(), { hoverStyle: {}, selectionStyle: {} }) }, _resample: function(ticksInterval, min, max, isDefinedMinMax) { var pointData, minTick, that = this, fusionPoints = [], nowIndexTicks = 0, lastPointIndex = 0, state = 0, originalPoints = that.getAllPoints(); function addFirstFusionPoint(point) { fusionPoints.push(point); minTick = point.argument; if (isDefinedMinMax) { if (point.argument < min) { state = 1 } else { if (point.argument > max) { state = 2 } else { state = 0 } } } } if (that.argumentAxisType === DISCRETE || that.valueAxisType === DISCRETE) { return _map(originalPoints, function(point, index) { if (index % ticksInterval === 0) { return point } point.setInvisibility(); return null }) } that._aggregatedPoints = that._aggregatedPoints || []; _each(originalPoints, function(_, point) { point.setInvisibility(); if (!fusionPoints.length) { addFirstFusionPoint(point) } else { if (!state && Math.abs(minTick - point.argument) < ticksInterval) { fusionPoints.push(point) } else { if (!(1 === state && point.argument < min) && !(2 === state && point.argument > max)) { pointData = that._fusionPoints(fusionPoints, minTick, nowIndexTicks); nowIndexTicks++; if (that._createPoint(pointData, that._aggregatedPoints, lastPointIndex)) { lastPointIndex++ } fusionPoints = []; addFirstFusionPoint(point) } } } }); if (fusionPoints.length) { pointData = that._fusionPoints(fusionPoints, minTick, nowIndexTicks); if (that._createPoint(pointData, that._aggregatedPoints, lastPointIndex)) { lastPointIndex++ } } that._correctPointsLength(lastPointIndex, that._aggregatedPoints); that._endUpdateData(); return that._aggregatedPoints }, canRenderCompleteHandle: function() { var result = this._canRenderCompleteHandle; delete this._canRenderCompleteHandle; return !!result }, isHovered: function() { return !!(1 & this.fullState) }, isSelected: function() { return !!(2 & this.fullState) }, isVisible: function() { return this._visible }, getAllPoints: function() { return (this._originalPoints || []).slice() }, getPointByPos: function(pos) { return (this._points || [])[pos] }, getVisiblePoints: function() { return (this._drawnPoints || []).slice() }, selectPoint: function(point) { if (!point.isSelected()) { setPointSelectedState(point, this._legendCallback); this._eventPipe({ action: POINT_SELECT, target: point }); this._eventTrigger(POINT_SELECTION_CHANGED, { target: point }) } }, deselectPoint: function(point) { if (point.isSelected()) { releasePointSelectedState(point, this._legendCallback); this._eventPipe({ action: POINT_DESELECT, target: point }); this._eventTrigger(POINT_SELECTION_CHANGED, { target: point }) } }, hover: function(mode) { var that = this, eventTrigger = that._eventTrigger; if (that.isHovered()) { return } that.lastHoverMode = _normalizeEnum(mode || that._options.hoverMode); that.fullState = that.fullState | HOVER_STATE; that._changeStyle(that.lastHoverMode, void 0, that.isSelected() && that.lastSelectionMode !== NONE_MODE); eventTrigger(SERIES_HOVER_CHANGED, { target: that }) }, clearHover: function() { var that = this, eventTrigger = that._eventTrigger; if (!that.isHovered()) { return } that._resetNearestPoint(); that.fullState = that.fullState & ~HOVER_STATE; that._changeStyle(that.lastHoverMode, HOVER, that.isSelected() && that.lastSelectionMode !== NONE_MODE); eventTrigger(SERIES_HOVER_CHANGED, { target: that }) }, hoverPoint: function(point) { var that = this; if (!point.isHovered()) { point.clearHover(); setPointHoverState(point, that._legendCallback); that._canChangeView() && that._applyStyle(that._styles.hover); that._eventPipe({ action: POINT_HOVER, target: point }); that._eventTrigger(POINT_HOVER_CHANGED, { target: point }) } }, clearPointHover: function() { var that = this; that.getPoints().some(function(currentPoint) { if (currentPoint.isHovered()) { releasePointHoverState(currentPoint, that._legendCallback); that._canChangeView() && that._applyStyle(that._styles.normal); that._eventPipe({ action: CLEAR_POINT_HOVER, target: currentPoint }); that._eventTrigger(POINT_HOVER_CHANGED, { target: currentPoint }); return true } return false }) }, showPointTooltip: function(point) { triggerEvent(this._extGroups.seriesGroup, new _Event("showpointtooltip"), point) }, hidePointTooltip: function(point) { triggerEvent(this._extGroups.seriesGroup, new _Event("hidepointtooltip"), point) }, select: function() { var that = this; if (!that.isSelected()) { that._setSelectedState(that._options.selectionMode); that._eventPipe({ action: SERIES_SELECT, target: that }); that._group.toForeground(); that._eventTrigger(SERIES_SELECTION_CHANGED, { target: that }) } }, clearSelection: function() { var that = this; if (that.isSelected()) { that._releaseSelectedState(); that._eventTrigger(SERIES_SELECTION_CHANGED, { target: that }) } }, getPointsByArg: function(arg) { return this.pointsByArgument[arg.valueOf()] || [] }, getPointsByKeys: function(arg) { return this.getPointsByArg(arg) }, notify: function(data) { var that = this, action = data.action, seriesModes = that._seriesModes, target = data.target, targetOptions = target.getOptions(), pointHoverMode = _normalizeEnum(targetOptions.hoverMode), selectionModeOfPoint = _normalizeEnum(targetOptions.selectionMode); if (action === POINT_HOVER) { that._hoverPointHandler(target, pointHoverMode, data.notifyLegend) } else { if (action === CLEAR_POINT_HOVER) { that._clearPointHoverHandler(target, pointHoverMode, data.notifyLegend) } else { if (action === SERIES_SELECT) { target !== that && "single" === seriesModes.seriesSelectionMode && that.clearSelection() } else { if (action === POINT_SELECT) { if ("single" === seriesModes.pointSelectionMode) { that.getPoints().some(function(currentPoint) { if (currentPoint !== target && currentPoint.isSelected()) { that.deselectPoint(currentPoint); return true } return false }) } that._selectPointHandler(target, selectionModeOfPoint) } else { if (action === POINT_DESELECT) { that._deselectPointHandler(target, selectionModeOfPoint) } } } } } }, _selectPointHandler: function(target, mode) { var that = this; if (mode === ALL_SERIES_POINTS) { target.series === that && that._setPointsView(SELECTION, target) } else { if (mode === ALL_ARGUMENT_POINTS) { that.getPointsByKeys(target.argument, target.argumentIndex).forEach(function(currentPoint) { currentPoint !== target && currentPoint.setView(SELECTION) }) } } }, _deselectPointHandler: function(target, mode) { if (mode === ALL_SERIES_POINTS) { target.series === this && this._resetPointsView(SELECTION, target) } else { if (mode === ALL_ARGUMENT_POINTS) { this.getPointsByKeys(target.argument, target.argumentIndex).forEach(function(currentPoint) { currentPoint !== target && currentPoint.resetView(SELECTION) }) } } }, _hoverPointHandler: function(target, mode, notifyLegend) { var that = this; if (target.series !== that && mode === ALL_ARGUMENT_POINTS) { that.getPointsByKeys(target.argument, target.argumentIndex).forEach(function(currentPoint) { currentPoint.setView(HOVER) }); notifyLegend && that._legendCallback(target) } else { if (mode === ALL_SERIES_POINTS && target.series === that) { that._setPointsView(HOVER, target) } } }, _clearPointHoverHandler: function(target, mode, notifyLegend) { var that = this; if (mode === ALL_ARGUMENT_POINTS) { target.series !== that && that.getPointsByKeys(target.argument, target.argumentIndex).forEach(function(currentPoint) { currentPoint.resetView(HOVER) }); notifyLegend && that._legendCallback(target) } else { if (mode === ALL_SERIES_POINTS && target.series === that) { that._resetPointsView(HOVER, target) } } }, _deletePoints: function() { var that = this; that._disposePoints(that._originalPoints); that._disposePoints(that._aggregatedPoints); that._disposePoints(that._oldPoints); that._points = that._oldPoints = that._aggregatedPoints = that._originalPoints = that._drawnPoints = null }, _deleteTrackers: function() { var that = this; _each(that._trackers || [], function(_, tracker) { tracker.remove() }); that._trackersGroup && that._trackersGroup.dispose(); that._trackers = that._trackersGroup = null }, dispose: function() { var that = this; that._deletePoints(); that._group.dispose(); that._labelsGroup && that._labelsGroup.dispose(); that._errorBarGroup && that._errorBarGroup.dispose(); that._deleteTrackers(); that._group = that._extGroups = that._markersGroup = that._elementsGroup = that._bordersGroup = that._labelsGroup = that._errorBarGroup = that._graphics = that._rangeData = that._renderer = that._styles = that._options = that._pointOptions = that._drawnPoints = that._aggregatedPoints = that.pointsByArgument = that._segments = that._prevSeries = null }, correctPosition: _noop, drawTrackers: _noop, getNeighborPoint: _noop, areErrorBarsVisible: _noop, getColor: function() { return this.getLegendStyles().normal.fill }, getOpacity: function() { return this._options.opacity }, getStackName: function() { return "stackedbar" === this.type || "fullstackedbar" === this.type ? this._stackName : null }, getPointByCoord: function(x, y) { var point = this.getNeighborPoint(x, y); return point && point.coordsIn(x, y) ? point : null }, getValueAxis: function() { return this._valueAxis }, getArgumentAxis: function() { return this._argumentAxis } } }, /*!********************************************!*\ !*** ./js/viz/series/points/base_point.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../../core/renderer */ 9), mixins = {}, statesConsts = __webpack_require__( /*! ../../components/consts */ 527).states, symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), barPoint = __webpack_require__( /*! ./bar_point */ 531), bubblePoint = __webpack_require__( /*! ./bubble_point */ 532), piePoint = __webpack_require__( /*! ./pie_point */ 533), rangeSymbolPoint = __webpack_require__( /*! ./range_symbol_point */ 534), rangeBarPoint = __webpack_require__( /*! ./range_bar_point */ 535), candlestickPoint = __webpack_require__( /*! ./candlestick_point */ 536), stockPoint = __webpack_require__( /*! ./stock_point */ 537), polarPoints = __webpack_require__( /*! ./polar_point */ 538), _normalizeEnum = __webpack_require__( /*! ../../core/utils */ 509).normalizeEnum, extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, _each = $.each, _extend = extend, commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), _isDefined = commonUtils.isDefined, _noop = commonUtils.noop, SYMBOL_POINT = "symbolPoint", POLAR_SYMBOL_POINT = "polarSymbolPoint", BAR_POINT = "barPoint", POLAR_BAR_POINT = "polarBarPoint", PIE_POINT = "piePoint", SELECTED_STATE = statesConsts.selectedMark, HOVER_STATE = statesConsts.hoverMark, NORMAL_STATE = statesConsts.normalMark, HOVER = statesConsts.hover, NORMAL = statesConsts.normal, SELECTION = statesConsts.selection, pointTypes = { chart: { scatter: SYMBOL_POINT, line: SYMBOL_POINT, spline: SYMBOL_POINT, stepline: SYMBOL_POINT, stackedline: SYMBOL_POINT, fullstackedline: SYMBOL_POINT, stackedspline: SYMBOL_POINT, fullstackedspline: SYMBOL_POINT, stackedsplinearea: SYMBOL_POINT, fullstackedsplinearea: SYMBOL_POINT, area: SYMBOL_POINT, splinearea: SYMBOL_POINT, steparea: SYMBOL_POINT, stackedarea: SYMBOL_POINT, fullstackedarea: SYMBOL_POINT, rangearea: "rangeSymbolPoint", bar: BAR_POINT, stackedbar: BAR_POINT, fullstackedbar: BAR_POINT, rangebar: "rangeBarPoint", bubble: "bubblePoint", stock: "stockPoint", candlestick: "candlestickPoint" }, pie: { pie: PIE_POINT, doughnut: PIE_POINT, donut: PIE_POINT }, polar: { scatter: POLAR_SYMBOL_POINT, line: POLAR_SYMBOL_POINT, area: POLAR_SYMBOL_POINT, bar: POLAR_BAR_POINT, stackedbar: POLAR_BAR_POINT } }; function isNoneMode(mode) { return "none" === _normalizeEnum(mode) } function Point(series, dataItem, options) { this.fullState = NORMAL_STATE; this.series = series; this.update(dataItem, options); this._viewCounters = { hover: 0, selection: 0 }; this._emptySettings = { fill: null, stroke: null, dashStyle: null } } exports.Point = Point; mixins.symbolPoint = symbolPoint; mixins.barPoint = barPoint; mixins.bubblePoint = bubblePoint; mixins.piePoint = piePoint; mixins.rangeSymbolPoint = rangeSymbolPoint; mixins.rangeBarPoint = rangeBarPoint; mixins.candlestickPoint = candlestickPoint; mixins.stockPoint = stockPoint; mixins.polarSymbolPoint = polarPoints.polarSymbolPoint; mixins.polarBarPoint = polarPoints.polarBarPoint; Point.prototype = { constructor: Point, getColor: function() { if (!this.hasValue() && !this._styles.usePointCustomOptions) { this.series.customizePoint(this, this._dataItem) } return this._styles.normal.fill || this.series.getColor() }, _getStyle: function() { return this._styles[this._currentStyle || "normal"] }, update: function(dataItem, options) { this.updateOptions(options); this.updateData(dataItem) }, updateData: function(dataItem) { var that = this; that.argument = that.initialArgument = that.originalArgument = dataItem.argument; that.tag = dataItem.tag; that.index = dataItem.index; this._dataItem = dataItem; that.lowError = dataItem.lowError; that.highError = dataItem.highError; that._updateData(dataItem); !that.hasValue() && that.setInvisibility(); that._fillStyle(); that._updateLabelData() }, deleteMarker: function() { var that = this; if (that.graphic) { that.graphic.dispose() } that.graphic = null }, _drawErrorBar: _noop, draw: function(renderer, groups, animationEnabled, firstDrawing) { var that = this; if (that._needDeletingOnDraw) { that.deleteMarker(); that._needDeletingOnDraw = false } if (that._needClearingOnDraw) { that.clearMarker(); that._needClearingOnDraw = false } if (!that._hasGraphic()) { that._getMarkerVisibility() && that._drawMarker(renderer, groups.markers, animationEnabled, firstDrawing) } else { that._updateMarker(animationEnabled, this._getStyle(), groups.markers) } that._drawLabel(); that._drawErrorBar(renderer, groups.errorBars, animationEnabled); return that }, applyStyle: function(style, callback) { var that = this; that._currentStyle = style; if (that.graphic) { if ("normal" === style) { that.clearMarker() } else { that.graphic.toForeground() } that._updateMarker(true, that._styles[style], void 0, callback) } return that }, _getViewStyle: function() { var state = NORMAL_STATE, fullState = this.fullState, styles = [NORMAL, HOVER, SELECTION, SELECTION]; if (this._viewCounters.hover) { state |= HOVER_STATE } if (this._viewCounters.selection) { state |= SELECTED_STATE } if (isNoneMode(this.getOptions().selectionMode)) { fullState &= ~SELECTED_STATE } if (isNoneMode(this.getOptions().hoverMode)) { fullState &= ~HOVER_STATE } state |= fullState; return styles[state] }, applyView: function(legendCallback) { var style = this._getViewStyle(); this.applyStyle(style, legendCallback) }, setView: function(style) { this._viewCounters[style]++; this.applyView() }, resetView: function(style) { --this._viewCounters[style]; if (this._viewCounters[style] < 0) { var debug = __webpack_require__( /*! ../../../core/utils/console */ 13).debug; debug.assert(false, "incorrect view style couinter " + this._viewCounters[style] + " " + style) } this.applyView() }, releaseHoverState: function() { var that = this; if (that.graphic && !that.isSelected()) { that.graphic.toBackground() } }, select: function() { this.series.selectPoint(this) }, clearSelection: function() { this.series.deselectPoint(this) }, hover: function() { this.series.hoverPoint(this) }, clearHover: function() { this.series.clearPointHover() }, showTooltip: function() { this.series.showPointTooltip(this) }, hideTooltip: function() { this.series.hidePointTooltip(this) }, _checkLabelsChanging: function(oldType, newType) { var isNewRange = ~newType.indexOf("range"), isOldRange = ~oldType.indexOf("range"); return isOldRange && !isNewRange || !isOldRange && isNewRange }, updateOptions: function(newOptions) { if (!newOptions) { return } var that = this, oldOptions = that._options, widgetType = newOptions.widgetType, oldType = oldOptions && oldOptions.type, newType = newOptions.type, newPointTypeMixin = pointTypes[widgetType][newType]; if (oldType !== newType) { that._needDeletingOnDraw = true; that._needClearingOnDraw = false; if (oldType) { that._checkLabelsChanging(oldType, newType) && that.deleteLabel(); that._resetType(mixins[pointTypes[oldType]]) } that._setType(mixins[newPointTypeMixin]) } else { that._needDeletingOnDraw = that._checkSymbol(oldOptions, newOptions); that._needClearingOnDraw = that._checkCustomize(oldOptions, newOptions) } that._options = newOptions; that._fillStyle(); that._updateLabelOptions(newPointTypeMixin) }, translate: function() { this.hasValue() && this._translate() }, _checkCustomize: function(oldOptions, newOptions) { return oldOptions.styles.usePointCustomOptions && !newOptions.styles.usePointCustomOptions }, _getCustomLabelVisibility: function() { return this._styles.useLabelCustomOptions ? !!this._options.label.visible : null }, getBoundingRect: function() { return this._getGraphicBBox() }, _resetType: function(methods) { for (var methodName in methods) { delete this[methodName] } }, _setType: function(methods) { for (var methodName in methods) { this[methodName] = methods[methodName] } }, isInVisibleArea: function() { return this.inVisibleArea }, isSelected: function() { return !!(this.fullState & SELECTED_STATE) }, isHovered: function() { return !!(this.fullState & HOVER_STATE) }, getOptions: function() { return this._options }, animate: function(complete, settings, partitionDuration) { if (!this.graphic) { complete && complete(); return } this.graphic.animate(settings, { partitionDuration: partitionDuration }, complete) }, getCoords: function(min) { var that = this; if (!min) { return { x: that.x, y: that.y } } if (!that._options.rotated) { return { x: that.x, y: that.minY } } return { x: that.minX, y: that.y } }, getDefaultCoords: function() { var that = this; return !that._options.rotated ? { x: that.x, y: that.defaultY } : { x: that.defaultX, y: that.y } }, _getVisibleArea: function() { return this.series.getVisibleArea() }, _getArgTranslator: function() { return this.series.getArgumentAxis().getTranslator() }, _getValTranslator: function() { return this.series.getValueAxis().getTranslator() }, _calculateVisibility: function(x, y, width, height) { var that = this, visibleArea = that._getVisibleArea(), rotated = that._options.rotated; if (visibleArea.minX > x + (width || 0) || visibleArea.maxX < x || visibleArea.minY > y + (height || 0) || visibleArea.maxY < y || rotated && _isDefined(width) && 0 !== width && (visibleArea.minX === x + width || visibleArea.maxX === x) || !rotated && _isDefined(height) && 0 !== height && (visibleArea.minY === y + height || visibleArea.maxY === y)) { that.inVisibleArea = false } else { that.inVisibleArea = true } }, hasValue: function() { return null !== this.value && null !== this.minValue }, correctPosition: _noop, correctRadius: _noop, correctLabelRadius: _noop, getCrosshairData: _noop, getPointRadius: _noop, _populatePointShape: _noop, _checkSymbol: _noop, getMarkerCoords: _noop, hide: _noop, show: _noop, hideMarker: _noop, setInvisibility: _noop, clearVisibility: _noop, isVisible: _noop, resetCorrection: _noop, correctValue: _noop, resetValue: _noop, setPercentValue: _noop, correctCoordinates: _noop, coordsIn: _noop, getTooltipParams: _noop, setLabelEllipsis: _noop, setLabelTrackerData: _noop, updateLabelCoord: _noop, drawLabel: _noop, correctLabelPosition: _noop, setMaxLabelLength: _noop, getMinValue: _noop, getMaxValue: _noop, dispose: function() { var that = this; that.deleteMarker(); that.deleteLabel(); that._errorBar && this._errorBar.dispose(); that._options = that._styles = that.series = that._errorBar = null }, getTooltipFormatObject: function(tooltip) { var that = this, tooltipFormatObject = that._getFormatObject(tooltip), sharedTooltipValuesArray = [], tooltipStackPointsFormatObject = []; if (that.stackPoints) { _each(that.stackPoints, function(_, point) { if (!point.isVisible()) { return } var formatObject = point._getFormatObject(tooltip); tooltipStackPointsFormatObject.push(formatObject); sharedTooltipValuesArray.push(formatObject.seriesName + ": " + formatObject.valueText) }); _extend(tooltipFormatObject, { points: tooltipStackPointsFormatObject, valueText: sharedTooltipValuesArray.join("\n"), stackName: that.stackPoints.stackName }) } return tooltipFormatObject }, setHole: function(holeValue, position) { var that = this, minValue = isFinite(that.minValue) ? that.minValue : 0; if (_isDefined(holeValue)) { if ("left" === position) { that.leftHole = that.value - holeValue; that.minLeftHole = minValue - holeValue } else { that.rightHole = that.value - holeValue; that.minRightHole = minValue - holeValue } } }, resetHoles: function() { this.leftHole = null; this.minLeftHole = null; this.rightHole = null; this.minRightHole = null }, getLabel: function() { return this._label }, getLabels: function() { return [this._label] } } }, /*!*************************************!*\ !*** ./js/viz/components/consts.js ***! \*************************************/ function(module, exports) { module.exports = { events: { mouseover: "mouseover", mouseout: "mouseout", mousemove: "mousemove", touchstart: "touchstart", touchmove: "touchmove", touchend: "touchend", mousedown: "mousedown", mouseup: "mouseup", click: "click", selectSeries: "selectseries", deselectSeries: "deselectseries", selectPoint: "selectpoint", deselectPoint: "deselectpoint", showPointTooltip: "showpointtooltip", hidePointTooltip: "hidepointtooltip" }, states: { hover: "hover", normal: "normal", selection: "selection", normalMark: 0, hoverMark: 1, selectedMark: 2, applyHover: "applyHover", applySelected: "applySelected", resetItem: "resetItem" }, pieLabelIndent: 30, pieLabelSpacing: 10, pieSeriesSpacing: 4 } }, /*!**********************************************!*\ !*** ./js/viz/series/points/symbol_point.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, labelModule = __webpack_require__( /*! ./label */ 529), _extend = extend, _isDefined = commonUtils.isDefined, _normalizeEnum = __webpack_require__( /*! ../../core/utils */ 509).normalizeEnum, _math = Math, _round = _math.round, _floor = _math.floor, _ceil = _math.ceil, DEFAULT_IMAGE_WIDTH = 20, DEFAULT_IMAGE_HEIGHT = 20, LABEL_OFFSET = 10, CANVAS_POSITION_DEFAULT = "canvas_position_default"; function getSquareMarkerCoords(radius) { return [-radius, -radius, radius, -radius, radius, radius, -radius, radius, -radius, -radius] } function getPolygonMarkerCoords(radius) { var r = _ceil(radius); return [-r, 0, 0, -r, r, 0, 0, r, -r, 0] } function getCrossMarkerCoords(radius) { var r = _ceil(radius), floorHalfRadius = _floor(r / 2), ceilHalfRadius = _ceil(r / 2); return [-r, -floorHalfRadius, -floorHalfRadius, -r, 0, -ceilHalfRadius, floorHalfRadius, -r, r, -floorHalfRadius, ceilHalfRadius, 0, r, floorHalfRadius, floorHalfRadius, r, 0, ceilHalfRadius, -floorHalfRadius, r, -r, floorHalfRadius, -ceilHalfRadius, 0] } function getTriangleDownMarkerCoords(radius) { return [-radius, -radius, radius, -radius, 0, radius, -radius, -radius] } function getTriangleUpMarkerCoords(radius) { return [-radius, radius, radius, radius, 0, -radius, -radius, radius] } module.exports = { deleteLabel: function() { this._label.dispose(); this._label = null }, _hasGraphic: function() { return this.graphic }, clearVisibility: function() { var that = this, graphic = that.graphic; if (graphic && graphic.attr("visibility")) { graphic.attr({ visibility: null }) } that._label.clearVisibility() }, isVisible: function() { return this.inVisibleArea && this.series.isVisible() }, setInvisibility: function() { var that = this, graphic = that.graphic; if (graphic && "hidden" !== graphic.attr("visibility")) { graphic.attr({ visibility: "hidden" }) } that._errorBar && that._errorBar.attr({ visibility: "hidden" }); that._label.hide() }, clearMarker: function() { var graphic = this.graphic; graphic && graphic.attr(this._emptySettings) }, _createLabel: function() { this._label = new labelModule.Label({ renderer: this.series._renderer, labelsGroup: this.series._labelsGroup, point: this }) }, _updateLabelData: function() { this._label.setData(this._getLabelFormatObject()) }, _updateLabelOptions: function() { !this._label && this._createLabel(); this._label.setOptions(this._options.label) }, _checkImage: function(image) { return _isDefined(image) && ("string" === typeof image || _isDefined(image.url)) }, _fillStyle: function() { this._styles = this._options.styles }, _checkSymbol: function(oldOptions, newOptions) { var oldSymbol = oldOptions.symbol, newSymbol = newOptions.symbol, symbolChanged = "circle" === oldSymbol && "circle" !== newSymbol || "circle" !== oldSymbol && "circle" === newSymbol, imageChanged = this._checkImage(oldOptions.image) !== this._checkImage(newOptions.image); return !!(symbolChanged || imageChanged) }, _populatePointShape: function(symbol, radius) { switch (symbol) { case "square": return getSquareMarkerCoords(radius); case "polygon": return getPolygonMarkerCoords(radius); case "triangle": case "triangleDown": return getTriangleDownMarkerCoords(radius); case "triangleUp": return getTriangleUpMarkerCoords(radius); case "cross": return getCrossMarkerCoords(radius) } }, correctValue: function(correction) { var that = this; if (that.hasValue()) { that.value = that.initialValue + correction; that.minValue = correction } }, resetCorrection: function() { this.value = this.initialValue; this.minValue = CANVAS_POSITION_DEFAULT }, resetValue: function() { var that = this; if (that.hasValue()) { that.value = that.initialValue = 0; that.minValue = 0; that._label.setDataField("value", that.value) } }, _getTranslates: function(animationEnabled) { var translateX = this.x, translateY = this.y; if (animationEnabled) { if (this._options.rotated) { translateX = this.defaultX } else { translateY = this.defaultY } } return { x: translateX, y: translateY } }, _createImageMarker: function(renderer, settings, options) { var width = options.width || DEFAULT_IMAGE_WIDTH, height = options.height || DEFAULT_IMAGE_HEIGHT; return renderer.image(-_round(.5 * width), -_round(.5 * height), width, height, options.url ? options.url.toString() : options.toString(), "center").attr({ translateX: settings.translateX, translateY: settings.translateY, visibility: settings.visibility }) }, _createSymbolMarker: function(renderer, pointSettings) { var marker, symbol = this._options.symbol; if ("circle" === symbol) { delete pointSettings.points; marker = renderer.circle().attr(pointSettings) } else { if ("square" === symbol || "polygon" === symbol || "triangle" === symbol || "triangleDown" === symbol || "triangleUp" === symbol || "cross" === symbol) { marker = renderer.path([], "area").attr(pointSettings).sharp() } } return marker }, _createMarker: function(renderer, group, image, settings) { var that = this, marker = that._checkImage(image) ? that._createImageMarker(renderer, settings, image) : that._createSymbolMarker(renderer, settings); if (marker) { marker.data({ "chart-data-point": that }).append(group) } return marker }, _getSymbolBBox: function(x, y, r) { return { x: x - r, y: y - r, width: 2 * r, height: 2 * r } }, _getImageBBox: function(x, y) { var image = this._options.image, width = image.width || DEFAULT_IMAGE_WIDTH, height = image.height || DEFAULT_IMAGE_HEIGHT; return { x: x - _round(width / 2), y: y - _round(height / 2), width: width, height: height } }, _getGraphicBBox: function() { var bBox, that = this, options = that._options, x = that.x, y = that.y; if (options.visible) { bBox = that._checkImage(options.image) ? that._getImageBBox(x, y) : that._getSymbolBBox(x, y, options.styles.normal.r) } else { bBox = { x: x, y: y, width: 0, height: 0 } } return bBox }, _isLabelInsidePoint: commonUtils.noop, _getShiftLabelCoords: function(label) { var coord = this._addLabelAlignmentAndOffset(label, this._getLabelCoords(label)); return this._checkLabelPosition(label, coord) }, _drawLabel: function() { var that = this, customVisibility = that._getCustomLabelVisibility(), label = that._label; if (that._showForZeroValues() && that.hasValue() && false !== customVisibility && (that.series.getLabelVisibility() || customVisibility)) { label.show() } else { label.hide() } }, correctLabelPosition: function(label) { var coord, that = this; if (!that._isLabelInsidePoint(label)) { coord = that._getShiftLabelCoords(label); label.setFigureToDrawConnector(that._getLabelConnector(label.pointPosition)); label.shift(_round(coord.x), _round(coord.y)) } }, _showForZeroValues: function() { return true }, _getLabelConnector: function(pointPosition) { var bBox = this._getGraphicBBox(pointPosition), w2 = bBox.width / 2, h2 = bBox.height / 2; return { x: bBox.x + w2, y: bBox.y + h2, r: this._options.visible ? Math.max(w2, h2) : 0 } }, _getPositionFromLocation: function() { return { x: this.x, y: this.y } }, _isPointInVisibleArea: function(visibleArea, graphicBBox) { return visibleArea.minX <= graphicBBox.x + graphicBBox.width && visibleArea.maxX >= graphicBBox.x && visibleArea.minY <= graphicBBox.y + graphicBBox.height && visibleArea.maxY >= graphicBBox.y }, _checkLabelPosition: function(label, coord) { var that = this, visibleArea = that._getVisibleArea(), labelBBox = label.getBoundingRect(), graphicBBox = that._getGraphicBBox(label.pointPosition), offset = LABEL_OFFSET; if (that._isPointInVisibleArea(visibleArea, graphicBBox)) { if (!that._options.rotated) { if (visibleArea.minX > coord.x) { coord.x = visibleArea.minX } if (visibleArea.maxX < coord.x + labelBBox.width) { coord.x = visibleArea.maxX - labelBBox.width } if (visibleArea.minY > coord.y) { coord.y = graphicBBox.y + graphicBBox.height + offset } if (visibleArea.maxY < coord.y + labelBBox.height) { coord.y = graphicBBox.y - labelBBox.height - offset } } else { if (visibleArea.minX > coord.x) { coord.x = graphicBBox.x + graphicBBox.width + offset } if (visibleArea.maxX < coord.x + labelBBox.width) { coord.x = graphicBBox.x - offset - labelBBox.width } if (visibleArea.minY > coord.y) { coord.y = visibleArea.minY } if (visibleArea.maxY < coord.y + labelBBox.height) { coord.y = visibleArea.maxY - labelBBox.height } } } return coord }, _addLabelAlignmentAndOffset: function(label, coord) { var labelBBox = label.getBoundingRect(), labelOptions = label.getLayoutOptions(); if (!this._options.rotated) { if ("left" === labelOptions.alignment) { coord.x += labelBBox.width / 2 } else { if ("right" === labelOptions.alignment) { coord.x -= labelBBox.width / 2 } } } coord.x += labelOptions.horizontalOffset; coord.y += labelOptions.verticalOffset; return coord }, _getLabelCoords: function(label) { return this._getLabelCoordOfPosition(label, this._getLabelPosition(label.pointPosition)) }, _getLabelCoordOfPosition: function(label, position) { var that = this, labelBBox = label.getBoundingRect(), graphicBBox = that._getGraphicBBox(label.pointPosition), offset = LABEL_OFFSET, centerY = graphicBBox.height / 2 - labelBBox.height / 2, centerX = graphicBBox.width / 2 - labelBBox.width / 2, x = graphicBBox.x, y = graphicBBox.y; switch (position) { case "left": x -= labelBBox.width + offset; y += centerY; break; case "right": x += graphicBBox.width + offset; y += centerY; break; case "top": x += centerX; y -= labelBBox.height + offset; break; case "bottom": x += centerX; y += graphicBBox.height + offset; break; case "inside": x += centerX; y += centerY } return { x: x, y: y } }, _drawMarker: function(renderer, group, animationEnabled) { var that = this, options = that._options, translates = that._getTranslates(animationEnabled), style = that._getStyle(); that.graphic = that._createMarker(renderer, group, options.image, _extend({ translateX: translates.x, translateY: translates.y, points: that._populatePointShape(options.symbol, style.r) }, style)) }, _getErrorBarSettings: function() { return { visibility: "visible" } }, _drawErrorBar: function(renderer, group) { if (!this._options.errorBars) { return } var settings, that = this, options = that._options, errorBarOptions = options.errorBars, points = [], pos = that._errorBarPos, high = that._highErrorCoord, low = that._lowErrorCoord, displayMode = _normalizeEnum(errorBarOptions.displayMode), isHighDisplayMode = "high" === displayMode, isLowDisplayMode = "low" === displayMode, edgeLength = _floor(parseInt(errorBarOptions.edgeLength) / 2), highErrorOnly = (isHighDisplayMode || !_isDefined(low)) && _isDefined(high) && !isLowDisplayMode, lowErrorOnly = (isLowDisplayMode || !_isDefined(high)) && _isDefined(low) && !isHighDisplayMode; highErrorOnly && (low = that._baseErrorBarPos); lowErrorOnly && (high = that._baseErrorBarPos); if ("none" !== displayMode && _isDefined(high) && _isDefined(low) && _isDefined(pos)) { !lowErrorOnly && points.push([pos - edgeLength, high, pos + edgeLength, high]); points.push([pos, high, pos, low]); !highErrorOnly && points.push([pos + edgeLength, low, pos - edgeLength, low]); options.rotated && $.each(points, function(_, p) { p.reverse() }); settings = that._getErrorBarSettings(errorBarOptions); if (!that._errorBar) { that._errorBar = renderer.path(points, "line").attr(settings).append(group) } else { settings.points = points; that._errorBar.attr(settings) } } else { that._errorBar && that._errorBar.attr({ visibility: "hidden" }) } }, getTooltipParams: function() { var that = this, graphic = that.graphic; return { x: that.x, y: that.y, offset: graphic ? graphic.getBBox().height / 2 : 0 } }, setPercentValue: function(total, fullStacked, leftHoleTotal, rightHoleTotal) { var that = this, valuePercent = that.value / total || 0, minValuePercent = that.minValue / total || 0, percent = valuePercent - minValuePercent; that._label.setDataField("percent", percent); that._label.setDataField("total", total); if (that.series.isFullStackedSeries() && that.hasValue()) { if (that.leftHole) { that.leftHole /= total - leftHoleTotal; that.minLeftHole /= total - leftHoleTotal } if (that.rightHole) { that.rightHole /= total - rightHoleTotal; that.minRightHole /= total - rightHoleTotal } that.value = valuePercent; that.minValue = !minValuePercent ? that.minValue : minValuePercent } }, _storeTrackerR: function() { var minTrackerSize, that = this, navigator = window.navigator, r = that._options.styles.normal.r; navigator = that.__debug_navigator || navigator; that.__debug_browserNavigator = navigator; minTrackerSize = "ontouchstart" in window || navigator.msPointerEnabled && navigator.msMaxTouchPoints || navigator.pointerEnabled && navigator.maxTouchPoints ? 20 : 6; that._options.trackerR = r < minTrackerSize ? minTrackerSize : r; return that._options.trackerR }, _translateErrorBars: function() { var that = this, options = that._options, rotated = options.rotated, errorBars = options.errorBars, translator = that._getValTranslator(); if (!errorBars) { return } _isDefined(that.lowError) && (that._lowErrorCoord = translator.translate(that.lowError)); _isDefined(that.highError) && (that._highErrorCoord = translator.translate(that.highError)); that._errorBarPos = _floor(rotated ? that.vy : that.vx); that._baseErrorBarPos = "stdDeviation" === errorBars.type ? that._lowErrorCoord + (that._highErrorCoord - that._lowErrorCoord) / 2 : rotated ? that.vx : that.vy }, _translate: function() { var that = this, valTranslator = that._getValTranslator(), argTranslator = that._getArgTranslator(); if (that._options.rotated) { that.vx = that.x = valTranslator.translate(that.value); that.vy = that.y = argTranslator.translate(that.argument); that.minX = valTranslator.translate(that.minValue); that.defaultX = valTranslator.translate(CANVAS_POSITION_DEFAULT) } else { that.vy = that.y = valTranslator.translate(that.value); that.vx = that.x = argTranslator.translate(that.argument); that.minY = valTranslator.translate(that.minValue); that.defaultY = valTranslator.translate(CANVAS_POSITION_DEFAULT) } that._translateErrorBars(); that._calculateVisibility(that.x, that.y) }, _updateData: function(data) { var that = this; that.value = that.initialValue = that.originalValue = data.value; that.minValue = that.initialMinValue = that.originalMinValue = _isDefined(data.minValue) ? data.minValue : CANVAS_POSITION_DEFAULT }, _getImageSettings: function(image) { return { href: image.url || image.toString(), width: image.width || DEFAULT_IMAGE_WIDTH, height: image.height || DEFAULT_IMAGE_HEIGHT } }, getCrosshairData: function() { var that = this, r = that._options.rotated, value = that.value, argument = that.argument; return { x: that.vx, y: that.vy, xValue: r ? value : argument, yValue: r ? argument : value, axis: that.series.axis } }, getPointRadius: function() { var extraSpace, style = this._getStyle(), options = this._options, r = style.r, symbol = options.symbol, isSquare = "square" === symbol, isTriangle = "triangle" === symbol || "triangleDown" === symbol || "triangleUp" === symbol; if (options.visible && !options.image && r) { extraSpace = style["stroke-width"] / 2; return (isSquare || isTriangle ? 1.4 * r : r) + extraSpace } return 0 }, _updateMarker: function(animationEnabled, style) { var settings, that = this, options = that._options, image = options.image, visibility = !that.isVisible() ? { visibility: "hidden" } : {}; if (that._checkImage(image)) { settings = _extend({}, { visibility: style.visibility }, visibility, that._getImageSettings(image)) } else { settings = _extend({}, style, visibility, { points: that._populatePointShape(options.symbol, style.r) }) } if (!animationEnabled) { settings.translateX = that.x; settings.translateY = that.y } that.graphic.attr(settings).sharp() }, _getLabelFormatObject: function() { var that = this; return { argument: that.initialArgument, value: that.initialValue, originalArgument: that.originalArgument, originalValue: that.originalValue, seriesName: that.series.name, lowErrorValue: that.lowError, highErrorValue: that.highError, point: that } }, _getLabelPosition: function() { var rotated = this._options.rotated; if (this.initialValue > 0) { return rotated ? "right" : "top" } else { return rotated ? "left" : "bottom" } }, _getFormatObject: function(tooltip) { var that = this, labelFormatObject = that._label.getData(); return _extend({}, labelFormatObject, { argumentText: tooltip.formatValue(that.initialArgument, "argument"), valueText: tooltip.formatValue(that.initialValue) }, _isDefined(labelFormatObject.percent) ? { percentText: tooltip.formatValue(labelFormatObject.percent, "percent") } : {}, _isDefined(labelFormatObject.total) ? { totalText: tooltip.formatValue(labelFormatObject.total) } : {}) }, _getMarkerVisibility: function() { return this._options.visible }, coordsIn: function(x, y) { var trackerRadius = this._storeTrackerR(); return x >= this.x - trackerRadius && x <= this.x + trackerRadius && y >= this.y - trackerRadius && y <= this.y + trackerRadius }, getMinValue: function() { var errorBarOptions = this._options.errorBars; if (errorBarOptions) { var displayMode = errorBarOptions.displayMode, lowValue = "high" === displayMode ? this.value : this.lowError, highValue = "low" === displayMode ? this.value : this.highError; return lowValue < highValue ? lowValue : highValue } else { return this.value } }, getMaxValue: function() { var errorBarOptions = this._options.errorBars; if (errorBarOptions) { var displayMode = errorBarOptions.displayMode, lowValue = "high" === displayMode ? this.value : this.lowError, highValue = "low" === displayMode ? this.value : this.highError; return lowValue > highValue ? lowValue : highValue } else { return this.value } } } }, /*!***************************************!*\ !*** ./js/viz/series/points/label.js ***! \***************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../../core/renderer */ 9), _format = __webpack_require__( /*! ../../core/format */ 530), vizUtils = __webpack_require__( /*! ../../core/utils */ 509), _degreesToRadians = vizUtils.degreesToRadians, _patchFontOptions = vizUtils.patchFontOptions, _math = Math, _round = _math.round, _floor = _math.floor, _getCosAndSin = vizUtils.getCosAndSin, _rotateBBox = vizUtils.rotateBBox, LABEL_BACKGROUND_PADDING_X = 8, LABEL_BACKGROUND_PADDING_Y = 4; function getClosestCoord(point, coords) { var closestCoord, closestDistance = 1 / 0; $.each(coords, function(_, coord) { var x = point[0] - coord[0], y = point[1] - coord[1], distance = x * x + y * y; if (distance < closestDistance) { closestDistance = distance; closestCoord = coord } }); return closestCoord } var barPointStrategy = { isLabelInside: function(labelPoint, figure) { return labelPoint.x >= figure.x && labelPoint.x <= figure.x + figure.width && labelPoint.y >= figure.y && labelPoint.y <= figure.y + figure.height }, prepareLabelPoints: function(points) { return points }, getFigureCenter: function(figure) { return [figure.x + figure.width / 2, figure.y + figure.height / 2] }, findFigurePoint: function(figure, labelPoint) { var figureCenter = barPointStrategy.getFigureCenter(figure), point = getClosestCoord(labelPoint, [ [figure.x, figureCenter[1]], [figureCenter[0], figure.y + figure.height], [figure.x + figure.width, figureCenter[1]], [figureCenter[0], figure.y] ]); return [_round(point[0]), _round(point[1])] } }; var symbolPointStrategy = { isLabelInside: function() { return false }, prepareLabelPoints: barPointStrategy.prepareLabelPoints, getFigureCenter: function(figure) { return [figure.x, figure.y] }, findFigurePoint: function(figure, labelPoint) { var angle = Math.atan2(figure.y - labelPoint[1], labelPoint[0] - figure.x); return [_round(figure.x + figure.r * Math.cos(angle)), _round(figure.y - figure.r * Math.sin(angle))] } }; var piePointStrategy = { isLabelInside: function(_0, _1, isOutside) { return !isOutside }, prepareLabelPoints: function(points, center, angle) { var rotatedPoints = [], x0 = center[0], y0 = center[1], cosSin = _getCosAndSin(angle || 0); $.each(points, function(_, point) { rotatedPoints.push([_round((point[0] - x0) * cosSin.cos + (point[1] - y0) * cosSin.sin + x0), _round(-(point[0] - x0) * cosSin.sin + (point[1] - y0) * cosSin.cos + y0)]) }); return rotatedPoints }, getFigureCenter: symbolPointStrategy.getFigureCenter, findFigurePoint: function(figure, labelPoint) { var x = figure.x + (figure.y - labelPoint[1]) / Math.tan(_degreesToRadians(figure.angle)), point = [figure.x, figure.y]; if (figure.x <= x && x <= labelPoint[0] || figure.x >= x && x >= labelPoint[0]) { point.push(_round(x), labelPoint[1]) } return point } }; function selectStrategy(figure) { return void 0 !== figure.angle && piePointStrategy || void 0 !== figure.r && symbolPointStrategy || barPointStrategy } function disposeItem(obj, field) { obj[field] && obj[field].dispose(); obj[field] = null } function checkBackground(background) { return background && (background.fill && "none" !== background.fill || background["stroke-width"] > 0 && background.stroke && "none" !== background.stroke) } function checkConnector(connector) { return connector && connector["stroke-width"] > 0 && connector.stroke && "none" !== connector.stroke } function formatText(data, options) { data.valueText = _format(data.value, options); data.argumentText = _format(data.argument, { format: options.argumentFormat, precision: options.argumentPrecision }); if (void 0 !== data.percent) { data.percentText = _format(data.percent, { format: { type: "percent", precision: options.format && options.format.percentPrecision || options.percentPrecision } }) } if (void 0 !== data.total) { data.totalText = _format(data.total, options) } if (void 0 !== data.openValue) { data.openValueText = _format(data.openValue, options) } if (void 0 !== data.closeValue) { data.closeValueText = _format(data.closeValue, options) } if (void 0 !== data.lowValue) { data.lowValueText = _format(data.lowValue, options) } if (void 0 !== data.highValue) { data.highValueText = _format(data.highValue, options) } if (void 0 !== data.reductionValue) { data.reductionValueText = _format(data.reductionValue, options) } return options.customizeText ? options.customizeText.call(data, data) : data.valueText } function Label(renderSettings) { this._renderer = renderSettings.renderer; this._container = renderSettings.labelsGroup; this._point = renderSettings.point } Label.prototype = { constructor: Label, _setVisibility: function(value, state) { this._group && this._group.attr({ visibility: value }); this._visible = state }, clearVisibility: function() { this._setVisibility(null, true) }, hide: function() { this._setVisibility("hidden", false) }, show: function() { var that = this; if (that._point.hasValue()) { that._draw(); that._point.correctLabelPosition(that) } }, isVisible: function() { return this._visible }, setColor: function(color) { this._color = color }, setOptions: function(options) { this._options = options }, setData: function(data) { this._data = data }, setDataField: function(fieldName, fieldValue) { this._data = this._data || {}; this._data[fieldName] = fieldValue }, getData: function() { return this._data }, setFigureToDrawConnector: function(figure) { this._figure = figure }, dispose: function() { var that = this; disposeItem(that, "_group"); that._data = that._options = that._textContent = that._visible = that._insideGroup = that._text = that._background = that._connector = that._figure = null }, _draw: function() { var that = this, renderer = that._renderer, container = that._container, options = that._options || {}, text = that._textContent = formatText(that._data, that._options) || null; that.clearVisibility(); if (text) { if (!that._group) { that._group = renderer.g().append(container); that._insideGroup = renderer.g().append(that._group); that._text = renderer.text("", 0, 0).append(that._insideGroup) } that._text.css(options.attributes ? _patchFontOptions(options.attributes.font) : {}); if (checkBackground(options.background)) { that._background = that._background || renderer.rect().append(that._insideGroup).toBackground(); that._background.attr(options.background); that._color && that._background.attr({ fill: that._color }) } else { disposeItem(that, "_background") } if (checkConnector(options.connector)) { that._connector = that._connector || renderer.path([], "line").sharp().append(that._group).toBackground(); that._connector.attr(options.connector); that._color && that._connector.attr({ stroke: that._color }) } else { disposeItem(that, "_connector") } that._text.attr({ text: text }); that._updateBackground(that._text.getBBox()); that._setVisibility("visible", true) } else { that.hide() } return that }, _updateBackground: function(bBox) { var that = this; that._textSize = [bBox.width, bBox.height]; if (that._background) { bBox.x -= LABEL_BACKGROUND_PADDING_X; bBox.y -= LABEL_BACKGROUND_PADDING_Y; bBox.width += 2 * LABEL_BACKGROUND_PADDING_X; bBox.height += 2 * LABEL_BACKGROUND_PADDING_Y; that._background.attr(bBox) } if (that._options.rotationAngle) { that._insideGroup.rotate(that._options.rotationAngle, bBox.x + bBox.width / 2, bBox.y + bBox.height / 2); bBox = _rotateBBox(bBox, [bBox.x + bBox.width / 2, bBox.y + bBox.height / 2], -that._options.rotationAngle) } that._bBox = bBox }, _getConnectorPoints: function() { var labelPoint, figurePoint, xc, yc, that = this, figure = that._figure, strategy = selectStrategy(figure), bBox = that.getBoundingRect(), points = []; if (!strategy.isLabelInside(bBox, figure, "inside" !== that._options.position)) { xc = bBox.x + bBox.width / 2; yc = bBox.y + bBox.height / 2; points = strategy.prepareLabelPoints([ [xc, yc - that._textSize[1] / 2], [xc + that._textSize[0] / 2, yc], [xc, yc + that._textSize[1] / 2], [xc - that._textSize[0] / 2, yc] ], [xc, yc], -that._options.rotationAngle || 0); labelPoint = getClosestCoord(strategy.getFigureCenter(figure), points); labelPoint = [_floor(labelPoint[0]), _floor(labelPoint[1])]; figurePoint = strategy.findFigurePoint(figure, labelPoint); points = figurePoint.concat(labelPoint) } return points }, fit: function(maxWidth) { this._text && this._text.applyEllipsis(maxWidth); this._updateBackground(this._text.getBBox()) }, setTrackerData: function(point) { this._text.data({ "chart-data-point": point }); this._background && this._background.data({ "chart-data-point": point }) }, shift: function(x, y) { var that = this; if (that._textContent) { that._insideGroup.attr({ translateX: that._x = _round(x - that._bBox.x), translateY: that._y = _round(y - that._bBox.y) }); if (that._connector) { that._connector.attr({ points: that._getConnectorPoints() }) } } return that }, getBoundingRect: function() { var bBox = this._bBox; return this._textContent ? { x: bBox.x + this._x, y: bBox.y + this._y, width: bBox.width, height: bBox.height } : {} }, getLayoutOptions: function() { var options = this._options; return { alignment: options.alignment, background: checkBackground(options.background), horizontalOffset: options.horizontalOffset, verticalOffset: options.verticalOffset, radialOffset: options.radialOffset, position: options.position } } }; exports.Label = Label; Label._DEBUG_formatText = formatText }, /*!*******************************!*\ !*** ./js/viz/core/format.js ***! \*******************************/ function(module, exports, __webpack_require__) { var _format = __webpack_require__( /*! ../../format_helper */ 66).format; module.exports = function(value, options) { return _format(value, options.format, options.precision) } }, /*!*******************************************!*\ !*** ./js/viz/series/points/bar_point.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, _extend = extend, _math = Math, _floor = _math.floor, _abs = _math.abs, _min = _math.min, symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), CANVAS_POSITION_DEFAULT = "canvas_position_default", DEFAULT_BAR_TRACKER_SIZE = 9, CORRECTING_BAR_TRACKER_VALUE = 4, RIGHT = "right", LEFT = "left", TOP = "top", BOTTOM = "bottom"; module.exports = _extend({}, symbolPoint, { correctCoordinates: function(correctOptions) { var that = this, correction = _floor(correctOptions.offset - correctOptions.width / 2); if (that._options.rotated) { that.height = correctOptions.width; that.yCorrection = correction } else { that.width = correctOptions.width; that.xCorrection = correction } }, _getGraphicBBox: function() { var that = this, bBox = {}; bBox.x = that.x; bBox.y = that.y; bBox.width = that.width; bBox.height = that.height; return bBox }, _getLabelConnector: function(location) { return this._getGraphicBBox(location) }, _getLabelPosition: function() { var position, that = this, initialValue = that.initialValue, invert = that._getValTranslator().getBusinessRange().invert, isDiscreteValue = "discrete" === that.series.valueAxisType, isFullStacked = that.series.isFullStackedSeries(), notAxisInverted = !isDiscreteValue && (initialValue >= 0 && !invert || initialValue < 0 && invert) || isDiscreteValue && !invert || isFullStacked; if (!that._options.rotated) { position = notAxisInverted ? TOP : BOTTOM } else { position = notAxisInverted ? RIGHT : LEFT } return position }, _getLabelCoords: function(label) { var coords, that = this; if (0 === that.initialValue && that.series.isFullStackedSeries()) { if (!this._options.rotated) { coords = that._getLabelCoordOfPosition(label, TOP) } else { coords = that._getLabelCoordOfPosition(label, RIGHT) } } else { if ("inside" === label.getLayoutOptions().position) { coords = that._getLabelCoordOfPosition(label, "inside") } else { coords = symbolPoint._getLabelCoords.call(this, label) } } return coords }, _checkLabelPosition: function(label, coord) { var that = this, visibleArea = that._getVisibleArea(); if (that._isPointInVisibleArea(visibleArea, that._getGraphicBBox())) { return that._moveLabelOnCanvas(coord, visibleArea, label.getBoundingRect()) } return coord }, _isLabelInsidePoint: function(label) { var that = this, graphicBBox = that._getGraphicBBox(), labelBBox = label.getBoundingRect(); if (that._options.resolveLabelsOverlapping && "inside" === label.getLayoutOptions().position) { if (labelBBox.width > graphicBBox.width || labelBBox.height > graphicBBox.height) { label.hide(); return true } } return false }, _moveLabelOnCanvas: function(coord, visibleArea, labelBBox) { var x = coord.x, y = coord.y; if (visibleArea.minX > x) { x = visibleArea.minX } if (visibleArea.maxX < x + labelBBox.width) { x = visibleArea.maxX - labelBBox.width } if (visibleArea.minY > y) { y = visibleArea.minY } if (visibleArea.maxY < y + labelBBox.height) { y = visibleArea.maxY - labelBBox.height } return { x: x, y: y } }, _showForZeroValues: function() { return this._options.label.showForZeroValues || this.initialValue }, _drawMarker: function(renderer, group, animationEnabled) { var that = this, style = that._getStyle(), x = that.x, y = that.y, width = that.width, height = that.height, r = that._options.cornerRadius; if (animationEnabled) { if (that._options.rotated) { width = 0; x = that.defaultX } else { height = 0; y = that.defaultY } } that.graphic = renderer.rect(x, y, width, height).attr({ rx: r, ry: r }).smartAttr(style).data({ "chart-data-point": that }).append(group) }, _getSettingsForTracker: function() { var that = this, y = that.y, height = that.height, x = that.x, width = that.width; if (that._options.rotated) { if (1 === width) { width = DEFAULT_BAR_TRACKER_SIZE; x -= CORRECTING_BAR_TRACKER_VALUE } } else { if (1 === height) { height = DEFAULT_BAR_TRACKER_SIZE; y -= CORRECTING_BAR_TRACKER_VALUE } } return { x: x, y: y, width: width, height: height } }, getGraphicSettings: function() { var graphic = this.graphic; return { x: graphic.attr("x"), y: graphic.attr("y"), height: graphic.attr("height"), width: graphic.attr("width") } }, _getEdgeTooltipParams: function(x, y, width, height) { var xCoord, yCoord, isPositive = this.value >= 0, invertedBusinessRange = this._getValTranslator().getBusinessRange().invert; if (this._options.rotated) { yCoord = y + height / 2; if (invertedBusinessRange) { xCoord = isPositive ? x : x + width } else { xCoord = isPositive ? x + width : x } } else { xCoord = x + width / 2; if (invertedBusinessRange) { yCoord = isPositive ? y + height : y } else { yCoord = isPositive ? y : y + height } } return { x: xCoord, y: yCoord, offset: 0 } }, getTooltipParams: function(location) { var x = this.x, y = this.y, width = this.width, height = this.height; return "edge" === location ? this._getEdgeTooltipParams(x, y, width, height) : { x: x + width / 2, y: y + height / 2, offset: 0 } }, _truncateCoord: function(coord, minBounce, maxBounce) { if (coord < minBounce) { return minBounce } if (coord > maxBounce) { return maxBounce } return coord }, _translateErrorBars: function(argVisibleArea) { symbolPoint._translateErrorBars.call(this); if (this._errorBarPos < argVisibleArea.min || this._errorBarPos > argVisibleArea.max) { this._errorBarPos = void 0 } }, _translate: function() { var arg, minArg, val, minVal, that = this, rotated = that._options.rotated, valAxis = rotated ? "x" : "y", argAxis = rotated ? "y" : "x", valIntervalName = rotated ? "width" : "height", argIntervalName = rotated ? "height" : "width", argTranslator = that._getArgTranslator(), valTranslator = that._getValTranslator(), argVisibleArea = argTranslator.getCanvasVisibleArea(), valVisibleArea = valTranslator.getCanvasVisibleArea(); arg = minArg = argTranslator.translate(that.argument) + (that[argAxis + "Correction"] || 0); val = valTranslator.translate(that.value); minVal = valTranslator.translate(that.minValue); if (null === val) { val = minVal } that["v" + valAxis] = val; that["v" + argAxis] = arg + that[argIntervalName] / 2; that[valIntervalName] = _abs(val - minVal); that._calculateVisibility(rotated ? _min(val, minVal) : _min(arg, minArg), rotated ? _min(arg, minArg) : _min(val, minVal), that.width, that.height); val = that._truncateCoord(val, valVisibleArea.min, valVisibleArea.max); minVal = that._truncateCoord(minVal, valVisibleArea.min, valVisibleArea.max); that[argAxis] = arg; that["min" + argAxis.toUpperCase()] = minArg; that[valIntervalName] = _abs(val - minVal); that[valAxis] = _min(val, minVal) + (that[valAxis + "Correction"] || 0); that["min" + valAxis.toUpperCase()] = minVal + (that[valAxis + "Correction"] || 0); that["default" + valAxis.toUpperCase()] = valTranslator.translate(CANVAS_POSITION_DEFAULT); that._translateErrorBars(argVisibleArea); if (that.inVisibleArea) { if (that[argAxis] < argVisibleArea.min) { that[argIntervalName] = that[argIntervalName] - (argVisibleArea.min - that[argAxis]); that[argAxis] = argVisibleArea.min; that["min" + argAxis.toUpperCase()] = argVisibleArea.min } if (that[argAxis] + that[argIntervalName] > argVisibleArea.max) { that[argIntervalName] = argVisibleArea.max - that[argAxis] } } }, _updateMarker: function(animationEnabled, style) { this.graphic.smartAttr(_extend({}, style, !animationEnabled ? this.getMarkerCoords() : {})) }, getMarkerCoords: function() { return { x: this.x, y: this.y, width: this.width, height: this.height } }, coordsIn: function(x, y) { var that = this; return x >= that.x && x <= that.x + that.width && y >= that.y && y <= that.y + that.height } }) }, /*!**********************************************!*\ !*** ./js/viz/series/points/bubble_point.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), _extend = extend, MIN_BUBBLE_HEIGHT = 20; module.exports = _extend({}, symbolPoint, { correctCoordinates: function(diameter) { this.bubbleSize = diameter / 2 }, _drawMarker: function(renderer, group, animationEnabled) { var that = this, attr = _extend({ translateX: that.x, translateY: that.y }, that._getStyle()); that.graphic = renderer.circle(0, 0, animationEnabled ? 0 : that.bubbleSize).smartAttr(attr).data({ "chart-data-point": that }).append(group) }, getTooltipParams: function(location) { var height, that = this, graphic = that.graphic; if (!graphic) { return } height = graphic.getBBox().height; return { x: that.x, y: height < MIN_BUBBLE_HEIGHT || "edge" === location ? this.y - height / 2 : this.y, offset: 0 } }, _getLabelFormatObject: function() { var formatObject = symbolPoint._getLabelFormatObject.call(this); formatObject.size = this.initialSize; return formatObject }, _updateData: function(data) { symbolPoint._updateData.call(this, data); this.size = this.initialSize = data.size }, _getGraphicBBox: function() { var that = this; return that._getSymbolBBox(that.x, that.y, that.bubbleSize) }, _updateMarker: function(animationEnabled, style) { var that = this; if (!animationEnabled) { style = _extend({ r: that.bubbleSize, translateX: that.x, translateY: that.y }, style) } that.graphic.smartAttr(style) }, _getFormatObject: function(tooltip) { var formatObject = symbolPoint._getFormatObject.call(this, tooltip); formatObject.sizeText = tooltip.formatValue(this.initialSize); return formatObject }, _storeTrackerR: function() { return this.bubbleSize }, _getLabelCoords: function(label) { var coords; if ("inside" === label.getLayoutOptions().position) { coords = this._getLabelCoordOfPosition(label, "inside") } else { coords = symbolPoint._getLabelCoords.call(this, label) } return coords } }) }, /*!*******************************************!*\ !*** ./js/viz/series/points/pie_point.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, CONNECTOR_LENGTH = 20, symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), _extend = extend, _round = Math.round, _sqrt = Math.sqrt, _acos = Math.acos, DEG = 180 / Math.PI, _abs = Math.abs, vizUtils = __webpack_require__( /*! ../../core/utils */ 509), _normalizeAngle = vizUtils.normalizeAngle, _getCosAndSin = vizUtils.getCosAndSin, commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), _isDefined = commonUtils.isDefined, getVerticallyShiftedAngularCoords = vizUtils.getVerticallyShiftedAngularCoords, INDENT_FROM_PIE = __webpack_require__( /*! ../../components/consts */ 527).pieLabelIndent; module.exports = _extend({}, symbolPoint, { _updateData: function(data) { var that = this; symbolPoint._updateData.call(this, data); that._visible = true; that.minValue = that.initialMinValue = that.originalMinValue = _isDefined(data.minValue) ? data.minValue : 0 }, animate: function(complete, duration, delay) { var that = this; that.graphic.animate({ x: that.centerX, y: that.centerY, outerRadius: that.radiusOuter, innerRadius: that.radiusInner, startAngle: that.toAngle, endAngle: that.fromAngle }, { delay: delay, partitionDuration: duration }, complete) }, correctPosition: function(correction) { var that = this; that.correctRadius(correction); that.correctLabelRadius(correction.radiusOuter); that.centerX = correction.centerX; that.centerY = correction.centerY }, correctRadius: function(correction) { this.radiusInner = correction.radiusInner; this.radiusOuter = correction.radiusOuter }, correctLabelRadius: function(radiusLabels) { this.radiusLabels = radiusLabels }, correctValue: function(correction, percent, base) { var that = this; that.value = (base || that.initialValue) + correction; that.minValue = correction; that.percent = percent; that._label.setDataField("percent", percent) }, setMaxLabelLength: function(maxLabelLength) { this._maxLabelLength = maxLabelLength }, _updateLabelData: function() { this._label.setData(this._getLabelFormatObject()) }, _getShiftLabelCoords: function() { var that = this, bBox = that._label.getBoundingRect(), coord = that._getLabelCoords(that._label), visibleArea = that._getVisibleArea(); if (that._isLabelDrawingWithoutPoints) { return that._checkLabelPosition(coord, bBox, visibleArea) } else { return that._getLabelExtraCoord(coord, that._checkVerticalLabelPosition(coord, bBox, visibleArea), bBox) } }, _getLabelPosition: function(options) { return options.position }, _getLabelCoords: function(label) { var rad, x, that = this, bBox = label.getBoundingRect(), options = label.getLayoutOptions(), angleFunctions = _getCosAndSin(that.middleAngle), position = that._getLabelPosition(options), radiusInner = that.radiusInner, radiusOuter = that.radiusOuter, radiusLabels = that.radiusLabels; if ("inside" === position) { rad = radiusInner + (radiusOuter - radiusInner) / 2 + options.radialOffset; x = that.centerX + rad * angleFunctions.cos - bBox.width / 2 } else { rad = radiusLabels + options.radialOffset + INDENT_FROM_PIE; if (angleFunctions.cos > .1) { x = that.centerX + rad * angleFunctions.cos } else { if (angleFunctions.cos < -.1) { x = that.centerX + rad * angleFunctions.cos - bBox.width } else { x = that.centerX + rad * angleFunctions.cos - bBox.width / 2 } } } return { x: x, y: _round(that.centerY - rad * angleFunctions.sin - bBox.height / 2) } }, _getColumnsCoord: function(coord) { var x, that = this, label = that._label, bBox = label.getBoundingRect(), options = label.getLayoutOptions(), rad = that.radiusLabels + options.radialOffset, visibleArea = that._getVisibleArea(), rightBorderX = visibleArea.maxX - bBox.width, leftBorderX = visibleArea.minX, angleOfPoint = _normalizeAngle(that.middleAngle); if ("columns" !== options.position) { return coord } rad += CONNECTOR_LENGTH; if (angleOfPoint < 90 || angleOfPoint >= 270) { x = that._maxLabelLength ? that.centerX + rad + that._maxLabelLength - bBox.width : rightBorderX; x = x > rightBorderX ? rightBorderX : x } else { x = that._maxLabelLength ? that.centerX - rad - that._maxLabelLength : leftBorderX; x = x < leftBorderX ? leftBorderX : x } coord.x = x; return coord }, drawLabel: function() { this.translate(); this._isLabelDrawingWithoutPoints = true; this._drawLabel(); this._isLabelDrawingWithoutPoints = false }, updateLabelCoord: function() { var that = this, bBox = that._label.getBoundingRect(), coord = that._getColumnsCoord(bBox); coord = that._checkHorizontalLabelPosition(coord, bBox, that._getVisibleArea()); that._label.shift(_round(coord.x), _round(bBox.y)) }, _checkVerticalLabelPosition: function(coord, box, visibleArea) { var x = coord.x, y = coord.y; if (coord.y + box.height > visibleArea.maxY) { y = visibleArea.maxY - box.height } else { if (coord.y < visibleArea.minY) { y = visibleArea.minY } } return { x: x, y: y } }, _getLabelExtraCoord: function(coord, shiftCoord, box) { return coord.y !== shiftCoord.y ? getVerticallyShiftedAngularCoords({ x: coord.x, y: coord.y, width: box.width, height: box.height }, shiftCoord.y - coord.y, { x: this.centerX, y: this.centerY }) : coord }, _checkHorizontalLabelPosition: function(coord, box, visibleArea) { var x = coord.x, y = coord.y; if (coord.x + box.width > visibleArea.maxX) { x = visibleArea.maxX - box.width } else { if (coord.x < visibleArea.minX) { x = visibleArea.minX } } return { x: x, y: y } }, setLabelEllipsis: function() { var that = this, bBox = that._label.getBoundingRect(), coord = that._checkHorizontalLabelPosition(bBox, bBox, that._getVisibleArea()); that._label.fit(bBox.width - _abs(coord.x - bBox.x)) }, setLabelTrackerData: function() { this._label.setTrackerData(this) }, _checkLabelPosition: function(coord, bBox, visibleArea) { coord = this._checkHorizontalLabelPosition(coord, bBox, visibleArea); return this._checkVerticalLabelPosition(coord, bBox, visibleArea) }, _getLabelConnector: function() { var that = this, rad = that.radiusOuter, seriesStyle = that._options.styles.normal, strokeWidthBy2 = seriesStyle["stroke-width"] / 2, borderWidth = that.series.getOptions().containerBackgroundColor === seriesStyle.stroke ? _round(strokeWidthBy2) : _round(-strokeWidthBy2), angleFunctions = _getCosAndSin(_round(that.middleAngle)); return { x: _round(that.centerX + (rad - borderWidth) * angleFunctions.cos), y: _round(that.centerY - (rad - borderWidth) * angleFunctions.sin), angle: that.middleAngle } }, _drawMarker: function(renderer, group, animationEnabled, firstDrawing) { var that = this, radiusOuter = that.radiusOuter, radiusInner = that.radiusInner, fromAngle = that.fromAngle, toAngle = that.toAngle; if (animationEnabled) { radiusInner = radiusOuter = 0; if (!firstDrawing) { fromAngle = toAngle = that.shiftedAngle } } that.graphic = renderer.arc(that.centerX, that.centerY, radiusInner, radiusOuter, toAngle, fromAngle).attr({ "stroke-linejoin": "round" }).smartAttr(that._getStyle()).data({ "chart-data-point": that }).sharp().append(group) }, getTooltipParams: function() { var that = this, angleFunctions = _getCosAndSin(that.middleAngle), radiusInner = that.radiusInner, radiusOuter = that.radiusOuter; return { x: that.centerX + (radiusInner + (radiusOuter - radiusInner) / 2) * angleFunctions.cos, y: that.centerY - (radiusInner + (radiusOuter - radiusInner) / 2) * angleFunctions.sin, offset: 0 } }, _translate: function() { var that = this, angle = that.shiftedAngle || 0, value = that.value, minValue = that.minValue, translator = that._getValTranslator(); that.fromAngle = translator.translate(minValue) + angle; that.toAngle = translator.translate(value) + angle; that.middleAngle = translator.translate((value - minValue) / 2 + minValue) + angle; if (!that.isVisible()) { that.middleAngle = that.toAngle = that.fromAngle = that.fromAngle || angle } }, _getMarkerVisibility: function() { return true }, _updateMarker: function(animationEnabled, style, _, callback) { var that = this; if (!animationEnabled) { style = _extend({ x: that.centerX, y: that.centerY, outerRadius: that.radiusOuter, innerRadius: that.radiusInner, startAngle: that.toAngle, endAngle: that.fromAngle }, style) } that.graphic.smartAttr(style).sharp(); callback && callback() }, getLegendStyles: function() { return this._styles.legendStyles }, isInVisibleArea: function() { return true }, hide: function() { var that = this; if (that._visible) { that._visible = false; that.hideTooltip(); that._options.visibilityChanged(that) } }, show: function() { var that = this; if (!that._visible) { that._visible = true; that._options.visibilityChanged(that) } }, setInvisibility: function() { this._label.hide() }, isVisible: function() { return this._visible }, _getFormatObject: function(tooltip) { var formatObject = symbolPoint._getFormatObject.call(this, tooltip), percent = this.percent; formatObject.percent = percent; formatObject.percentText = tooltip.formatValue(percent, "percent"); return formatObject }, getColor: function() { return this._styles.normal.fill }, coordsIn: function(x, y) { var angle, that = this, lx = x - that.centerX, ly = y - that.centerY, r = _sqrt(lx * lx + ly * ly), fromAngle = that.fromAngle % 360, toAngle = that.toAngle % 360; if (r < that.radiusInner || r > that.radiusOuter || 0 === r) { return false } angle = _acos(lx / r) * DEG * (ly > 0 ? -1 : 1); if (angle < 0) { angle += 360 } if (fromAngle === toAngle && _abs(that.toAngle - that.fromAngle) > 1e-4) { return true } else { return fromAngle >= toAngle ? angle <= fromAngle && angle >= toAngle : !(angle >= fromAngle && angle <= toAngle) } } }) }, /*!****************************************************!*\ !*** ./js/viz/series/points/range_symbol_point.js ***! \****************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../../core/renderer */ 9), extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), labelModule = __webpack_require__( /*! ./label */ 529), symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), _extend = extend, _isDefined = commonUtils.isDefined, _math = Math, _abs = _math.abs, _min = _math.min, _max = _math.max, _round = _math.round, DEFAULT_IMAGE_WIDTH = 20, DEFAULT_IMAGE_HEIGHT = 20; module.exports = _extend({}, symbolPoint, { deleteLabel: function() { var that = this; that._topLabel.dispose(); that._topLabel = null; that._bottomLabel.dispose(); that._bottomLabel = null }, hideMarker: function(type) { var graphic = this.graphic, marker = graphic && graphic[type + "Marker"], label = this["_" + type + "Label"]; if (marker && "hidden" !== marker.attr("visibility")) { marker.attr({ visibility: "hidden" }) } label.hide() }, setInvisibility: function() { this.hideMarker("top"); this.hideMarker("bottom") }, clearVisibility: function() { var that = this, graphic = that.graphic, topMarker = graphic && graphic.topMarker, bottomMarker = graphic && graphic.bottomMarker; if (topMarker && topMarker.attr("visibility")) { topMarker.attr({ visibility: null }) } if (bottomMarker && bottomMarker.attr("visibility")) { bottomMarker.attr({ visibility: null }) } that._topLabel.clearVisibility(); that._bottomLabel.clearVisibility() }, clearMarker: function() { var that = this, graphic = that.graphic, topMarker = graphic && graphic.topMarker, bottomMarker = graphic && graphic.bottomMarker, emptySettings = that._emptySettings; topMarker && topMarker.attr(emptySettings); bottomMarker && bottomMarker.attr(emptySettings) }, _getLabelPosition: function(markerType) { var position, labelsInside = "inside" === this._options.label.position; if (!this._options.rotated) { position = "top" === markerType ^ labelsInside ? "top" : "bottom" } else { position = "top" === markerType ^ labelsInside ? "right" : "left" } return position }, _getLabelMinFormatObject: function() { var that = this; return { index: 0, argument: that.initialArgument, value: that.initialMinValue, seriesName: that.series.name, originalValue: that.originalMinValue, originalArgument: that.originalArgument, point: that } }, _updateLabelData: function() { var maxFormatObject = this._getLabelFormatObject(); maxFormatObject.index = 1; this._topLabel.setData(maxFormatObject); this._bottomLabel.setData(this._getLabelMinFormatObject()) }, _updateLabelOptions: function() { var that = this, options = this._options.label; (!that._topLabel || !that._bottomLabel) && that._createLabel(); that._topLabel.setOptions(options); that._bottomLabel.setOptions(options) }, _createLabel: function() { var options = { renderer: this.series._renderer, labelsGroup: this.series._labelsGroup, point: this }; this._topLabel = new labelModule.Label(options); this._bottomLabel = new labelModule.Label(options) }, _getGraphicBBox: function(location) { var bBox, options = this._options, images = this._getImage(options.image), image = "top" === location ? this._checkImage(images.top) : this._checkImage(images.bottom), coord = this._getPositionFromLocation(location); if (options.visible) { bBox = image ? this._getImageBBox(coord.x, coord.y) : this._getSymbolBBox(coord.x, coord.y, options.styles.normal.r) } else { bBox = { x: coord.x, y: coord.y, width: 0, height: 0 } } return bBox }, _getPositionFromLocation: function(location) { var x, y, isTop = "top" === location; if (!this._options.rotated) { x = this.x; y = isTop ? _min(this.y, this.minY) : _max(this.y, this.minY) } else { x = isTop ? _max(this.x, this.minX) : _min(this.x, this.minX); y = this.y } return { x: x, y: y } }, _checkOverlay: function(bottomCoord, topCoord, topValue) { return bottomCoord < topCoord + topValue }, _getOverlayCorrections: function(topCoords, bottomCoords) { var rotated = this._options.rotated, coordSelector = !rotated ? "y" : "x", valueSelector = !rotated ? "height" : "width", visibleArea = this._getValTranslator().getCanvasVisibleArea(), minBound = visibleArea.min, maxBound = visibleArea.max, delta = _round((topCoords[coordSelector] + topCoords[valueSelector] - bottomCoords[coordSelector]) / 2), coord1 = topCoords[coordSelector] - delta, coord2 = bottomCoords[coordSelector] + delta; if (coord1 < minBound) { delta = minBound - topCoords[coordSelector]; coord1 += delta; coord2 += delta } else { if (coord2 + bottomCoords[valueSelector] > maxBound) { delta = -(bottomCoords[coordSelector] + bottomCoords[valueSelector] - maxBound); coord1 += delta; coord2 += delta } } return { coord1: coord1, coord2: coord2 } }, _checkLabelsOverlay: function(topLocation) { var that = this, topCoords = that._topLabel.getBoundingRect(), bottomCoords = that._bottomLabel.getBoundingRect(), corrections = {}; if (!that._options.rotated) { if ("top" === topLocation) { if (this._checkOverlay(bottomCoords.y, topCoords.y, topCoords.height)) { corrections = this._getOverlayCorrections(topCoords, bottomCoords); that._topLabel.shift(topCoords.x, corrections.coord1); that._bottomLabel.shift(bottomCoords.x, corrections.coord2) } } else { if (this._checkOverlay(topCoords.y, bottomCoords.y, bottomCoords.height)) { corrections = this._getOverlayCorrections(bottomCoords, topCoords); that._topLabel.shift(topCoords.x, corrections.coord2); that._bottomLabel.shift(bottomCoords.x, corrections.coord1) } } } else { if ("top" === topLocation) { if (this._checkOverlay(topCoords.x, bottomCoords.x, bottomCoords.width)) { corrections = this._getOverlayCorrections(bottomCoords, topCoords); that._topLabel.shift(corrections.coord2, topCoords.y); that._bottomLabel.shift(corrections.coord1, bottomCoords.y) } } else { if (this._checkOverlay(bottomCoords.x, topCoords.x, topCoords.width)) { corrections = this._getOverlayCorrections(topCoords, bottomCoords); that._topLabel.shift(corrections.coord1, topCoords.y); that._bottomLabel.shift(corrections.coord2, bottomCoords.y) } } } }, _drawLabel: function() { var that = this, labels = [], notInverted = that._options.rotated ? that.x >= that.minX : that.y < that.minY, customVisibility = that._getCustomLabelVisibility(), topLabel = that._topLabel, bottomLabel = that._bottomLabel; topLabel.pointPosition = notInverted ? "top" : "bottom"; bottomLabel.pointPosition = notInverted ? "bottom" : "top"; if ((that.series.getLabelVisibility() || customVisibility) && that.hasValue() && false !== customVisibility) { false !== that.visibleTopMarker && labels.push(topLabel); false !== that.visibleBottomMarker && labels.push(bottomLabel); $.each(labels, function(_, label) { label.show() }); that._checkLabelsOverlay(that._topLabel.pointPosition) } else { topLabel.hide(); bottomLabel.hide() } }, _getImage: function(imageOption) { var image = {}; if (_isDefined(imageOption)) { if ("string" === typeof imageOption) { image.top = image.bottom = imageOption } else { image.top = { url: "string" === typeof imageOption.url ? imageOption.url : imageOption.url && imageOption.url.rangeMaxPoint, width: "number" === typeof imageOption.width ? imageOption.width : imageOption.width && imageOption.width.rangeMaxPoint, height: "number" === typeof imageOption.height ? imageOption.height : imageOption.height && imageOption.height.rangeMaxPoint }; image.bottom = { url: "string" === typeof imageOption.url ? imageOption.url : imageOption.url && imageOption.url.rangeMinPoint, width: "number" === typeof imageOption.width ? imageOption.width : imageOption.width && imageOption.width.rangeMinPoint, height: "number" === typeof imageOption.height ? imageOption.height : imageOption.height && imageOption.height.rangeMinPoint } } } return image }, _checkSymbol: function(oldOptions, newOptions) { var that = this, oldSymbol = oldOptions.symbol, newSymbol = newOptions.symbol, symbolChanged = "circle" === oldSymbol && "circle" !== newSymbol || "circle" !== oldSymbol && "circle" === newSymbol, oldImages = that._getImage(oldOptions.image), newImages = that._getImage(newOptions.image), topImageChanged = that._checkImage(oldImages.top) !== that._checkImage(newImages.top), bottomImageChanged = that._checkImage(oldImages.bottom) !== that._checkImage(newImages.bottom); return symbolChanged || topImageChanged || bottomImageChanged }, _getSettingsForTwoMarkers: function(style) { var that = this, options = that._options, settings = {}, x = options.rotated ? _min(that.x, that.minX) : that.x, y = options.rotated ? that.y : _min(that.y, that.minY), radius = style.r, points = that._populatePointShape(options.symbol, radius); settings.top = _extend({ translateX: x + that.width, translateY: y, r: radius }, style); settings.bottom = _extend({ translateX: x, translateY: y + that.height, r: radius }, style); if (points) { settings.top.points = settings.bottom.points = points } return settings }, _hasGraphic: function() { return this.graphic && this.graphic.topMarker && this.graphic.bottomMarker }, _drawOneMarker: function(renderer, markerType, imageSettings, settings) { var that = this, graphic = that.graphic; if (graphic[markerType]) { that._updateOneMarker(markerType, settings) } else { graphic[markerType] = that._createMarker(renderer, graphic, imageSettings, settings) } }, _drawMarker: function(renderer, group, animationEnabled, firstDrawing, style) { var that = this, settings = that._getSettingsForTwoMarkers(style || that._getStyle()), image = that._getImage(that._options.image); if (that._checkImage(image.top)) { settings.top = that._getImageSettings(settings.top, image.top) } if (that._checkImage(image.bottom)) { settings.bottom = that._getImageSettings(settings.bottom, image.bottom) } that.graphic = that.graphic || renderer.g().append(group); that.visibleTopMarker && that._drawOneMarker(renderer, "topMarker", image.top, settings.top); that.visibleBottomMarker && that._drawOneMarker(renderer, "bottomMarker", image.bottom, settings.bottom) }, _getSettingsForTracker: function(radius) { var that = this, rotated = that._options.rotated; return { translateX: rotated ? _min(that.x, that.minX) - radius : that.x - radius, translateY: rotated ? that.y - radius : _min(that.y, that.minY) - radius, width: that.width + 2 * radius, height: that.height + 2 * radius } }, isInVisibleArea: function() { var notVisibleByArg, notVisibleByVal, tmp, visibleArgArea, visibleValArea, that = this, rotated = that._options.rotated, argument = !rotated ? that.x : that.y, maxValue = !rotated ? _max(that.minY, that.y) : _max(that.minX, that.x), minValue = !rotated ? _min(that.minY, that.y) : _min(that.minX, that.x), visibleTopMarker = true, visibleBottomMarker = true, visibleRangeArea = true; visibleArgArea = that._getArgTranslator().getCanvasVisibleArea(); visibleValArea = that._getValTranslator().getCanvasVisibleArea(); notVisibleByArg = visibleArgArea.max < argument || visibleArgArea.min > argument; notVisibleByVal = visibleValArea.min > minValue && visibleValArea.min > maxValue || visibleValArea.max < minValue && visibleValArea.max < maxValue; if (notVisibleByArg || notVisibleByVal) { visibleTopMarker = visibleBottomMarker = visibleRangeArea = false } else { visibleTopMarker = visibleValArea.min <= minValue && visibleValArea.max > minValue; visibleBottomMarker = visibleValArea.min < maxValue && visibleValArea.max >= maxValue; if (rotated) { tmp = visibleTopMarker; visibleTopMarker = visibleBottomMarker; visibleBottomMarker = tmp } } that.visibleTopMarker = visibleTopMarker; that.visibleBottomMarker = visibleBottomMarker; return visibleRangeArea }, getTooltipParams: function() { var x, y, that = this, rotated = that._options.rotated, minValue = !rotated ? _min(that.y, that.minY) : _min(that.x, that.minX), side = !rotated ? "height" : "width", visibleArea = that._getVisibleArea(), minVisible = rotated ? visibleArea.minX : visibleArea.minY, maxVisible = rotated ? visibleArea.maxX : visibleArea.maxY, min = _max(minVisible, minValue), max = _min(maxVisible, minValue + that[side]); if (!rotated) { x = that.x; y = min + (max - min) / 2 } else { y = that.y; x = min + (max - min) / 2 } return { x: x, y: y, offset: 0 } }, _translate: function() { var that = this, rotated = that._options.rotated; symbolPoint._translate.call(that); that.height = rotated ? 0 : _abs(that.minY - that.y); that.width = rotated ? _abs(that.x - that.minX) : 0 }, _updateData: function(data) { var that = this; symbolPoint._updateData.call(that, data); that.minValue = that.initialMinValue = that.originalMinValue = data.minValue }, _getImageSettings: function(settings, image) { return { href: image.url || image.toString(), width: image.width || DEFAULT_IMAGE_WIDTH, height: image.height || DEFAULT_IMAGE_HEIGHT, translateX: settings.translateX, translateY: settings.translateY } }, getCrosshairData: function(x, y) { var that = this, rotated = that._options.rotated, minX = that.minX, minY = that.minY, vx = that.vx, vy = that.vy, value = that.value, minValue = that.minValue, argument = that.argument, coords = { axis: that.series.axis, x: vx, y: vy, yValue: value, xValue: argument }; if (rotated) { coords.yValue = argument; if (_abs(vx - x) < _abs(minX - x)) { coords.xValue = value } else { coords.x = minX; coords.xValue = minValue } } else { if (_abs(vy - y) >= _abs(minY - y)) { coords.y = minY; coords.yValue = minValue } } return coords }, _updateOneMarker: function(markerType, settings) { this.graphic && this.graphic[markerType] && this.graphic[markerType].attr(settings) }, _updateMarker: function(animationEnabled, style) { this._drawMarker(void 0, void 0, false, false, style) }, _getFormatObject: function(tooltip) { var that = this, initialMinValue = that.initialMinValue, initialValue = that.initialValue, initialArgument = that.initialArgument, minValue = tooltip.formatValue(initialMinValue), value = tooltip.formatValue(initialValue); return { argument: initialArgument, argumentText: tooltip.formatValue(initialArgument, "argument"), valueText: minValue + " - " + value, rangeValue1Text: minValue, rangeValue2Text: value, rangeValue1: initialMinValue, rangeValue2: initialValue, seriesName: that.series.name, point: that, originalMinValue: that.originalMinValue, originalValue: that.originalValue, originalArgument: that.originalArgument } }, getLabel: function() { return [this._topLabel, this._bottomLabel] }, getLabels: function() { return [this._topLabel, this._bottomLabel] }, getBoundingRect: commonUtils.noop, coordsIn: function(x, y) { var trackerRadius = this._storeTrackerR(), xCond = x >= this.x - trackerRadius && x <= this.x + trackerRadius, yCond = y >= this.y - trackerRadius && y <= this.y + trackerRadius; if (this._options.rotated) { return yCond && (xCond || x >= this.minX - trackerRadius && x <= this.minX + trackerRadius) } else { return xCond && (yCond || y >= this.minY - trackerRadius && y <= this.minY + trackerRadius) } }, getMaxValue: function() { if ("discrete" !== this.series.valueAxisType) { return this.minValue > this.value ? this.minValue : this.value } return this.value }, getMinValue: function() { if ("discrete" !== this.series.valueAxisType) { return this.minValue < this.value ? this.minValue : this.value } return this.minValue } }) }, /*!*************************************************!*\ !*** ./js/viz/series/points/range_bar_point.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var noop = __webpack_require__( /*! ../../../core/utils/common */ 14).noop, extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, barPoint = __webpack_require__( /*! ./bar_point */ 531), rangeSymbolPointMethods = __webpack_require__( /*! ./range_symbol_point */ 534), _extend = extend; module.exports = _extend({}, barPoint, { deleteLabel: rangeSymbolPointMethods.deleteLabel, _getFormatObject: rangeSymbolPointMethods._getFormatObject, clearVisibility: function() { var graphic = this.graphic; if (graphic && graphic.attr("visibility")) { graphic.attr({ visibility: null }) } this._topLabel.clearVisibility(); this._bottomLabel.clearVisibility() }, setInvisibility: function() { var graphic = this.graphic; if (graphic && "hidden" !== graphic.attr("visibility")) { graphic.attr({ visibility: "hidden" }) } this._topLabel.hide(); this._bottomLabel.hide() }, getTooltipParams: function(location) { var x, y, that = this, edgeLocation = "edge" === location; if (that._options.rotated) { x = edgeLocation ? that.x + that.width : that.x + that.width / 2; y = that.y + that.height / 2 } else { x = that.x + that.width / 2; y = edgeLocation ? that.y : that.y + that.height / 2 } return { x: x, y: y, offset: 0 } }, _translate: function() { var that = this, barMethods = barPoint; barMethods._translate.call(that); if (that._options.rotated) { that.width = that.width || 1 } else { that.height = that.height || 1 } }, _updateData: rangeSymbolPointMethods._updateData, _getLabelPosition: rangeSymbolPointMethods._getLabelPosition, _getLabelMinFormatObject: rangeSymbolPointMethods._getLabelMinFormatObject, _updateLabelData: rangeSymbolPointMethods._updateLabelData, _updateLabelOptions: rangeSymbolPointMethods._updateLabelOptions, getCrosshairData: rangeSymbolPointMethods.getCrosshairData, _createLabel: rangeSymbolPointMethods._createLabel, _checkOverlay: rangeSymbolPointMethods._checkOverlay, _checkLabelsOverlay: rangeSymbolPointMethods._checkLabelsOverlay, _getOverlayCorrections: rangeSymbolPointMethods._getOverlayCorrections, _drawLabel: rangeSymbolPointMethods._drawLabel, _getLabelCoords: rangeSymbolPointMethods._getLabelCoords, _getGraphicBBox: function(location) { var isTop = "top" === location, bBox = barPoint._getGraphicBBox.call(this); if (!this._options.rotated) { bBox.y = isTop ? bBox.y : bBox.y + bBox.height; bBox.height = 0 } else { bBox.x = isTop ? bBox.x + bBox.width : bBox.x; bBox.width = 0 } return bBox }, getLabel: rangeSymbolPointMethods.getLabel, getLabels: rangeSymbolPointMethods.getLabels, getBoundingRect: noop, getMinValue: rangeSymbolPointMethods.getMinValue, getMaxValue: rangeSymbolPointMethods.getMaxValue }) }, /*!***************************************************!*\ !*** ./js/viz/series/points/candlestick_point.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var isNumeric = __webpack_require__( /*! ../../../core/utils/common */ 14).isNumeric, extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), barPoint = __webpack_require__( /*! ./bar_point */ 531), _isNumeric = isNumeric, _extend = extend, _math = Math, _abs = _math.abs, _min = _math.min, _max = _math.max, _round = _math.round, DEFAULT_FINANCIAL_TRACKER_MARGIN = 2; module.exports = _extend({}, barPoint, { _getContinuousPoints: function(minValueName, maxValueName) { var points, that = this, x = that.x, createPoint = that._options.rotated ? function(x, y) { return [y, x] } : function(x, y) { return [x, y] }, width = that.width, min = that[minValueName], max = that[maxValueName]; if (min === max) { points = [].concat(createPoint(x, that.highY)).concat(createPoint(x, that.lowY)).concat(createPoint(x, that.closeY)).concat(createPoint(x - width / 2, that.closeY)).concat(createPoint(x + width / 2, that.closeY)).concat(createPoint(x, that.closeY)) } else { points = [].concat(createPoint(x, that.highY)).concat(createPoint(x, max)).concat(createPoint(x + width / 2, max)).concat(createPoint(x + width / 2, min)).concat(createPoint(x, min)).concat(createPoint(x, that.lowY)).concat(createPoint(x, min)).concat(createPoint(x - width / 2, min)).concat(createPoint(x - width / 2, max)).concat(createPoint(x, max)) } return points }, _getCategoryPoints: function(y) { var that = this, x = that.x, createPoint = that._options.rotated ? function(x, y) { return [y, x] } : function(x, y) { return [x, y] }; return [].concat(createPoint(x, that.highY)).concat(createPoint(x, that.lowY)).concat(createPoint(x, y)).concat(createPoint(x - that.width / 2, y)).concat(createPoint(x + that.width / 2, y)).concat(createPoint(x, y)) }, _getPoints: function() { var points, minValueName, maxValueName, that = this, openValue = that.openValue, closeValue = that.closeValue; if (_isNumeric(openValue) && _isNumeric(closeValue)) { minValueName = openValue > closeValue ? "closeY" : "openY"; maxValueName = openValue > closeValue ? "openY" : "closeY"; points = that._getContinuousPoints(minValueName, maxValueName) } else { if (openValue === closeValue) { points = [that.x, that.highY, that.x, that.lowY] } else { points = that._getCategoryPoints(_isNumeric(openValue) ? that.openY : that.closeY) } } return points }, getColor: function() { var that = this; return that._isReduction ? that._options.reduction.color : that._styles.normal.stroke || that.series.getColor() }, _drawMarkerInGroup: function(group, attributes, renderer) { var that = this; that.graphic = renderer.path(that._getPoints(), "area").attr({ "stroke-linecap": "square" }).attr(attributes).data({ "chart-data-point": that }).sharp().append(group) }, _fillStyle: function() { var that = this, styles = that._options.styles; if (that._isReduction && that._isPositive) { that._styles = styles.reductionPositive } else { if (that._isReduction) { that._styles = styles.reduction } else { if (that._isPositive) { that._styles = styles.positive } else { that._styles = styles } } } }, _getMinTrackerWidth: function() { return 2 + 2 * this._styles.normal["stroke-width"] }, correctCoordinates: function(correctOptions) { var minWidth = this._getMinTrackerWidth(), maxWidth = 10, width = correctOptions.width; width = width < minWidth ? minWidth : width > maxWidth ? maxWidth : width; this.width = width + width % 2; this.xCorrection = correctOptions.offset }, _getMarkerGroup: function(group) { var markerGroup, that = this; if (that._isReduction && that._isPositive) { markerGroup = group.reductionPositiveMarkersGroup } else { if (that._isReduction) { markerGroup = group.reductionMarkersGroup } else { if (that._isPositive) { markerGroup = group.defaultPositiveMarkersGroup } else { markerGroup = group.defaultMarkersGroup } } } return markerGroup }, _drawMarker: function(renderer, group) { this._drawMarkerInGroup(this._getMarkerGroup(group), this._getStyle(), renderer) }, _getSettingsForTracker: function() { var x, y, width, height, that = this, highY = that.highY, lowY = that.lowY, rotated = that._options.rotated; if (highY === lowY) { highY = rotated ? highY + DEFAULT_FINANCIAL_TRACKER_MARGIN : highY - DEFAULT_FINANCIAL_TRACKER_MARGIN; lowY = rotated ? lowY - DEFAULT_FINANCIAL_TRACKER_MARGIN : lowY + DEFAULT_FINANCIAL_TRACKER_MARGIN } if (rotated) { x = _min(lowY, highY); y = that.x - that.width / 2; width = _abs(lowY - highY); height = that.width } else { x = that.x - that.width / 2; y = _min(lowY, highY); width = that.width; height = _abs(lowY - highY) } return { x: x, y: y, width: width, height: height } }, _getGraphicBBox: function() { var that = this, rotated = that._options.rotated, x = that.x, width = that.width, lowY = that.lowY, highY = that.highY; return { x: !rotated ? x - _round(width / 2) : lowY, y: !rotated ? highY : x - _round(width / 2), width: !rotated ? width : highY - lowY, height: !rotated ? lowY - highY : width } }, getTooltipParams: function(location) { var that = this; if (that.graphic) { var x, y, minValue = _min(that.lowY, that.highY), maxValue = _max(that.lowY, that.highY), visibleArea = that._getVisibleArea(), edgeLocation = "edge" === location, rotated = that._options.rotated, minVisible = rotated ? visibleArea.minX : visibleArea.minY, maxVisible = rotated ? visibleArea.maxX : visibleArea.maxY, min = _max(minVisible, minValue), max = _min(maxVisible, maxValue), center = min + (max - min) / 2; if (rotated) { y = that.x; x = edgeLocation ? max : center } else { x = that.x; y = edgeLocation ? min : center } return { x: x, y: y, offset: 0 } } }, hasValue: function() { return null !== this.highValue && null !== this.lowValue }, _translate: function() { var centerValue, that = this, rotated = that._options.rotated, valTranslator = that._getValTranslator(); that.vx = that.vy = that.x = that._getArgTranslator().translate(that.argument) + (that.xCorrection || 0); that.openY = null !== that.openValue ? valTranslator.translate(that.openValue) : null; that.highY = valTranslator.translate(that.highValue); that.lowY = valTranslator.translate(that.lowValue); that.closeY = null !== that.closeValue ? valTranslator.translate(that.closeValue) : null; centerValue = _min(that.lowY, that.highY) + _abs(that.lowY - that.highY) / 2; that._calculateVisibility(!rotated ? that.x : centerValue, !rotated ? centerValue : that.x) }, getCrosshairData: function(x, y) { var yValue, coords, that = this, rotated = that._options.rotated, origY = rotated ? x : y, argument = that.argument, coord = "low"; if (_abs(that.lowY - origY) < _abs(that.closeY - origY)) { yValue = that.lowY } else { yValue = that.closeY; coord = "close" } if (_abs(yValue - origY) >= _abs(that.openY - origY)) { yValue = that.openY; coord = "open" } if (_abs(yValue - origY) >= _abs(that.highY - origY)) { yValue = that.highY; coord = "high" } if (rotated) { coords = { y: that.vy, x: yValue, xValue: that[coord + "Value"], yValue: argument } } else { coords = { x: that.vx, y: yValue, xValue: argument, yValue: that[coord + "Value"] } } coords.axis = that.series.axis; return coords }, _updateData: function(data) { var that = this, label = that._label, reductionColor = this._options.reduction.color; that.value = that.initialValue = data.reductionValue; that.originalValue = data.value; that.lowValue = that.originalLowValue = data.lowValue; that.highValue = that.originalHighValue = data.highValue; that.openValue = that.originalOpenValue = data.openValue; that.closeValue = that.originalCloseValue = data.closeValue; that._isPositive = data.openValue < data.closeValue; that._isReduction = data.isReduction; if (that._isReduction) { label.setColor(reductionColor) } }, _updateMarker: function(animationEnabled, style, group) { var that = this, graphic = that.graphic; graphic.attr({ points: that._getPoints() }).smartAttr(style).sharp(); group && graphic.append(that._getMarkerGroup(group)) }, _getLabelFormatObject: function() { var that = this; return { openValue: that.openValue, highValue: that.highValue, lowValue: that.lowValue, closeValue: that.closeValue, reductionValue: that.initialValue, argument: that.initialArgument, value: that.initialValue, seriesName: that.series.name, originalOpenValue: that.originalOpenValue, originalCloseValue: that.originalCloseValue, originalLowValue: that.originalLowValue, originalHighValue: that.originalHighValue, originalArgument: that.originalArgument, point: that } }, _getFormatObject: function(tooltip) { var that = this, highValue = tooltip.formatValue(that.highValue), openValue = tooltip.formatValue(that.openValue), closeValue = tooltip.formatValue(that.closeValue), lowValue = tooltip.formatValue(that.lowValue), symbolMethods = symbolPoint, formatObject = symbolMethods._getFormatObject.call(that, tooltip); return _extend({}, formatObject, { valueText: "h: " + highValue + ("" !== openValue ? " o: " + openValue : "") + ("" !== closeValue ? " c: " + closeValue : "") + " l: " + lowValue, highValueText: highValue, openValueText: openValue, closeValueText: closeValue, lowValueText: lowValue }) }, getMaxValue: function() { return this.highValue }, getMinValue: function() { return this.lowValue } }) }, /*!*********************************************!*\ !*** ./js/viz/series/points/stock_point.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, isNumeric = __webpack_require__( /*! ../../../core/utils/common */ 14).isNumeric, candlestickPoint = __webpack_require__( /*! ./candlestick_point */ 536), _extend = extend, _isNumeric = isNumeric; module.exports = _extend({}, candlestickPoint, { _getPoints: function() { var points, that = this, createPoint = that._options.rotated ? function(x, y) { return [y, x] } : function(x, y) { return [x, y] }, openYExist = _isNumeric(that.openY), closeYExist = _isNumeric(that.closeY), x = that.x, width = that.width; points = [].concat(createPoint(x, that.highY)); openYExist && (points = points.concat(createPoint(x, that.openY))); openYExist && (points = points.concat(createPoint(x - width / 2, that.openY))); openYExist && (points = points.concat(createPoint(x, that.openY))); closeYExist && (points = points.concat(createPoint(x, that.closeY))); closeYExist && (points = points.concat(createPoint(x + width / 2, that.closeY))); closeYExist && (points = points.concat(createPoint(x, that.closeY))); points = points.concat(createPoint(x, that.lowY)); return points }, _drawMarkerInGroup: function(group, attributes, renderer) { this.graphic = renderer.path(this._getPoints(), "line").attr({ "stroke-linecap": "square" }).attr(attributes).data({ "chart-data-point": this }).sharp().append(group) }, _getMinTrackerWidth: function() { var width = 2 + this._styles.normal["stroke-width"]; return width + width % 2 } }) }, /*!*********************************************!*\ !*** ./js/viz/series/points/polar_point.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../../core/utils/extend */ 11).extend, _extend = extend, commonUtils = __webpack_require__( /*! ../../../core/utils/common */ 14), symbolPoint = __webpack_require__( /*! ./symbol_point */ 528), barPoint = __webpack_require__( /*! ./bar_point */ 531), piePoint = __webpack_require__( /*! ./pie_point */ 533), isDefined = commonUtils.isDefined, vizUtils = __webpack_require__( /*! ../../core/utils */ 509), normalizeAngle = vizUtils.normalizeAngle, _math = Math, _max = _math.max, ERROR_BARS_ANGLE_OFFSET = 90, CANVAS_POSITION_END = "canvas_position_end", CANVAS_POSITION_DEFAULT = "canvas_position_default"; exports.polarSymbolPoint = _extend({}, symbolPoint, { _getLabelCoords: piePoint._getLabelCoords, _moveLabelOnCanvas: barPoint._moveLabelOnCanvas, _getLabelPosition: function() { return "outside" }, _getCoords: function(argument, value) { var axis = this.series.getValueAxis(), startAngle = axis.getAngles()[0], angle = this._getArgTranslator().translate(argument), radius = this._getValTranslator().translate(value), coords = vizUtils.convertPolarToXY(axis.getCenter(), axis.getAngles()[0], angle, radius); coords.angle = angle + startAngle - 90, coords.radius = radius; return coords }, _translate: function() { var that = this, center = that.series.getValueAxis().getCenter(), coord = that._getCoords(that.argument, that.value); that.vx = normalizeAngle(coord.angle); that.vy = that.radiusOuter = that.radiusLabels = coord.radius; that.radius = coord.radius; that.middleAngle = -coord.angle; that.angle = -coord.angle; that.x = coord.x; that.y = coord.y; that.defaultX = that.centerX = center.x; that.defaultY = that.centerY = center.y; that._translateErrorBars(); that.inVisibleArea = true }, _translateErrorBars: function() { var that = this, errorBars = that._options.errorBars, translator = that._getValTranslator(); if (!errorBars) { return } isDefined(that.lowError) && (that._lowErrorCoord = that.centerY - translator.translate(that.lowError)); isDefined(that.highError) && (that._highErrorCoord = that.centerY - translator.translate(that.highError)); that._errorBarPos = that.centerX; that._baseErrorBarPos = "stdDeviation" === errorBars.type ? that._lowErrorCoord + (that._highErrorCoord - that._lowErrorCoord) / 2 : that.centerY - that.radius }, _getTranslates: function(animationEnabled) { return animationEnabled ? this.getDefaultCoords() : { x: this.x, y: this.y } }, getDefaultCoords: function() { var cosSin = vizUtils.getCosAndSin(-this.angle), radius = this._getValTranslator().translate(CANVAS_POSITION_DEFAULT), x = this.defaultX + radius * cosSin.cos, y = this.defaultY + radius * cosSin.sin; return { x: x, y: y } }, _addLabelAlignmentAndOffset: function(label, coord) { return coord }, _checkLabelPosition: function(label, coord) { var that = this, visibleArea = that._getVisibleArea(), graphicBBox = that._getGraphicBBox(); if (that._isPointInVisibleArea(visibleArea, graphicBBox)) { coord = that._moveLabelOnCanvas(coord, visibleArea, label.getBoundingRect()) } return coord }, _getErrorBarSettings: function(errorBarOptions, animationEnabled) { var settings = symbolPoint._getErrorBarSettings.call(this, errorBarOptions, animationEnabled); settings.rotate = ERROR_BARS_ANGLE_OFFSET - this.angle; settings.rotateX = this.centerX; settings.rotateY = this.centerY; return settings }, getCoords: function(min) { return min ? this.getDefaultCoords() : { x: this.x, y: this.y } } }); exports.polarBarPoint = _extend({}, barPoint, { _translateErrorBars: exports.polarSymbolPoint._translateErrorBars, _getErrorBarSettings: exports.polarSymbolPoint._getErrorBarSettings, _moveLabelOnCanvas: barPoint._moveLabelOnCanvas, _getLabelCoords: piePoint._getLabelCoords, _getLabelConnector: piePoint._getLabelConnector, getTooltipParams: piePoint.getTooltipParams, _getLabelPosition: piePoint._getLabelPosition, _getCoords: exports.polarSymbolPoint._getCoords, _translate: function() { var that = this, translator = that._getValTranslator(), maxRadius = translator.translate(CANVAS_POSITION_END); that.radiusInner = translator.translate(that.minValue); exports.polarSymbolPoint._translate.call(that); if (null === that.radiusInner) { that.radiusInner = that.radius = maxRadius } else { if (null === that.radius) { this.radius = this.value >= 0 ? maxRadius : 0 } } that.radiusOuter = that.radiusLabels = _max(that.radiusInner, that.radius); that.radiusInner = that.defaultRadius = _math.min(that.radiusInner, that.radius); that.middleAngle = that.angle = -normalizeAngle(that.middleAngleCorrection - that.angle) }, getMarkerCoords: function() { return { x: this.centerX, y: this.centerY, outerRadius: this.radiusOuter, innerRadius: this.defaultRadius, startAngle: this.middleAngle - this.interval / 2, endAngle: this.middleAngle + this.interval / 2 } }, _drawMarker: function(renderer, group, animationEnabled) { var that = this, styles = that._getStyle(), coords = that.getMarkerCoords(), innerRadius = coords.innerRadius, outerRadius = coords.outerRadius, start = that._getCoords(that.argument, CANVAS_POSITION_DEFAULT), x = coords.x, y = coords.y; if (animationEnabled) { innerRadius = 0; outerRadius = 0; x = start.x; y = start.y } that.graphic = renderer.arc(x, y, innerRadius, outerRadius, coords.startAngle, coords.endAngle).attr(styles).data({ "chart-data-point": that }).append(group) }, _checkLabelPosition: function(label, coord) { var that = this, visibleArea = that._getVisibleArea(), angleFunctions = vizUtils.getCosAndSin(that.middleAngle), x = that.centerX + that.defaultRadius * angleFunctions.cos, y = that.centerY - that.defaultRadius * angleFunctions.sin; if (x > visibleArea.minX && x < visibleArea.maxX && y > visibleArea.minY && y < visibleArea.maxY) { coord = that._moveLabelOnCanvas(coord, visibleArea, label.getBoundingRect()) } return coord }, _addLabelAlignmentAndOffset: function(label, coord) { return coord }, correctCoordinates: function(correctOptions) { this.middleAngleCorrection = correctOptions.offset; this.interval = correctOptions.width }, coordsIn: function(x, y) { var val = vizUtils.convertXYToPolar(this.series.getValueAxis().getCenter(), x, y), coords = this.getMarkerCoords(), isBetweenAngles = coords.startAngle < coords.endAngle ? -val.phi >= coords.startAngle && -val.phi <= coords.endAngle : -val.phi <= coords.startAngle && -val.phi >= coords.endAngle; return val.r >= coords.innerRadius && val.r <= coords.outerRadius && isBetweenAngles } }) }, /*!********************************************************!*\ !*** ./js/viz/series/helpers/range_data_calculator.js ***! \********************************************************/ function(module, exports, __webpack_require__) { var _math = Math, _abs = _math.abs, unique = __webpack_require__( /*! ../../core/utils */ 509).unique, _isDefined = __webpack_require__( /*! ../../../core/utils/common */ 14).isDefined, DISCRETE = "discrete"; function addLabelPaddings(series, valueRange) { var labelOptions = series.getOptions().label; if (series.areLabelsVisible() && labelOptions && labelOptions.visible && "inside" !== labelOptions.position) { if (valueRange.min < 0) { valueRange.minSpaceCorrection = true } if (valueRange.max > 0) { valueRange.maxSpaceCorrection = true } } } function addRangeSeriesLabelPaddings(series, range) { if (series.areLabelsVisible() && series._options.label.visible && "inside" !== series._options.label.position) { range.minSpaceCorrection = range.maxSpaceCorrection = true } } function continuousRangeCalculator(range, minValue, maxValue) { range.min = range.min < minValue ? range.min : minValue; range.max = range.max > maxValue ? range.max : maxValue } function getRangeCalculator(axisType, calcInterval) { if (axisType === DISCRETE) { return function(range, minValue, maxValue) { if (minValue !== maxValue) { range.categories.push(maxValue) } range.categories.push(minValue) } } if (calcInterval) { return function(range, value) { var interval = calcInterval(value, range.prevValue), minInterval = range.interval; range.interval = (minInterval < interval ? minInterval : interval) || minInterval; range.prevValue = value; continuousRangeCalculator(range, value, value) } } return continuousRangeCalculator } function getInitialRange(axisType, dataType, firstValue) { var range = { axisType: axisType, dataType: dataType }; if (axisType === DISCRETE) { range.categories = [] } else { range.min = firstValue; range.max = firstValue } return range } function processCategories(range) { if (range.categories) { range.categories = unique(range.categories) } } function getValueForArgument(point, extraPoint, x) { if (extraPoint) { var y1 = point.value, y2 = extraPoint.value, x1 = point.argument, x2 = extraPoint.argument; return (x - x1) * (y2 - y1) / (x2 - x1) + y1 } else { return point.value } } function getViewPortFilter(viewport) { if (!_isDefined(viewport.max) && !_isDefined(viewport.min)) { return function() { return true } } if (!_isDefined(viewport.max)) { return function(argument) { return argument >= viewport.min } } if (!_isDefined(viewport.min)) { return function(argument) { return argument <= viewport.max } } return function(argument) { return argument >= viewport.min && argument <= viewport.max } } function calculateRangeBetweenPoints(rangeCalculator, range, point, prevPoint, bound) { var value = getValueForArgument(point, prevPoint, bound); rangeCalculator(range, value, value) } function getViewportReducer(series) { var viewportFilter, rangeCalculator = getRangeCalculator(series.valueAxisType), viewport = series.getArgumentAxis() && series.getArgumentAxis().getViewport() || {}; viewportFilter = getViewPortFilter(viewport); return function(range, point, index, points) { var argument = point.argument; if (!point.hasValue()) { return range } if (viewportFilter(argument)) { if (!range.startCalc) { range.startCalc = true; calculateRangeBetweenPoints(rangeCalculator, range, point, points[index - 1], viewport.min) } rangeCalculator(range, point.getMinValue(), point.getMaxValue()) } else { if (_isDefined(viewport.max) && argument > viewport.max) { if (!range.startCalc) { calculateRangeBetweenPoints(rangeCalculator, range, point, points[index - 1], viewport.min) } range.endCalc = true; calculateRangeBetweenPoints(rangeCalculator, range, point, points[index - 1], viewport.max) } } return range } } function getIntervalCalculator(series) { var calcInterval = series.getArgumentAxis() && series.getArgumentAxis().calcInterval; if (calcInterval) { return calcInterval } return function(value, prevValue) { return _abs(value - prevValue) } } module.exports = { getRangeData: function(series) { var points = series.getPoints(), intervalCalculator = getIntervalCalculator(series), argumentCalculator = getRangeCalculator(series.argumentAxisType, points.length > 1 && intervalCalculator), valueRangeCalculator = getRangeCalculator(series.valueAxisType), viewportReducer = getViewportReducer(series), range = points.reduce(function(range, point, index, points) { var argument = point.argument; argumentCalculator(range.arg, argument, argument); if (point.hasValue()) { valueRangeCalculator(range.val, point.getMinValue(), point.getMaxValue()); viewportReducer(range.viewport, point, index, points) } return range }, { arg: getInitialRange(series.argumentAxisType, series.argumentType, points.length ? points[0].argument : void 0), val: getInitialRange(series.valueAxisType, series.valueType, points.length ? series.getValueRangeInitialValue() : void 0), viewport: getInitialRange(series.valueAxisType, series.valueType, points.length ? series.getValueRangeInitialValue() : void 0) }); processCategories(range.arg); processCategories(range.val); return range }, getViewport: function(series) { var reducer, points = series.getPoints(), range = {}; if (series.valueAxisType !== DISCRETE && series.argumentAxisType !== DISCRETE) { reducer = getViewportReducer(series); range = getInitialRange(series.valueAxisType, series.valueType, points.length ? series.getValueRangeInitialValue() : void 0); points.some(function(point, index) { reducer(range, point, index, points); return range.endCalc }) } return range }, addLabelPaddings: addLabelPaddings, addRangeSeriesLabelPaddings: addRangeSeriesLabelPaddings } }, /*!*****************************************!*\ !*** ./js/viz/series/scatter_series.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, rangeCalculator = __webpack_require__( /*! ./helpers/range_data_calculator */ 539), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), vizUtils = __webpack_require__( /*! ../core/utils */ 509), _each = $.each, _extend = extend, _noop = commonUtils.noop, _isDefined = commonUtils.isDefined, _isString = commonUtils.isString, _map = vizUtils.map, _normalizeEnum = vizUtils.normalizeEnum, math = Math, _floor = math.floor, _abs = math.abs, _sqrt = math.sqrt, _min = math.min, _max = math.max, DEFAULT_SYMBOL_POINT_SIZE = 2, DEFAULT_TRACKER_WIDTH = 12, DEFAULT_DURATION = 400, HIGH_ERROR = "highError", LOW_ERROR = "lowError", ORIGINAL = "original", VARIANCE = "variance", STANDARD_DEVIATION = "stddeviation", STANDARD_ERROR = "stderror", PERCENT = "percent", FIXED = "fixed", UNDEFINED = "undefined", DISCRETE = "discrete", LOGARITHMIC = "logarithmic", DATETIME = "datetime"; exports.chart = {}; exports.polar = {}; function sum(array) { var result = 0; _each(array, function(_, value) { result += value }); return result } function isErrorBarTypeCorrect(type) { return inArray(type, [FIXED, PERCENT, VARIANCE, STANDARD_DEVIATION, STANDARD_ERROR]) !== -1 } function variance(array, expectedValue) { return sum(_map(array, function(value) { return (value - expectedValue) * (value - expectedValue) })) / array.length } var baseScatterMethods = { _defaultDuration: DEFAULT_DURATION, _defaultTrackerWidth: DEFAULT_TRACKER_WIDTH, _applyStyle: _noop, _updateOptions: _noop, _parseStyle: _noop, _prepareSegment: _noop, _drawSegment: _noop, _generateDefaultSegments: _noop, _prepareSeriesToDrawing: function() { var that = this; that._deleteOldAnimationMethods(); that._disposePoints(that._oldPoints); that._oldPoints = null }, _appendInGroup: function() { this._group.append(this._extGroups.seriesGroup) }, _createLegendState: function(styleOptions, defaultColor) { return { fill: styleOptions.color || defaultColor, hatching: styleOptions.hatching } }, updateTemplateFieldNames: function() { var that = this, options = that._options; options.valueField = that.getValueFields()[0] + that.name; options.tagField = that.getTagField() + that.name }, _applyElementsClipRect: function(settings) { settings["clip-path"] = this._paneClipRectID }, _applyMarkerClipRect: function(settings) { settings["clip-path"] = this._forceClipping ? this._paneClipRectID : null }, _createGroup: function(groupName, parent, target, settings) { var group = parent[groupName] = parent[groupName] || this._renderer.g(); target && group.append(target); settings && group.attr(settings) }, _applyClearingSettings: function(settings) { settings.opacity = null; settings.scale = null; if (this._options.rotated) { settings.translateX = null } else { settings.translateY = null } }, _createGroups: function() { var that = this; that._createGroup("_markersGroup", that, that._group); that._createGroup("_labelsGroup", that) }, _setMarkerGroupSettings: function() { var that = this, settings = that._createPointStyles(that._getMarkerGroupOptions()).normal; settings.class = "dxc-markers"; settings.opacity = 1; that._applyMarkerClipRect(settings); that._markersGroup.attr(settings) }, getVisibleArea: function() { return this._visibleArea }, areErrorBarsVisible: function() { var errorBarOptions = this._options.valueErrorBar; return errorBarOptions && this._errorBarsEnabled() && "none" !== errorBarOptions.displayMode && (isErrorBarTypeCorrect(_normalizeEnum(errorBarOptions.type)) || _isDefined(errorBarOptions.lowValueField) || _isDefined(errorBarOptions.highValueField)) }, _createErrorBarGroup: function(animationEnabled) { var settings, that = this, errorBarOptions = that._options.valueErrorBar; if (that.areErrorBarsVisible()) { settings = { "class": "dxc-error-bars", stroke: errorBarOptions.color, "stroke-width": errorBarOptions.lineWidth, opacity: animationEnabled ? .001 : errorBarOptions.opacity || 1, "stroke-linecap": "square", sharp: true, "clip-path": that._forceClipping ? that._paneClipRectID : that._widePaneClipRectID }; that._createGroup("_errorBarGroup", that, that._group, settings) } }, _setGroupsSettings: function(animationEnabled) { var that = this; that._setMarkerGroupSettings(); that._setLabelGroupSettings(animationEnabled); that._createErrorBarGroup(animationEnabled) }, _getCreatingPointOptions: function() { var defaultPointOptions, normalStyle, that = this, creatingPointOptions = that._predefinedPointOptions; if (!creatingPointOptions) { defaultPointOptions = that._getPointOptions(); that._predefinedPointOptions = creatingPointOptions = _extend(true, { styles: {} }, defaultPointOptions); normalStyle = defaultPointOptions.styles && defaultPointOptions.styles.normal || {}; creatingPointOptions.styles = creatingPointOptions.styles || {}; creatingPointOptions.styles.normal = { "stroke-width": normalStyle["stroke-width"], r: normalStyle.r, opacity: normalStyle.opacity } } return creatingPointOptions }, _getPointOptions: function() { return this._parsePointOptions(this._preparePointOptions(), this._options.label) }, _getOptionsForPoint: function() { return this._options.point }, _parsePointStyle: function(style, defaultColor, defaultBorderColor, defaultSize) { var border = style.border || {}, sizeValue = void 0 !== style.size ? style.size : defaultSize; return { fill: style.color || defaultColor, stroke: border.color || defaultBorderColor, "stroke-width": border.visible ? border.width : 0, r: sizeValue / 2 + (border.visible && 0 !== sizeValue ? ~~(border.width / 2) || 0 : 0) } }, _createPointStyles: function(pointOptions) { var that = this, mainPointColor = pointOptions.color || that._options.mainSeriesColor, containerColor = that._options.containerBackgroundColor, normalStyle = that._parsePointStyle(pointOptions, mainPointColor, mainPointColor); normalStyle.visibility = pointOptions.visible ? "visible" : "hidden"; return { normal: normalStyle, hover: that._parsePointStyle(pointOptions.hoverStyle, containerColor, mainPointColor, pointOptions.size), selection: that._parsePointStyle(pointOptions.selectionStyle, containerColor, mainPointColor, pointOptions.size) } }, _checkData: function(data) { return _isDefined(data.argument) && void 0 !== data.value }, getErrorBarRangeCorrector: function() { var mode, func; if (this.areErrorBarsVisible()) { mode = _normalizeEnum(this._options.valueErrorBar.displayMode); func = function(point) { var lowError = point.lowError, highError = point.highError; switch (mode) { case "low": return [lowError]; case "high": return [highError]; case "none": return []; default: return [lowError, highError] } } } return func }, getValueRangeInitialValue: function() { return }, _getRangeData: function() { return rangeCalculator.getRangeData(this) }, _processRange: function(range) { rangeCalculator.addLabelPaddings(this, range.val) }, _getPointData: function(data, options) { var pointData = { value: data[options.valueField || "val"], argument: data[options.argumentField || "arg"], tag: data[options.tagField || "tag"] }; this._fillErrorBars(data, pointData, options); return pointData }, _errorBarsEnabled: function() { return this.valueAxisType !== DISCRETE && this.valueAxisType !== LOGARITHMIC && this.valueType !== DATETIME }, _fillErrorBars: function(data, pointData, options) { var errorBars = options.valueErrorBar; if (this.areErrorBarsVisible()) { pointData.lowError = data[errorBars.lowValueField || LOW_ERROR]; pointData.highError = data[errorBars.highValueField || HIGH_ERROR] } }, _drawPoint: function(options) { var point = options.point; if (point.isInVisibleArea()) { point.clearVisibility(); point.draw(this._renderer, options.groups, options.hasAnimation, options.firstDrawing); this._drawnPoints.push(point) } else { point.setInvisibility() } }, _clearingAnimation: function(drawComplete) { var that = this, params = { opacity: .001 }, options = { duration: that._defaultDuration, partitionDuration: .5 }; that._labelsGroup && that._labelsGroup.animate(params, options, function() { that._markersGroup && that._markersGroup.animate(params, options, drawComplete) }) }, _animateComplete: function() { var that = this, animationSettings = { duration: that._defaultDuration }; that._labelsGroup && that._labelsGroup.animate({ opacity: 1 }, animationSettings); that._errorBarGroup && that._errorBarGroup.animate({ opacity: that._options.valueErrorBar.opacity || 1 }, animationSettings) }, _animate: function() { var that = this, lastPointIndex = that._drawnPoints.length - 1; _each(that._drawnPoints || [], function(i, p) { p.animate(i === lastPointIndex ? function() { that._animateComplete() } : void 0, { translateX: p.x, translateY: p.y }) }) }, _getPointSize: function() { return this._options.point.visible ? this._options.point.size : DEFAULT_SYMBOL_POINT_SIZE }, _calcMedianValue: function(fusionPoints, valueField) { var result, allValue = _map(fusionPoints, function(point) { return _isDefined(point[valueField]) ? point[valueField] : null }); allValue.sort(function(a, b) { return a - b }); result = allValue[_floor(allValue.length / 2)]; return _isDefined(result) ? result : null }, _calcErrorBarValues: function(fusionPoints) { if (!fusionPoints.length) { return {} } var lowError, highError, lowValue = fusionPoints[0].lowError, highValue = fusionPoints[0].highError, i = 1, length = fusionPoints.length; for (i; i < length; i++) { lowError = fusionPoints[i].lowError; highError = fusionPoints[i].highError; if (_isDefined(lowError) && _isDefined(highError)) { lowValue = _min(lowError, lowValue); highValue = _max(highError, highValue) } } return { low: lowValue, high: highValue } }, _fusionPoints: function(fusionPoints, tick, index) { var errorBarValues = this._calcErrorBarValues(fusionPoints); return { value: this._calcMedianValue(fusionPoints, "value"), argument: tick, tag: null, index: index, seriesName: this.name, lowError: errorBarValues.low, highError: errorBarValues.high } }, _endUpdateData: function() { delete this._predefinedPointOptions }, getArgumentField: function() { return this._options.argumentField || "arg" }, getValueFields: function() { var lowValueField, highValueField, options = this._options, errorBarsOptions = options.valueErrorBar, valueFields = [options.valueField || "val"]; if (errorBarsOptions) { lowValueField = errorBarsOptions.lowValueField; highValueField = errorBarsOptions.highValueField; _isString(lowValueField) && valueFields.push(lowValueField); _isString(highValueField) && valueFields.push(highValueField) } return valueFields }, _calculateErrorBars: function(data) { if (!this.areErrorBarsVisible()) { return } var value, valueArray, valueArrayLength, meanValue, processDataItem, that = this, options = that._options, errorBarsOptions = options.valueErrorBar, errorBarType = _normalizeEnum(errorBarsOptions.type), floatErrorValue = parseFloat(errorBarsOptions.value), valueField = that.getValueFields()[0], lowValueField = errorBarsOptions.lowValueField || LOW_ERROR, highValueField = errorBarsOptions.highValueField || HIGH_ERROR, addSubError = function(_i, item) { value = item[valueField]; item[lowValueField] = value - floatErrorValue; item[highValueField] = value + floatErrorValue }; switch (errorBarType) { case FIXED: processDataItem = addSubError; break; case PERCENT: processDataItem = function(_, item) { value = item[valueField]; var error = value * floatErrorValue / 100; item[lowValueField] = value - error; item[highValueField] = value + error }; break; case UNDEFINED: processDataItem = function(_, item) { item[lowValueField] = item[ORIGINAL + lowValueField]; item[highValueField] = item[ORIGINAL + highValueField] }; break; default: valueArray = _map(data, function(item) { return _isDefined(item[valueField]) ? item[valueField] : null }); valueArrayLength = valueArray.length; floatErrorValue = floatErrorValue || 1; switch (errorBarType) { case VARIANCE: floatErrorValue = variance(valueArray, sum(valueArray) / valueArrayLength) * floatErrorValue; processDataItem = addSubError; break; case STANDARD_DEVIATION: meanValue = sum(valueArray) / valueArrayLength; floatErrorValue = _sqrt(variance(valueArray, meanValue)) * floatErrorValue; processDataItem = function(_, item) { item[lowValueField] = meanValue - floatErrorValue; item[highValueField] = meanValue + floatErrorValue }; break; case STANDARD_ERROR: floatErrorValue = _sqrt(variance(valueArray, sum(valueArray) / valueArrayLength) / valueArrayLength) * floatErrorValue; processDataItem = addSubError } } processDataItem && _each(data, processDataItem) }, _beginUpdateData: function(data) { this._calculateErrorBars(data) } }; exports.chart = _extend({}, baseScatterMethods, { drawTrackers: function() { var trackers, trackersGroup, that = this, segments = that._segments || [], rotated = that._options.rotated, cat = []; if (!that.isVisible()) { return } if (segments.length) { trackers = that._trackers = that._trackers || []; trackersGroup = that._trackersGroup = (that._trackersGroup || that._renderer.g().attr({ fill: "gray", opacity: .001, stroke: "gray", "class": "dxc-trackers" })).attr({ "clip-path": this._paneClipRectID || null }).append(that._group); _each(segments, function(i, segment) { if (!trackers[i]) { trackers[i] = that._drawTrackerElement(segment).data({ "chart-data-series": that }).append(trackersGroup) } else { that._updateTrackerElement(segment, trackers[i]) } }) } that._trackersTranslator = cat; _each(that.getVisiblePoints(), function(_, p) { var pointCoord = parseInt(rotated ? p.vy : p.vx); if (!cat[pointCoord]) { cat[pointCoord] = p } else { Array.isArray(cat[pointCoord]) ? cat[pointCoord].push(p) : cat[pointCoord] = [cat[pointCoord], p] } }) }, getNeighborPoint: function(x, y) { var minDistance, pCoord = this._options.rotated ? y : x, nCoord = pCoord, cat = this._trackersTranslator, point = null, oppositeCoord = this._options.rotated ? x : y, oppositeCoordName = this._options.rotated ? "vx" : "vy"; if (this.isVisible() && cat) { point = cat[pCoord]; do { point = cat[nCoord] || cat[pCoord]; pCoord--; nCoord++ } while ((pCoord >= 0 || nCoord < cat.length) && !point); if (Array.isArray(point)) { minDistance = _abs(point[0][oppositeCoordName] - oppositeCoord); _each(point, function(i, p) { var distance = _abs(p[oppositeCoordName] - oppositeCoord); if (minDistance >= distance) { minDistance = distance; point = p } }) } } return point }, _applyVisibleArea: function() { var that = this, rotated = that._options.rotated, visibleX = (rotated ? that.getValueAxis() : that.getArgumentAxis()).getTranslator().getCanvasVisibleArea(), visibleY = (rotated ? that.getArgumentAxis() : that.getValueAxis()).getTranslator().getCanvasVisibleArea(); that._visibleArea = { minX: visibleX.min, maxX: visibleX.max, minY: visibleY.min, maxY: visibleY.max } } }); exports.polar = _extend({}, baseScatterMethods, { drawTrackers: function() { exports.chart.drawTrackers.call(this); var index, cat = this._trackersTranslator; if (!this.isVisible()) { return } _each(cat, function(i, category) { if (category) { index = i; return false } }); cat[index + 360] = cat[index] }, getNeighborPoint: function(x, y) { var pos = vizUtils.convertXYToPolar(this.getValueAxis().getCenter(), x, y); return exports.chart.getNeighborPoint.call(this, pos.phi, pos.r) }, _applyVisibleArea: function() { var that = this, canvas = that.getValueAxis().getCanvas(); that._visibleArea = { minX: canvas.left, maxX: canvas.width - canvas.right, minY: canvas.top, maxY: canvas.height - canvas.bottom } } }) }, /*!**************************************!*\ !*** ./js/viz/series/line_series.js ***! \**************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), series = __webpack_require__( /*! ./scatter_series */ 540), chartScatterSeries = series.chart, polarScatterSeries = series.polar, objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, vizUtils = __webpack_require__( /*! ../core/utils */ 509), normalizeAngle = vizUtils.normalizeAngle, DISCRETE = "discrete", _map = vizUtils.map, _extend = extend, _each = $.each; exports.chart = {}; exports.polar = {}; function clonePoint(point, newX, newY, newAngle) { var p = objectUtils.clone(point); p.x = newX; p.y = newY; p.angle = newAngle; return p } function getTangentPoint(point, prevPoint, centerPoint, tan, nextStepAngle) { var correctAngle = point.angle + nextStepAngle, cosSin = vizUtils.getCosAndSin(correctAngle), x = centerPoint.x + (point.radius + tan * nextStepAngle) * cosSin.cos, y = centerPoint.y - (point.radius + tan * nextStepAngle) * cosSin.sin; return clonePoint(prevPoint, x, y, correctAngle) } var lineMethods = { _applyGroupSettings: function(style, settings, group) { var that = this; settings = _extend(settings, style); that._applyElementsClipRect(settings); group.attr(settings) }, _setGroupsSettings: function(animationEnabled) { var that = this, style = that._styles.normal; that._applyGroupSettings(style.elements, { "class": "dxc-elements" }, that._elementsGroup); that._bordersGroup && that._applyGroupSettings(style.border, { "class": "dxc-borders" }, that._bordersGroup); chartScatterSeries._setGroupsSettings.call(that, animationEnabled); animationEnabled && that._markersGroup && that._markersGroup.attr({ opacity: .001 }) }, _createGroups: function() { var that = this; that._createGroup("_elementsGroup", that, that._group); that._areBordersVisible() && that._createGroup("_bordersGroup", that, that._group); chartScatterSeries._createGroups.call(that) }, _areBordersVisible: function() { return false }, _getDefaultSegment: function(segment) { return { line: _map(segment.line || [], function(pt) { return pt.getDefaultCoords() }) } }, _prepareSegment: function(points) { return { line: points } }, _parseLineOptions: function(options, defaultColor) { return { stroke: options.color || defaultColor, "stroke-width": options.width, dashStyle: options.dashStyle || "solid" } }, _parseStyle: function(options, defaultColor) { return { elements: this._parseLineOptions(options, defaultColor) } }, _applyStyle: function(style) { var that = this; that._elementsGroup && that._elementsGroup.attr(style.elements); _each(that._graphics || [], function(_, graphic) { graphic.line && graphic.line.attr({ "stroke-width": style.elements["stroke-width"] }).sharp() }) }, _drawElement: function(segment, group) { return { line: this._createMainElement(segment.line, { "stroke-width": this._styles.normal.elements["stroke-width"] }).append(group) } }, _removeElement: function(element) { element.line.remove() }, _generateDefaultSegments: function() { var that = this; return _map(that._segments || [], function(segment) { return that._getDefaultSegment(segment) }) }, _updateElement: function(element, segment, animate, animateParams, complete) { var params = { points: segment.line }, lineElement = element.line; animate ? lineElement.animate(params, animateParams, complete) : lineElement.attr(params) }, _clearingAnimation: function(drawComplete) { var that = this, lastIndex = that._graphics.length - 1, settings = { opacity: .001 }, options = { duration: that._defaultDuration, partitionDuration: .5 }; that._labelsGroup && that._labelsGroup.animate(settings, options, function() { that._markersGroup && that._markersGroup.animate(settings, options, function() { _each(that._defaultSegments || [], function(i, segment) { that._oldUpdateElement(that._graphics[i], segment, true, { partitionDuration: .5 }, i === lastIndex ? drawComplete : void 0) }) }) }) }, _animateComplete: function() { var that = this; chartScatterSeries._animateComplete.call(this); that._markersGroup && that._markersGroup.animate({ opacity: 1 }, { duration: that._defaultDuration }) }, _animate: function() { var that = this, lastIndex = that._graphics.length - 1; _each(that._graphics || [], function(i, elem) { that._updateElement(elem, that._segments[i], true, { complete: i === lastIndex ? function() { that._animateComplete() } : void 0 }) }) }, _drawPoint: function(options) { chartScatterSeries._drawPoint.call(this, { point: options.point, groups: options.groups }) }, _createMainElement: function(points, settings) { return this._renderer.path(points, "line").attr(settings).sharp() }, _drawSegment: function(points, animationEnabled, segmentCount, lastSegment) { var that = this, segment = that._prepareSegment(points, that._options.rotated, lastSegment); that._segments.push(segment); if (!that._graphics[segmentCount]) { that._graphics[segmentCount] = that._drawElement(animationEnabled ? that._getDefaultSegment(segment) : segment, that._elementsGroup) } else { if (!animationEnabled) { that._updateElement(that._graphics[segmentCount], segment) } } }, _getTrackerSettings: function() { var that = this, defaultTrackerWidth = that._defaultTrackerWidth, strokeWidthFromElements = that._styles.normal.elements["stroke-width"]; return { "stroke-width": strokeWidthFromElements > defaultTrackerWidth ? strokeWidthFromElements : defaultTrackerWidth, fill: "none" } }, _getMainPointsFromSegment: function(segment) { return segment.line }, _drawTrackerElement: function(segment) { return this._createMainElement(this._getMainPointsFromSegment(segment), this._getTrackerSettings(segment)) }, _updateTrackerElement: function(segment, element) { var settings = this._getTrackerSettings(segment); settings.points = this._getMainPointsFromSegment(segment); element.attr(settings) } }; exports.chart.line = _extend({}, chartScatterSeries, lineMethods); exports.chart.stepline = _extend({}, exports.chart.line, { _calculateStepLinePoints: function(points) { var segment = []; _each(points, function(i, pt) { var stepY, point; if (!i) { segment.push(pt); return } stepY = segment[segment.length - 1].y; if (stepY !== pt.y) { point = objectUtils.clone(pt); point.y = stepY; segment.push(point) } segment.push(pt) }); return segment }, _prepareSegment: function(points) { return exports.chart.line._prepareSegment(this._calculateStepLinePoints(points)) } }); exports.chart.spline = _extend({}, exports.chart.line, { _calculateBezierPoints: function(src, rotated) { var bezierPoints = [], pointsCopy = src, checkExtremum = function(otherPointCoord, pointCoord, controlCoord) { return otherPointCoord > pointCoord && controlCoord > otherPointCoord || otherPointCoord < pointCoord && controlCoord < otherPointCoord ? otherPointCoord : controlCoord }; if (1 !== pointsCopy.length) { pointsCopy.forEach(function(curPoint, i) { var leftControlX, leftControlY, rightControlX, rightControlY, xCur, yCur, x1, x2, y1, y2, curIsExtremum, leftPoint, rightPoint, a, b, c, xc, yc, shift, prevPoint = pointsCopy[i - 1], nextPoint = pointsCopy[i + 1], lambda = .5; if (!i || i === pointsCopy.length - 1) { bezierPoints.push(curPoint, curPoint); return } xCur = curPoint.x; yCur = curPoint.y; x1 = prevPoint.x; x2 = nextPoint.x; y1 = prevPoint.y; y2 = nextPoint.y; curIsExtremum = !!(!rotated && (yCur <= prevPoint.y && yCur <= nextPoint.y || yCur >= prevPoint.y && yCur >= nextPoint.y) || rotated && (xCur <= prevPoint.x && xCur <= nextPoint.x || xCur >= prevPoint.x && xCur >= nextPoint.x)); if (curIsExtremum) { if (!rotated) { rightControlY = leftControlY = yCur; rightControlX = (xCur + nextPoint.x) / 2; leftControlX = (xCur + prevPoint.x) / 2 } else { rightControlX = leftControlX = xCur; rightControlY = (yCur + nextPoint.y) / 2; leftControlY = (yCur + prevPoint.y) / 2 } } else { a = y2 - y1; b = x1 - x2; c = y1 * x2 - x1 * y2; if (!rotated) { if (!b) { bezierPoints.push(curPoint, curPoint, curPoint); return } xc = xCur; yc = -1 * (a * xc + c) / b; shift = yc - yCur; y1 -= shift; y2 -= shift } else { if (!a) { bezierPoints.push(curPoint, curPoint, curPoint); return } yc = yCur; xc = -1 * (b * yc + c) / a; shift = xc - xCur; x1 -= shift; x2 -= shift } rightControlX = (xCur + lambda * x2) / (1 + lambda); rightControlY = (yCur + lambda * y2) / (1 + lambda); leftControlX = (xCur + lambda * x1) / (1 + lambda); leftControlY = (yCur + lambda * y1) / (1 + lambda) } if (!rotated) { leftControlY = checkExtremum(prevPoint.y, yCur, leftControlY); rightControlY = checkExtremum(nextPoint.y, yCur, rightControlY) } else { leftControlX = checkExtremum(prevPoint.x, xCur, leftControlX); rightControlX = checkExtremum(nextPoint.x, xCur, rightControlX) } leftPoint = clonePoint(curPoint, leftControlX, leftControlY); rightPoint = clonePoint(curPoint, rightControlX, rightControlY); bezierPoints.push(leftPoint, curPoint, rightPoint) }) } else { bezierPoints.push(pointsCopy[0]) } return bezierPoints }, _prepareSegment: function(points, rotated) { return exports.chart.line._prepareSegment(this._calculateBezierPoints(points, rotated)) }, _createMainElement: function(points, settings) { return this._renderer.path(points, "bezier").attr(settings).sharp() } }); exports.polar.line = _extend({}, polarScatterSeries, lineMethods, { _prepareSegment: function(points, rotated, lastSegment) { var i, preparedPoints = [], centerPoint = this.getValueAxis().getCenter(); lastSegment && this._closeSegment(points); if (this.argumentAxisType !== DISCRETE && this.valueAxisType !== DISCRETE) { for (i = 1; i < points.length; i++) { preparedPoints = preparedPoints.concat(this._getTangentPoints(points[i], points[i - 1], centerPoint)) } if (!preparedPoints.length) { preparedPoints = points } } else { return exports.chart.line._prepareSegment.apply(this, arguments) } return { line: preparedPoints } }, _getRemainingAngle: function(angle) { var normAngle = normalizeAngle(angle); return angle >= 0 ? 360 - normAngle : -normAngle }, _closeSegment: function(points) { var point, differenceAngle; if (this._segments.length) { point = this._segments[0].line[0] } else { point = clonePoint(points[0], points[0].x, points[0].y, points[0].angle) } if (points[points.length - 1].angle !== point.angle) { if (normalizeAngle(Math.round(points[points.length - 1].angle)) === normalizeAngle(Math.round(point.angle))) { point.angle = points[points.length - 1].angle } else { differenceAngle = points[points.length - 1].angle - point.angle; point.angle = points[points.length - 1].angle + this._getRemainingAngle(differenceAngle) } points.push(point) } }, _getTangentPoints: function(point, prevPoint, centerPoint) { var i, tangentPoints = [], betweenAngle = Math.round(prevPoint.angle - point.angle), tan = (prevPoint.radius - point.radius) / betweenAngle; if (0 === betweenAngle) { tangentPoints = [prevPoint, point] } else { if (betweenAngle > 0) { for (i = betweenAngle; i >= 0; i--) { tangentPoints.push(getTangentPoint(point, prevPoint, centerPoint, tan, i)) } } else { for (i = 0; i >= betweenAngle; i--) { tangentPoints.push(getTangentPoint(point, prevPoint, centerPoint, tan, betweenAngle - i)) } } } return tangentPoints } }) }, /*!**************************************!*\ !*** ./js/viz/series/area_series.js ***! \**************************************/ function(module, exports, __webpack_require__) { var objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, scatterSeries = __webpack_require__( /*! ./scatter_series */ 540).chart, lineSeries = __webpack_require__( /*! ./line_series */ 541), chartLineSeries = lineSeries.chart.line, polarLineSeries = lineSeries.polar.line, _map = __webpack_require__( /*! ../core/utils */ 509).map, _extend = extend; exports.chart = {}; exports.polar = {}; var baseAreaMethods = { _createBorderElement: chartLineSeries._createMainElement, _createLegendState: function(styleOptions, defaultColor) { var legendState = scatterSeries._createLegendState.call(this, styleOptions, defaultColor); legendState.opacity = styleOptions.opacity; return legendState }, getValueRangeInitialValue: function() { if ("logarithmic" !== this.valueAxisType && "datetime" !== this.valueType && false !== this.showZero) { return 0 } else { return scatterSeries.getValueRangeInitialValue.call(this) } }, _getDefaultSegment: function(segment) { var defaultSegment = chartLineSeries._getDefaultSegment(segment); defaultSegment.area = defaultSegment.line.concat(defaultSegment.line.slice().reverse()); return defaultSegment }, _updateElement: function(element, segment, animate, animateParams, complete) { var lineParams = { points: segment.line }, areaParams = { points: segment.area }, borderElement = element.line; if (animate) { borderElement && borderElement.animate(lineParams, animateParams); element.area.animate(areaParams, animateParams, complete) } else { borderElement && borderElement.attr(lineParams); element.area.attr(areaParams) } }, _removeElement: function(element) { element.line && element.line.remove(); element.area.remove() }, _drawElement: function(segment) { return { line: this._bordersGroup && this._createBorderElement(segment.line, { "stroke-width": this._styles.normal.border["stroke-width"] }).append(this._bordersGroup), area: this._createMainElement(segment.area).append(this._elementsGroup) } }, _applyStyle: function(style) { var that = this; that._elementsGroup && that._elementsGroup.smartAttr(style.elements); that._bordersGroup && that._bordersGroup.attr(style.border); (that._graphics || []).forEach(function(graphic) { graphic.line && graphic.line.attr({ "stroke-width": style.border["stroke-width"] }).sharp() }) }, _parseStyle: function(options, defaultColor, defaultBorderColor) { var borderOptions = options.border || {}, borderStyle = chartLineSeries._parseLineOptions(borderOptions, defaultBorderColor); borderStyle.stroke = borderOptions.visible && borderStyle["stroke-width"] ? borderStyle.stroke : "none"; borderStyle["stroke-width"] = borderStyle["stroke-width"] || 1; return { border: borderStyle, elements: { stroke: "none", fill: options.color || defaultColor, hatching: options.hatching, opacity: options.opacity } } }, _areBordersVisible: function() { var options = this._options; return options.border.visible || options.hoverStyle.border.visible || options.selectionStyle.border.visible }, _createMainElement: function(points, settings) { return this._renderer.path(points, "area").attr(settings) }, _getTrackerSettings: function(segment) { return { "stroke-width": segment.singlePointSegment ? this._defaultTrackerWidth : 0 } }, _getMainPointsFromSegment: function(segment) { return segment.area } }; exports.chart.area = _extend({}, chartLineSeries, baseAreaMethods, { _prepareSegment: function(points, rotated) { var processedPoints = this._processSinglePointsAreaSegment(points, rotated); return { line: processedPoints, area: _map(processedPoints, function(pt) { return pt.getCoords() }).concat(_map(processedPoints.slice().reverse(), function(pt) { return pt.getCoords(true) })), singlePointSegment: processedPoints !== points } }, _processSinglePointsAreaSegment: function(points, rotated) { if (1 === points.length) { var p = points[0], p1 = objectUtils.clone(p); p1[rotated ? "y" : "x"] += 1; p1.argument = null; return [p, p1] } return points } }); exports.polar.area = _extend({}, polarLineSeries, baseAreaMethods, { _prepareSegment: function(points, rotated, lastSegment) { lastSegment && polarLineSeries._closeSegment.call(this, points); var preparedPoints = exports.chart.area._prepareSegment.call(this, points); return preparedPoints }, _processSinglePointsAreaSegment: function(points) { return lineSeries.polar.line._prepareSegment.call(this, points).line } }); exports.chart.steparea = _extend({}, exports.chart.area, { _prepareSegment: function(points, rotated) { points = exports.chart.area._processSinglePointsAreaSegment(points, rotated); return exports.chart.area._prepareSegment.call(this, lineSeries.chart.stepline._calculateStepLinePoints(points)) } }); exports.chart.splinearea = _extend({}, exports.chart.area, { _areaPointsToSplineAreaPoints: function(areaPoints) { var previousMiddlePoint = areaPoints[areaPoints.length / 2 - 1], middlePoint = areaPoints[areaPoints.length / 2]; areaPoints.splice(areaPoints.length / 2, 0, { x: previousMiddlePoint.x, y: previousMiddlePoint.y }, { x: middlePoint.x, y: middlePoint.y }); if (previousMiddlePoint.defaultCoords) { areaPoints[areaPoints.length / 2].defaultCoords = true } if (middlePoint.defaultCoords) { areaPoints[areaPoints.length / 2 - 1].defaultCoords = true } }, _prepareSegment: function(points, rotated) { var areaSeries = exports.chart.area, processedPoints = areaSeries._processSinglePointsAreaSegment(points, rotated), areaSegment = areaSeries._prepareSegment.call(this, lineSeries.chart.spline._calculateBezierPoints(processedPoints, rotated)); this._areaPointsToSplineAreaPoints(areaSegment.area); areaSegment.singlePointSegment = processedPoints !== points; return areaSegment }, _getDefaultSegment: function(segment) { var areaDefaultSegment = exports.chart.area._getDefaultSegment(segment); this._areaPointsToSplineAreaPoints(areaDefaultSegment.area); return areaDefaultSegment }, _createMainElement: function(points, settings) { return this._renderer.path(points, "bezierarea").attr(settings) }, _createBorderElement: lineSeries.chart.spline._createMainElement }) }, /*!*************************************!*\ !*** ./js/viz/series/bar_series.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, scatterSeries = __webpack_require__( /*! ./scatter_series */ 540), areaSeries = __webpack_require__( /*! ./area_series */ 542).chart.area, chartSeries = scatterSeries.chart, polarSeries = scatterSeries.polar, _extend = extend, _each = $.each, DEFAULT_BAR_POINT_SIZE = 3; exports.chart = {}; exports.polar = {}; var baseBarSeriesMethods = { _updateOptions: function(options) { this._stackName = "axis_" + (options.axis || "default") + "_stack_" + (options.stack || "default") }, _parsePointStyle: function(style, defaultColor, defaultBorderColor) { var color = style.color || defaultColor, base = chartSeries._parsePointStyle.call(this, style, color, defaultBorderColor); base.fill = color; base.hatching = style.hatching; base.dashStyle = style.border && style.border.dashStyle || "solid"; delete base.r; return base }, _applyMarkerClipRect: function(settings) { settings["clip-path"] = null }, _clearingAnimation: function(drawComplete) { var that = this, settings = that._oldGetAffineCoordOptions() || that._getAffineCoordOptions(); that._labelsGroup && that._labelsGroup.animate({ opacity: .001 }, { duration: that._defaultDuration, partitionDuration: .5 }, function() { that._markersGroup.animate(settings, { partitionDuration: .5 }, function() { that._markersGroup.attr({ scaleX: null, scaleY: null, translateX: 0, translateY: 0 }); drawComplete() }) }) }, _setGroupsSettings: function(animationEnabled, firstDrawing) { var that = this, settings = {}; chartSeries._setGroupsSettings.apply(that, arguments); if (animationEnabled && firstDrawing) { settings = this._getAffineCoordOptions() } else { if (!animationEnabled) { settings = { scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 } } } that._markersGroup.attr(settings) }, _drawPoint: function(options) { options.hasAnimation = options.hasAnimation && !options.firstDrawing; options.firstDrawing = false; chartSeries._drawPoint.call(this, options) }, _getMainColor: function() { return this._options.mainSeriesColor }, _createPointStyles: function(pointOptions) { var that = this, mainColor = pointOptions.color || that._getMainColor(); return { normal: that._parsePointStyle(pointOptions, mainColor, mainColor), hover: that._parsePointStyle(pointOptions.hoverStyle || {}, mainColor, mainColor), selection: that._parsePointStyle(pointOptions.selectionStyle || {}, mainColor, mainColor) } }, _updatePointsVisibility: function() { var visibility = this._options.visible; $.each(this._points, function(_, point) { point._options.visible = visibility }) }, _getOptionsForPoint: function() { return this._options }, _animate: function(firstDrawing) { var that = this, complete = function() { that._animateComplete() }, animateFunc = function(drawnPoints, complete) { var lastPointIndex = drawnPoints.length - 1; _each(drawnPoints || [], function(i, point) { point.animate(i === lastPointIndex ? complete : void 0, point.getMarkerCoords()) }) }; that._animatePoints(firstDrawing, complete, animateFunc) }, _getPointSize: function() { return DEFAULT_BAR_POINT_SIZE }, getValueRangeInitialValue: areaSeries.getValueRangeInitialValue }; exports.chart.bar = _extend({}, chartSeries, baseBarSeriesMethods, { _getAffineCoordOptions: function() { var rotated = this._options.rotated, direction = rotated ? "X" : "Y", settings = { scaleX: rotated ? .001 : 1, scaleY: rotated ? 1 : .001 }; settings["translate" + direction] = this.getValueAxis().getTranslator().translate("canvas_position_default"); return settings }, _processRange: function(range) { areaSeries._processRange.apply(this, arguments); range.arg.stick = false }, _animatePoints: function(firstDrawing, complete, animateFunc) { var that = this; that._markersGroup.animate({ scaleX: 1, scaleY: 1, translateY: 0, translateX: 0 }, void 0, complete); if (!firstDrawing) { animateFunc(that._drawnPoints, complete) } } }); exports.polar.bar = _extend({}, polarSeries, baseBarSeriesMethods, { _animatePoints: function(firstDrawing, complete, animateFunc) { animateFunc(this._drawnPoints, complete) }, _setGroupsSettings: chartSeries._setGroupsSettings, _drawPoint: function(point, groups, animationEnabled) { chartSeries._drawPoint.call(this, point, groups, animationEnabled) }, _parsePointStyle: function(style) { var base = baseBarSeriesMethods._parsePointStyle.apply(this, arguments); base.opacity = style.opacity; return base }, _createGroups: chartSeries._createGroups, _setMarkerGroupSettings: function() { var groupSettings, that = this, markersSettings = that._createPointStyles(that._getMarkerGroupOptions()).normal; markersSettings.class = "dxc-markers"; that._applyMarkerClipRect(markersSettings); groupSettings = _extend({}, markersSettings); delete groupSettings.opacity; that._markersGroup.attr(groupSettings) }, _createLegendState: areaSeries._createLegendState }) }, /*!***************************************!*\ !*** ./js/viz/series/range_series.js ***! \***************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _extend = extend, _isDefined = commonUtils.isDefined, _map = __webpack_require__( /*! ../core/utils */ 509).map, _noop = commonUtils.noop, rangeCalculator = __webpack_require__( /*! ./helpers/range_data_calculator */ 539), scatterSeries = __webpack_require__( /*! ./scatter_series */ 540).chart, barSeries = __webpack_require__( /*! ./bar_series */ 543).chart.bar, areaSeries = __webpack_require__( /*! ./area_series */ 542).chart.area; exports.chart = {}; var baseRangeSeries = { _beginUpdateData: _noop, areErrorBarsVisible: _noop, _createErrorBarGroup: _noop, _checkData: function(data) { return _isDefined(data.argument) && void 0 !== data.value && void 0 !== data.minValue }, updateTemplateFieldNames: function() { var that = this, options = that._options, valueFields = that.getValueFields(), name = that.name; options.rangeValue1Field = valueFields[0] + name; options.rangeValue2Field = valueFields[1] + name; options.tagField = that.getTagField() + name }, getValueRangeInitialValue: scatterSeries.getValueRangeInitialValue, _getPointData: function(data, options) { return { tag: data[options.tagField || "tag"], minValue: data[options.rangeValue1Field || "val1"], value: data[options.rangeValue2Field || "val2"], argument: data[options.argumentField || "arg"] } }, _fusionPoints: function(fusionPoints, tick) { var calcMedianValue = scatterSeries._calcMedianValue, value = calcMedianValue.call(this, fusionPoints, "value"), minValue = calcMedianValue.call(this, fusionPoints, "minValue"); if (null === value || null === minValue) { value = minValue = null } return { minValue: minValue, value: value, argument: tick, tag: null } }, getValueFields: function() { return [this._options.rangeValue1Field || "val1", this._options.rangeValue2Field || "val2"] }, _processRange: function(range) { rangeCalculator.addRangeSeriesLabelPaddings(this, range.val) } }; exports.chart.rangebar = _extend({}, barSeries, baseRangeSeries); exports.chart.rangearea = _extend({}, areaSeries, { _drawPoint: function(options) { var point = options.point; if (point.isInVisibleArea()) { point.clearVisibility(); point.draw(this._renderer, options.groups); this._drawnPoints.push(point); if (!point.visibleTopMarker) { point.hideMarker("top") } if (!point.visibleBottomMarker) { point.hideMarker("bottom") } } else { point.setInvisibility() } }, _prepareSegment: function(points, rotated) { var processedPoints = this._processSinglePointsAreaSegment(points, rotated), processedMinPointsCoords = _map(processedPoints, function(pt) { return pt.getCoords(true) }); return { line: processedPoints, bottomLine: processedMinPointsCoords, area: _map(processedPoints, function(pt) { return pt.getCoords() }).concat(processedMinPointsCoords.slice().reverse()), singlePointSegment: processedPoints !== points } }, _getDefaultSegment: function(segment) { var defaultSegment = areaSeries._getDefaultSegment.call(this, segment); defaultSegment.bottomLine = defaultSegment.line; return defaultSegment }, _removeElement: function(element) { areaSeries._removeElement.call(this, element); element.bottomLine && element.bottomLine.remove() }, _drawElement: function(segment, group) { var that = this, drawnElement = areaSeries._drawElement.call(that, segment, group); drawnElement.bottomLine = that._bordersGroup && that._createBorderElement(segment.bottomLine, { "stroke-width": that._styles.normal.border["stroke-width"] }).append(that._bordersGroup); return drawnElement }, _applyStyle: function(style) { var that = this, elementsGroup = that._elementsGroup, bordersGroup = that._bordersGroup; elementsGroup && elementsGroup.smartAttr(style.elements); bordersGroup && bordersGroup.attr(style.border); (that._graphics || []).forEach(function(graphic) { graphic.line && graphic.line.attr({ "stroke-width": style.border["stroke-width"] }); graphic.bottomLine && graphic.bottomLine.attr({ "stroke-width": style.border["stroke-width"] }) }) }, _updateElement: function(element, segment, animate, animateParams, complete) { areaSeries._updateElement.call(this, element, segment, animate, animateParams, complete); var bottomLineParams = { points: segment.bottomLine }, bottomBorderElement = element.bottomLine; if (bottomBorderElement) { animate ? bottomBorderElement.animate(bottomLineParams, animateParams) : bottomBorderElement.attr(bottomLineParams) } } }, baseRangeSeries) }, /*!****************************************!*\ !*** ./js/viz/series/bubble_series.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), lineSeries = __webpack_require__( /*! ./line_series */ 541).chart.line, scatterSeries = __webpack_require__( /*! ./scatter_series */ 540).chart, areaSeries = __webpack_require__( /*! ./area_series */ 542).chart.area, barSeries = __webpack_require__( /*! ./bar_series */ 543), chartBarSeries = barSeries.chart.bar, polarBarSeries = barSeries.polar.bar, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _isDefined = commonUtils.isDefined, _extend = extend, _each = $.each, _noop = commonUtils.noop; exports.chart = {}; exports.chart.bubble = _extend({}, scatterSeries, { _fillErrorBars: _noop, getErrorBarRangeCorrector: _noop, _calculateErrorBars: _noop, _getMainColor: chartBarSeries._getMainColor, _createPointStyles: chartBarSeries._createPointStyles, _updatePointsVisibility: chartBarSeries._updatePointsVisibility, _getOptionsForPoint: chartBarSeries._getOptionsForPoint, _applyMarkerClipRect: lineSeries._applyElementsClipRect, _parsePointStyle: polarBarSeries._parsePointStyle, _createLegendState: areaSeries._createLegendState, _setMarkerGroupSettings: polarBarSeries._setMarkerGroupSettings, areErrorBarsVisible: _noop, _createErrorBarGroup: _noop, _checkData: function(data) { return _isDefined(data.argument) && _isDefined(data.size) && void 0 !== data.value }, _getPointData: function(data, options) { var pointData = scatterSeries._getPointData.call(this, data, options); pointData.size = data[options.sizeField || "size"]; return pointData }, _fusionPoints: function(fusionPoints, tick) { var calcMedianValue = scatterSeries._calcMedianValue; return { size: calcMedianValue.call(this, fusionPoints, "size"), value: calcMedianValue.call(this, fusionPoints, "value"), argument: tick, tag: null } }, getValueFields: function() { return [this._options.valueField || "val"] }, getSizeField: function() { return this._options.sizeField || "size" }, updateTemplateFieldNames: function() { var that = this, options = that._options, name = that.name; options.valueField = that.getValueFields()[0] + name; options.sizeField = that.getSizeField() + name; options.tagField = that.getTagField() + name }, _clearingAnimation: function(drawComplete) { var that = this, partitionDuration = .5, lastPointIndex = that._drawnPoints.length - 1, labelsGroup = that._labelsGroup; labelsGroup && labelsGroup.animate({ opacity: .001 }, { duration: that._defaultDuration, partitionDuration: partitionDuration }, function() { _each(that._drawnPoints || [], function(i, p) { p.animate(i === lastPointIndex ? drawComplete : void 0, { r: 0 }, partitionDuration) }) }) }, _animate: function() { var that = this, lastPointIndex = that._drawnPoints.length - 1, labelsGroup = that._labelsGroup, labelAnimFunc = function() { labelsGroup && labelsGroup.animate({ opacity: 1 }, { duration: that._defaultDuration }) }; _each(that._drawnPoints || [], function(i, p) { p.animate(i === lastPointIndex ? labelAnimFunc : void 0, { r: p.bubbleSize, translateX: p.x, translateY: p.y }) }) } }) }, /*!*************************************!*\ !*** ./js/viz/series/pie_series.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, scatterSeries = __webpack_require__( /*! ./scatter_series */ 540), vizUtils = __webpack_require__( /*! ../core/utils */ 509), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, chartScatterSeries = scatterSeries.chart, barSeries = __webpack_require__( /*! ./bar_series */ 543).chart.bar, _extend = extend, _each = $.each, _noop = noop, _map = vizUtils.map, _isFinite = isFinite, _max = Math.max, ANIMATION_DURATION = .7, INSIDE = "inside"; exports.pie = _extend({}, barSeries, { _setGroupsSettings: chartScatterSeries._setGroupsSettings, _createErrorBarGroup: _noop, _drawPoint: function(options) { var point = options.point, legendCallback = this._legendCallback; chartScatterSeries._drawPoint.call(this, options); !point.isVisible() && point.setInvisibility(); point.isSelected() && legendCallback() }, adjustLabels: function() { var maxLabelLength, that = this, points = that._points || [], labelsBBoxes = []; _each(points, function(_, point) { if (point._label.isVisible()) { point.setLabelTrackerData(); if (point._label.getLayoutOptions().position !== INSIDE) { point.setLabelEllipsis(); labelsBBoxes.push(point._label.getBoundingRect().width) } } }); if (labelsBBoxes.length) { maxLabelLength = _max.apply(null, labelsBBoxes) } _each(points, function(_, point) { if (point._label.isVisible() && point._label.getLayoutOptions().position !== INSIDE) { point.setMaxLabelLength(maxLabelLength); point.updateLabelCoord() } }) }, _processRange: _noop, _applyElementsClipRect: _noop, getColor: _noop, areErrorBarsVisible: _noop, _prepareSeriesToDrawing: _noop, _endUpdateData: function() { this._arrayArguments = {}; chartScatterSeries._prepareSeriesToDrawing.call(this) }, drawLabelsWOPoints: function() { var that = this; if (that._options.label.position === INSIDE) { return false } that._labelsGroup.append(that._extGroups.labelsGroup); (that._points || []).forEach(function(point) { point.drawLabel() }); return true }, _getCreatingPointOptions: function(data) { return this._getPointOptions(data) }, _updateOptions: function(options) { this.labelSpace = 0; this.innerRadius = "pie" === this.type ? 0 : options.innerRadius }, _checkData: function(data) { var base = barSeries._checkData(data); return this._options.paintNullPoints ? base : base && null !== data.value }, _createGroups: chartScatterSeries._createGroups, _setMarkerGroupSettings: function() { var that = this; that._markersGroup.attr({ "class": "dxc-markers" }) }, _getMainColor: function(data) { var that = this, arr = that._arrayArguments || {}, argument = data.argument; arr[argument] = ++arr[argument] || 0; that._arrayArguments = arr; return that._options.mainSeriesColor(argument, arr[argument]) }, _getPointOptions: function(data) { return this._parsePointOptions(this._preparePointOptions(), this._options.label, data) }, _getRangeData: function() { return this._rangeData }, _getArrangeTotal: function(points) { var total = 0; _each(points, function(_, point) { if (point.isVisible()) { total += point.initialValue } }); return total }, _createPointStyles: function(pointOptions, data) { var that = this, mainColor = pointOptions.color || that._getMainColor(data); return { normal: that._parsePointStyle(pointOptions, mainColor, mainColor), hover: that._parsePointStyle(pointOptions.hoverStyle, mainColor, mainColor), selection: that._parsePointStyle(pointOptions.selectionStyle, mainColor, mainColor), legendStyles: { normal: that._createLegendState(pointOptions, mainColor), hover: that._createLegendState(pointOptions.hoverStyle, mainColor), selection: that._createLegendState(pointOptions.selectionStyle, mainColor) } } }, _getArrangeMinShownValue: function(points, total) { var minSegmentSize = this._options.minSegmentSize, totalMinSegmentSize = 0, totalNotMinValues = 0; total = total || points.length; _each(points, function(_, point) { if (point.isVisible()) { if (point.initialValue < minSegmentSize * total / 360) { totalMinSegmentSize += minSegmentSize } else { totalNotMinValues += point.initialValue } } }); return totalMinSegmentSize < 360 ? minSegmentSize * totalNotMinValues / (360 - totalMinSegmentSize) : 0 }, _applyArrangeCorrection: function(points, minShownValue, total) { var percent, options = this._options, isClockWise = "anticlockwise" !== options.segmentsDirection, shiftedAngle = _isFinite(options.startAngle) ? vizUtils.normalizeAngle(options.startAngle) : 0, minSegmentSize = options.minSegmentSize, correction = 0, zeroTotalCorrection = 0; if (0 === total) { total = points.filter(function(el) { return el.isVisible() }).length; zeroTotalCorrection = 1 } _each(isClockWise ? points : points.concat([]).reverse(), function(_, point) { var updatedZeroValue, val = point.isVisible() ? zeroTotalCorrection || point.initialValue : 0; if (minSegmentSize && point.isVisible() && val < minShownValue) { updatedZeroValue = minShownValue } percent = val / total; point.correctValue(correction, percent, zeroTotalCorrection + (updatedZeroValue || 0)); point.shiftedAngle = shiftedAngle; correction += updatedZeroValue || val }); this._rangeData = { val: { min: 0, max: correction } } }, _removePoint: function(point) { var points = this.getPointsByArg(point.argument); points.splice(points.indexOf(point), 1); point.dispose() }, arrangePoints: function() { var minShownValue, total, points, that = this, originalPoints = that._originalPoints || [], minSegmentSize = that._options.minSegmentSize, isAllPointsNegative = true, i = 0, len = originalPoints.length; while (i < len && isAllPointsNegative) { isAllPointsNegative = originalPoints[i].value <= 0; i++ } points = that._originalPoints = that._points = _map(originalPoints, function(point) { if (null === point.value || !isAllPointsNegative && point.value < 0) { that._removePoint(point); return null } else { return point } }); total = that._getArrangeTotal(points); if (minSegmentSize) { minShownValue = this._getArrangeMinShownValue(points, total) } that._applyArrangeCorrection(points, minShownValue, total) }, correctPosition: function(correction, canvas) { var debug = __webpack_require__( /*! ../../core/utils/console */ 13).debug; debug.assert(correction, "correction was not passed"); debug.assertParam(correction.centerX, "correction.centerX was not passed"); debug.assertParam(correction.centerY, "correction.centerY was not passed"); debug.assertParam(correction.radiusInner, "correction.radiusInner was not passed"); debug.assertParam(correction.radiusOuter, "correction.radiusOuter was not passed"); debug.assertParam(canvas, "correction.canvas was not passed"); _each(this._points, function(_, point) { point.correctPosition(correction) }); this.setVisibleArea(canvas) }, correctRadius: function(correction) { _each(this._points, function(_, point) { point.correctRadius(correction) }) }, correctLabelRadius: function(labelRadius) { _each(this._points, function(_, point) { point.correctLabelRadius(labelRadius) }) }, setVisibleArea: function(canvas) { this._visibleArea = { minX: canvas.left, maxX: canvas.width - canvas.right, minY: canvas.top, maxY: canvas.height - canvas.bottom } }, _applyVisibleArea: _noop, _animate: function(firstDrawing) { var animatePoint, that = this, points = that._points, pointsCount = points && points.length, completeFunc = function() { that._animateComplete() }; if (firstDrawing) { animatePoint = function(p, i) { p.animate(i === pointsCount - 1 ? completeFunc : void 0, ANIMATION_DURATION, (1 - ANIMATION_DURATION) * i / (pointsCount - 1)) } } else { animatePoint = function(p, i) { p.animate(i === pointsCount - 1 ? completeFunc : void 0) } } points.forEach(animatePoint) }, getVisiblePoints: function() { return _map(this._points, function(p) { return p.isVisible() ? p : null }) }, getPointsByKeys: function(arg, argumentIndex) { var pointsByArg = this.getPointsByArg(arg); return pointsByArg[argumentIndex] && [pointsByArg[argumentIndex]] || pointsByArg } }); exports.doughnut = exports.donut = exports.pie }, /*!*******************************************!*\ !*** ./js/viz/series/financial_series.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), scatterSeries = __webpack_require__( /*! ./scatter_series */ 540).chart, barSeries = __webpack_require__( /*! ./bar_series */ 543).chart.bar, rangeCalculator = __webpack_require__( /*! ./helpers/range_data_calculator */ 539), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _isDefined = commonUtils.isDefined, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _extend = extend, _each = $.each, _noop = commonUtils.noop, DEFAULT_FINANCIAL_POINT_SIZE = 10; exports.stock = _extend({}, scatterSeries, { _animate: _noop, _applyMarkerClipRect: function(settings) { settings["clip-path"] = this._forceClipping ? this._paneClipRectID : this._widePaneClipRectID }, _updatePointsVisibility: barSeries._updatePointsVisibility, _getOptionsForPoint: barSeries._getOptionsForPoint, getErrorBarRangeCorrector: _noop, _createErrorBarGroup: _noop, areErrorBarsVisible: _noop, _createGroups: scatterSeries._createGroups, _setMarkerGroupSettings: function() { var that = this, markersGroup = that._markersGroup, styles = that._createPointStyles(that._getMarkerGroupOptions()), defaultStyle = _extend(styles.normal, { "class": "default-markers" }), defaultPositiveStyle = _extend(styles.positive.normal, { "class": "default-positive-markers" }), reductionStyle = _extend(styles.reduction.normal, { "class": "reduction-markers" }), reductionPositiveStyle = _extend(styles.reductionPositive.normal, { "class": "reduction-positive-markers" }), markerSettings = { "class": "dxc-markers" }; that._applyMarkerClipRect(markerSettings); markersGroup.attr(markerSettings); that._createGroup("defaultMarkersGroup", markersGroup, markersGroup, defaultStyle); that._createGroup("reductionMarkersGroup", markersGroup, markersGroup, reductionStyle); that._createGroup("defaultPositiveMarkersGroup", markersGroup, markersGroup, defaultPositiveStyle); that._createGroup("reductionPositiveMarkersGroup", markersGroup, markersGroup, reductionPositiveStyle) }, _setGroupsSettings: function() { scatterSeries._setGroupsSettings.call(this, false) }, _clearingAnimation: function(drawComplete) { drawComplete() }, _getCreatingPointOptions: function() { var defaultPointOptions, that = this, creatingPointOptions = that._predefinedPointOptions; if (!creatingPointOptions) { defaultPointOptions = this._getPointOptions(); that._predefinedPointOptions = creatingPointOptions = _extend(true, { styles: {} }, defaultPointOptions); creatingPointOptions.styles.normal = creatingPointOptions.styles.positive.normal = creatingPointOptions.styles.reduction.normal = creatingPointOptions.styles.reductionPositive.normal = { "stroke-width": defaultPointOptions.styles && defaultPointOptions.styles.normal && defaultPointOptions.styles.normal["stroke-width"] } } return creatingPointOptions }, _checkData: function(data) { return _isDefined(data.argument) && void 0 !== data.highValue && void 0 !== data.lowValue && void 0 !== data.openValue && void 0 !== data.closeValue }, _getPointData: function(data, options) { var level, reductionValue, that = this, openValueField = options.openValueField || "open", closeValueField = options.closeValueField || "close", highValueField = options.highValueField || "high", lowValueField = options.lowValueField || "low"; that.level = options.reduction.level; switch (_normalizeEnum(that.level)) { case "open": level = openValueField; break; case "high": level = highValueField; break; case "low": level = lowValueField; break; default: level = closeValueField; that.level = "close" } reductionValue = data[level]; return { argument: data[options.argumentField || "date"], highValue: data[highValueField], lowValue: data[lowValueField], closeValue: data[closeValueField], openValue: data[openValueField], reductionValue: reductionValue, tag: data[options.tagField || "tag"], isReduction: that._checkReduction(reductionValue) } }, _parsePointStyle: function(style, defaultColor, innerColor) { return { stroke: style.color || defaultColor, "stroke-width": style.width, fill: style.color || innerColor } }, updateTemplateFieldNames: function() { var that = this, options = that._options, valueFields = that.getValueFields(), name = that.name; options.openValueField = valueFields[0] + name; options.highValueField = valueFields[1] + name; options.lowValueField = valueFields[2] + name; options.closeValueField = valueFields[3] + name; options.tagField = that.getTagField() + name }, _getDefaultStyle: function(options) { var that = this, mainPointColor = options.color || that._options.mainSeriesColor; return { normal: that._parsePointStyle(options, mainPointColor, mainPointColor), hover: that._parsePointStyle(options.hoverStyle, mainPointColor, mainPointColor), selection: that._parsePointStyle(options.selectionStyle, mainPointColor, mainPointColor) } }, _getReductionStyle: function(options) { var that = this, reductionColor = options.reduction.color; return { normal: that._parsePointStyle({ color: reductionColor, width: options.width, hatching: options.hatching }, reductionColor, reductionColor), hover: that._parsePointStyle(options.hoverStyle, reductionColor, reductionColor), selection: that._parsePointStyle(options.selectionStyle, reductionColor, reductionColor) } }, _createPointStyles: function(pointOptions) { var positiveStyle, reductionStyle, reductionPositiveStyle, that = this, innerColor = that._options.innerColor, styles = that._getDefaultStyle(pointOptions); positiveStyle = _extend(true, {}, styles); reductionStyle = that._getReductionStyle(pointOptions); reductionPositiveStyle = _extend(true, {}, reductionStyle); positiveStyle.normal.fill = positiveStyle.hover.fill = positiveStyle.selection.fill = innerColor; reductionPositiveStyle.normal.fill = reductionPositiveStyle.hover.fill = reductionPositiveStyle.selection.fill = innerColor; styles.positive = positiveStyle; styles.reduction = reductionStyle; styles.reductionPositive = reductionPositiveStyle; return styles }, _endUpdateData: function() { delete this.prevLevelValue; delete this._predefinedPointOptions }, _checkReduction: function(value) { var that = this, result = false; if (null !== value) { if (_isDefined(that.prevLevelValue)) { result = value < that.prevLevelValue } that.prevLevelValue = value } return result }, _fusionPoints: function(fusionPoints, tick) { var reductionLevel, openValue, closeValue, fusedPointData = {}, highValue = -(1 / 0), lowValue = +(1 / 0); if (!fusionPoints.length) { return {} } _each(fusionPoints, function(_, point) { if (!point.hasValue()) { return } highValue = Math.max(highValue, point.highValue); lowValue = Math.min(lowValue, point.lowValue); openValue = void 0 !== openValue ? openValue : point.openValue; closeValue = void 0 !== point.closeValue ? point.closeValue : closeValue }); fusedPointData.argument = tick; fusedPointData.openValue = openValue; fusedPointData.closeValue = closeValue; fusedPointData.highValue = highValue; fusedPointData.lowValue = lowValue; fusedPointData.tag = null; switch (_normalizeEnum(this.level)) { case "open": reductionLevel = openValue; break; case "high": reductionLevel = highValue; break; case "low": reductionLevel = lowValue; break; default: reductionLevel = closeValue } fusedPointData.reductionValue = reductionLevel; fusedPointData.isReduction = this._checkReduction(reductionLevel); return fusedPointData }, _getPointSize: function() { return DEFAULT_FINANCIAL_POINT_SIZE }, getValueFields: function() { var options = this._options; return [options.openValueField || "open", options.highValueField || "high", options.lowValueField || "low", options.closeValueField || "close"] }, getArgumentField: function() { return this._options.argumentField || "date" }, _beginUpdateData: _noop, _processRange: function(range) { rangeCalculator.addRangeSeriesLabelPaddings(this, range.val) } }); exports.candlestick = _extend({}, exports.stock, { _beginUpdateData: barSeries._beginUpdateData, _parsePointStyle: function(style, defaultColor, innerColor) { var color = style.color || innerColor, base = exports.stock._parsePointStyle.call(this, style, defaultColor, color); base.fill = color; base.hatching = style.hatching; return base } }) }, /*!*****************************************!*\ !*** ./js/viz/series/stacked_series.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, areaSeries = __webpack_require__( /*! ./area_series */ 542).chart, chartAreaSeries = areaSeries.area, barSeries = __webpack_require__( /*! ./bar_series */ 543), chartBarSeries = barSeries.chart.bar, lineSeries = __webpack_require__( /*! ./line_series */ 541).chart, _extend = extend, vizUtils = __webpack_require__( /*! ../core/utils */ 509), objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), _noop = noop, baseStackedSeries = { getErrorBarRangeCorrector: _noop, _fillErrorBars: _noop, _calculateErrorBars: _noop }, baseFullStackedSeries = _extend({}, baseStackedSeries, { isFullStackedSeries: function() { return true } }); exports.chart = {}; exports.polar = {}; exports.chart.stackedline = _extend({}, lineSeries.line, baseStackedSeries, {}); exports.chart.stackedspline = _extend({}, lineSeries.spline, baseStackedSeries, {}); var fullStackedLineSeries = exports.chart.fullstackedline = _extend({}, lineSeries.line, baseFullStackedSeries, { _processRange: function(range) { lineSeries.line._processRange.apply(this, arguments); range.val.percentStick = true }, getValueRangeInitialValue: areaSeries.area.getValueRangeInitialValue }); exports.chart.fullstackedspline = _extend({}, lineSeries.spline, baseFullStackedSeries, { _processRange: function(range) { lineSeries.line._processRange.apply(this, arguments); range.val.percentStick = true }, getValueRangeInitialValue: areaSeries.area.getValueRangeInitialValue }); exports.chart.stackedbar = _extend({}, chartBarSeries, baseStackedSeries, {}); exports.chart.fullstackedbar = _extend({}, chartBarSeries, baseFullStackedSeries, { _processRange: function(range) { chartBarSeries._processRange.apply(this, arguments); range.val.percentStick = true } }); function clonePoint(point, value, minValue, position) { point = objectUtils.clone(point); point.value = value; point.minValue = minValue; point.translate(); point.argument = point.argument + position; return point } function preparePointsForStackedAreaSegment(points) { var p, array, i = 0, result = [], len = points.length; while (i < len) { p = points[i]; array = [p]; if (p.leftHole) { array = [clonePoint(p, p.leftHole, p.minLeftHole, "left"), p] } if (p.rightHole) { array.push(clonePoint(p, p.rightHole, p.minRightHole, "right")) } result.push(array); i++ } return [].concat.apply([], result) } exports.chart.stackedarea = _extend({}, chartAreaSeries, baseStackedSeries, { _prepareSegment: function(points, rotated) { return chartAreaSeries._prepareSegment.call(this, preparePointsForStackedAreaSegment(points, this._prevSeries), rotated) }, _appendInGroup: function() { this._group.append(this._extGroups.seriesGroup).toBackground() } }); function getPointsByArgFromPrevSeries(prevSeries, argument) { var result; while (!result && prevSeries) { result = prevSeries._segmentByArg && prevSeries._segmentByArg[argument]; prevSeries = prevSeries._prevSeries } return result } exports.chart.stackedsplinearea = _extend({}, areaSeries.splinearea, baseStackedSeries, { _prepareSegment: function(points, rotated) { var areaSegment, that = this; points = preparePointsForStackedAreaSegment(points, that._prevSeries); if (!this._prevSeries || 1 === points.length) { areaSegment = areaSeries.splinearea._prepareSegment.call(this, points, rotated) } else { var forwardPoints = lineSeries.spline._calculateBezierPoints(points, rotated), backwardPoints = vizUtils.map(points, function(p) { var point = p.getCoords(true); point.argument = p.argument; return point }), prevSeriesForwardPoints = [], pointByArg = {}, i = 0, len = that._prevSeries._segments.length; while (i < len) { prevSeriesForwardPoints = prevSeriesForwardPoints.concat(that._prevSeries._segments[i].line); i++ } $.each(prevSeriesForwardPoints, function(_, p) { if (null !== p.argument) { var argument = p.argument.valueOf(); if (!pointByArg[argument]) { pointByArg[argument] = [p] } else { pointByArg[argument].push(p) } } }); that._prevSeries._segmentByArg = pointByArg; backwardPoints = lineSeries.spline._calculateBezierPoints(backwardPoints, rotated); $.each(backwardPoints, function(i, p) { var prevSeriesPoints, argument = p.argument.valueOf(); if (i % 3 === 0) { prevSeriesPoints = pointByArg[argument] || getPointsByArgFromPrevSeries(that._prevSeries, argument); if (prevSeriesPoints) { backwardPoints[i - 1] && prevSeriesPoints[0] && (backwardPoints[i - 1] = prevSeriesPoints[0]); backwardPoints[i + 1] && (backwardPoints[i + 1] = prevSeriesPoints[2] || p) } } }); areaSegment = { line: forwardPoints, area: forwardPoints.concat(backwardPoints.reverse()) }; that._areaPointsToSplineAreaPoints(areaSegment.area) } return areaSegment }, _appendInGroup: exports.chart.stackedarea._appendInGroup }); exports.chart.fullstackedarea = _extend({}, chartAreaSeries, baseFullStackedSeries, { _prepareSegment: exports.chart.stackedarea._prepareSegment, _appendInGroup: exports.chart.stackedarea._appendInGroup, _processRange: fullStackedLineSeries._processRange }); exports.chart.fullstackedsplinearea = _extend({}, areaSeries.splinearea, baseFullStackedSeries, { _prepareSegment: exports.chart.stackedsplinearea._prepareSegment, _appendInGroup: exports.chart.stackedarea._appendInGroup, _processRange: fullStackedLineSeries._processRange }); exports.polar.stackedbar = _extend({}, barSeries.polar.bar, baseStackedSeries, {}) }, /*!**************************************************!*\ !*** ./js/viz/components/chart_theme_manager.js ***! \**************************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, BaseThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager, _isString = commonUtils.isString, _isDefined = commonUtils.isDefined, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, FONT = "font", COMMON_AXIS_SETTINGS = "commonAxisSettings", PIE_FONT_FIELDS = ["legend." + FONT, "title." + FONT, "title.subtitle." + FONT, "tooltip." + FONT, "loadingIndicator." + FONT, "export." + FONT, "commonSeriesSettings.label." + FONT], POLAR_FONT_FIELDS = PIE_FONT_FIELDS.concat([COMMON_AXIS_SETTINGS + ".label." + FONT, COMMON_AXIS_SETTINGS + ".title." + FONT]), CHART_FONT_FIELDS = POLAR_FONT_FIELDS.concat(["crosshair.label." + FONT]), chartToFontFieldsMap = { pie: PIE_FONT_FIELDS, chart: CHART_FONT_FIELDS, polar: POLAR_FONT_FIELDS }; var ThemeManager = BaseThemeManager.inherit(function() { var ctor = function(options, themeGroupName) { var that = this; that.callBase.apply(that, arguments); options = options || {}; that._userOptions = options; that._mergeAxisTitleOptions = []; that._multiPieColors = {}; that._themeSection = themeGroupName; that._fontFields = chartToFontFieldsMap[themeGroupName]; that._callback = commonUtils.noop }; var dispose = function() { var that = this; that.palette && that.palette.dispose(); that.palette = that._userOptions = that._mergedSettings = that._multiPieColors = null; return that.callBase.apply(that, arguments) }; var resetPalette = function() { this.palette.reset(); this._multiPieColors = {} }; var updatePalette = function(palette) { this.palette = this.createPalette(palette, { useHighlight: true }) }; var processTitleOptions = function(options) { return _isString(options) ? { text: options } : options }; var processAxisOptions = function(axisOptions) { if (!axisOptions) { return } axisOptions = extend(true, {}, axisOptions); axisOptions.title = processTitleOptions(axisOptions.title); if ("logarithmic" === axisOptions.type && axisOptions.logarithmBase <= 0 || axisOptions.logarithmBase && !commonUtils.isNumeric(axisOptions.logarithmBase)) { axisOptions.logarithmBase = void 0; axisOptions.logarithmBaseError = true } if (axisOptions.label) { if (axisOptions.label.alignment) { axisOptions.label.userAlignment = true } if (_isString(axisOptions.label.overlappingBehavior)) { axisOptions.label.overlappingBehavior = { mode: axisOptions.label.overlappingBehavior } } if (!axisOptions.label.overlappingBehavior || !axisOptions.label.overlappingBehavior.mode) { axisOptions.label.overlappingBehavior = axisOptions.label.overlappingBehavior || {} } } return axisOptions }; var applyParticularAxisOptions = function(name, userOptions, rotated) { var theme = this._theme, position = !(rotated ^ "valueAxis" === name) ? "horizontalAxis" : "verticalAxis", commonAxisSettings = processAxisOptions(this._userOptions.commonAxisSettings, name); return extend(true, {}, theme.commonAxisSettings, theme[position], theme[name], commonAxisSettings, processAxisOptions(userOptions, name)) }; var mergeOptions = function(name, userOptions) { userOptions = userOptions || this._userOptions[name]; var theme = this._theme[name], result = this._mergedSettings[name]; if (result) { return result } if (typeUtils.isPlainObject(theme) && typeUtils.isPlainObject(userOptions)) { result = extend(true, {}, theme, userOptions) } else { result = _isDefined(userOptions) ? userOptions : theme } this._mergedSettings[name] = result; return result }; var applyParticularTheme = { base: mergeOptions, argumentAxis: applyParticularAxisOptions, valueAxisRangeSelector: function() { return mergeOptions.call(this, "valueAxis") }, valueAxis: applyParticularAxisOptions, series: function(name, userOptions) { var settings, mainSeriesColor, seriesVisibility, that = this, theme = that._theme, userCommonSettings = that._userOptions.commonSeriesSettings || {}, themeCommonSettings = theme.commonSeriesSettings, widgetType = that._themeSection.split(".").slice(-1)[0], type = _normalizeEnum(userOptions.type || userCommonSettings.type || themeCommonSettings.type || "pie" === widgetType && theme.type), palette = that.palette, isBar = ~type.indexOf("bar"), isLine = ~type.indexOf("line"), isArea = ~type.indexOf("area"), isBubble = "bubble" === type, resolveLabelsOverlapping = that.getOptions("resolveLabelsOverlapping"), containerBackgroundColor = that.getOptions("containerBackgroundColor"); if (isBar || isBubble) { userOptions = extend(true, {}, userCommonSettings, userCommonSettings[type], userOptions); seriesVisibility = userOptions.visible; userCommonSettings = { type: {} }; extend(true, userOptions, userOptions.point); userOptions.visible = seriesVisibility } settings = extend(true, {}, themeCommonSettings, themeCommonSettings[type], userCommonSettings, userCommonSettings[type], userOptions); settings.type = type; settings.widgetType = widgetType; settings.containerBackgroundColor = containerBackgroundColor; if ("pie" !== widgetType) { mainSeriesColor = settings.color || palette.getNextColor() } else { mainSeriesColor = function(argument, index) { var cat = argument + index; if (!that._multiPieColors[cat]) { that._multiPieColors[cat] = palette.getNextColor() } return that._multiPieColors[cat] } } settings.mainSeriesColor = mainSeriesColor; settings.resolveLabelsOverlapping = resolveLabelsOverlapping; if (settings.label && (isLine || isArea && "rangearea" !== type || "scatter" === type)) { settings.label.position = "outside" } return settings }, animation: function(name) { var userOptions = this._userOptions[name]; userOptions = typeUtils.isPlainObject(userOptions) ? userOptions : _isDefined(userOptions) ? { enabled: !!userOptions } : {}; return mergeOptions.call(this, name, userOptions) } }; return { _themeSection: "chart", ctor: ctor, dispose: dispose, resetPalette: resetPalette, getOptions: function(name) { return (applyParticularTheme[name] || applyParticularTheme.base).apply(this, arguments) }, refresh: function() { this._mergedSettings = {}; return this.callBase.apply(this, arguments) }, _initializeTheme: function() { var that = this; that.callBase.apply(that, arguments); that.updatePalette(that.getOptions("palette")) }, resetOptions: function(name) { this._mergedSettings[name] = null }, update: function(options) { this._userOptions = options }, updatePalette: updatePalette } }()); exports.ThemeManager = ThemeManager }, /*!*******************************************!*\ !*** ./js/viz/core/base_theme_manager.js ***! \*******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), Class = __webpack_require__( /*! ../../core/class */ 25), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), paletteModule = __webpack_require__( /*! ../palette */ 512), _isString = commonUtils.isString, _parseScalar = __webpack_require__( /*! ./utils */ 509).parseScalar, themeModule = __webpack_require__( /*! ../themes */ 508), _findTheme = themeModule.findTheme, _addCacheItem = themeModule.addCacheItem, _removeCacheItem = themeModule.removeCacheItem, _extend = extend, _each = $.each; __webpack_require__( /*! ./default */ 551); __webpack_require__( /*! ./ios */ 552); __webpack_require__( /*! ./android */ 553); __webpack_require__( /*! ./win */ 554); function getThemePart(theme, path) { var _theme = theme; path && _each(path.split("."), function(_, pathItem) { return _theme = _theme[pathItem] }); return _theme } exports.BaseThemeManager = Class.inherit({ ctor: function() { _addCacheItem(this) }, dispose: function() { var that = this; _removeCacheItem(that); that._callback = that._theme = that._font = null; return that }, setCallback: function(callback) { this._callback = callback; return this }, setTheme: function(theme, rtl) { this._current = theme; this._rtl = rtl; return this.refresh() }, refresh: function() { var that = this, current = that._current || {}, theme = _findTheme(current.name || current); that._themeName = theme.name; that._defaultPalette = theme.defaultPalette; that._font = _extend({}, theme.font, current.font); that._themeSection && _each(that._themeSection.split("."), function(_, path) { theme = _extend(true, {}, theme[path]) }); that._theme = _extend(true, {}, theme, _isString(current) ? {} : current); that._initializeTheme(); if (_parseScalar(that._rtl, that._theme.rtlEnabled)) { _extend(true, that._theme, that._theme._rtl) } that._callback(); return that }, theme: function(path) { return getThemePart(this._theme, path) }, themeName: function() { return this._themeName }, createPalette: function(palette, options) { return new paletteModule.Palette(palette || this._defaultPalette, options) }, createDiscretePalette: function(palette, count) { return new paletteModule.DiscretePalette(palette || this._defaultPalette, count) }, createGradientPalette: function(palette) { return new paletteModule.GradientPalette(palette || this._defaultPalette) }, _initializeTheme: function() { var that = this; _each(that._fontFields || [], function(_, path) { that._initializeFont(getThemePart(that._theme, path)) }) }, _initializeFont: function(font) { _extend(font, this._font, _extend({}, font)) } }) }, /*!********************************!*\ !*** ./js/viz/core/default.js ***! \********************************/ function(module, exports, __webpack_require__) { var WHITE = "#ffffff", BLACK = "#000000", LIGHT_GREY = "#d3d3d3", GREY_GREEN = "#303030", SOME_GREY = "#2b2b2b", RED = "#ff0000", PRIMARY_TITLE_COLOR = "#232323", SECONDARY_TITLE_COLOR = "#767676", CONTRAST_ACTIVE = "#cf00da", MARKER_COLOR = "#f8ca00", TARGET_COLOR = "#8e8e8e", POSITIVE_COLOR = "#b8b8b8", LINE_COLOR = "#c7c7c7", AREA_LAYER_COLOR = "#686868", RANGE_COLOR = "#b5b5b5", NONE = "none", SOLID = "solid", TOP = "top", RIGHT = "right", BOTTOM = "bottom", LEFT = "left", CENTER = "center", INSIDE = "inside", OUTSIDE = "outside", themeModule = __webpack_require__( /*! ../themes */ 508), registerTheme = themeModule.registerTheme, registerThemeAlias = themeModule.registerThemeAlias; registerTheme({ name: "generic.light", font: { color: SECONDARY_TITLE_COLOR, family: "'Segoe UI', 'Helvetica Neue', 'Trebuchet MS', Verdana", weight: 400, size: 12, cursor: "default" }, redrawOnResize: true, backgroundColor: WHITE, primaryTitleColor: PRIMARY_TITLE_COLOR, secondaryTitleColor: SECONDARY_TITLE_COLOR, axisColor: LIGHT_GREY, axisLabelColor: SECONDARY_TITLE_COLOR, title: { backgroundColor: WHITE, font: { size: 28, family: "'Segoe UI Light', 'Helvetica Neue Light', 'Segoe UI', 'Helvetica Neue', 'Trebuchet MS', Verdana", weight: 200 }, subtitle: { font: { size: 16 } } }, loadingIndicator: { text: "Loading..." }, "export": { backgroundColor: WHITE, font: { size: 14, color: PRIMARY_TITLE_COLOR, weight: 400 }, button: { "default": { color: "#333", borderColor: "#ddd", backgroundColor: WHITE }, hover: { color: "#333", borderColor: "#bebebe", backgroundColor: "#e6e6e6" }, focus: { color: BLACK, borderColor: "#9d9d9d", backgroundColor: "#e6e6e6" }, active: { color: "#333", borderColor: "#9d9d9d", backgroundColor: "#d4d4d4" } }, shadowColor: LIGHT_GREY }, tooltip: { enabled: false, border: { width: 1, color: LIGHT_GREY, dashStyle: SOLID, visible: true }, font: { color: PRIMARY_TITLE_COLOR }, color: WHITE, arrowLength: 10, paddingLeftRight: 18, paddingTopBottom: 15, shared: false, location: CENTER, shadow: { opacity: .4, offsetX: 0, offsetY: 4, blur: 2, color: BLACK } }, legend: { hoverMode: "includePoints", verticalAlignment: TOP, horizontalAlignment: RIGHT, position: OUTSIDE, visible: true, margin: 10, markerSize: 12, border: { visible: false, width: 1, cornerRadius: 0, dashStyle: SOLID }, paddingLeftRight: 20, paddingTopBottom: 15, columnCount: 0, rowCount: 0, columnItemSpacing: 20, rowItemSpacing: 8 }, "chart:common": { animation: { enabled: true, duration: 1e3, easing: "easeOutCubic", maxPointCountSupported: 300 }, commonSeriesSettings: { border: { visible: false, width: 2 }, showInLegend: true, visible: true, hoverMode: "nearestPoint", selectionMode: "includePoints", hoverStyle: { hatching: { direction: RIGHT, width: 2, step: 6, opacity: .75 }, border: { visible: false, width: 3 } }, selectionStyle: { hatching: { direction: RIGHT, width: 2, step: 6, opacity: .5 }, border: { visible: false, width: 3 } }, valueErrorBar: { displayMode: "auto", value: 1, color: BLACK, lineWidth: 2, edgeLength: 8 }, label: { visible: false, alignment: CENTER, rotationAngle: 0, horizontalOffset: 0, verticalOffset: 0, radialOffset: 0, showForZeroValues: true, customizeText: void 0, maxLabelCount: void 0, position: OUTSIDE, font: { color: WHITE }, border: { visible: false, width: 1, color: LIGHT_GREY, dashStyle: SOLID }, connector: { visible: false, width: 1 } } }, seriesSelectionMode: "single", pointSelectionMode: "single", equalRowHeight: true, dataPrepareSettings: { checkTypeForAllData: false, convertToAxisDataType: true, sortingMethod: true }, title: { margin: 10 }, adaptiveLayout: { width: 80, height: 80, keepLabels: true }, _rtl: { legend: { itemTextPosition: LEFT } }, resolveLabelOverlapping: NONE }, "chart:common:axis": { visible: false, setTicksAtUnitBeginning: true, valueMarginsEnabled: true, placeholderSize: null, logarithmBase: 10, discreteAxisDivisionMode: "betweenLabels", width: 1, label: { visible: true }, grid: { visible: false, width: 1 }, minorGrid: { visible: false, width: 1, opacity: .3 }, tick: { visible: false, width: 1, length: 8 }, minorTick: { visible: false, width: 1, opacity: .3, length: 8 }, stripStyle: { paddingLeftRight: 10, paddingTopBottom: 5 }, constantLineStyle: { width: 1, color: BLACK, dashStyle: SOLID, label: { visible: true, position: INSIDE } }, marker: { label: {} } }, chart: { commonSeriesSettings: { type: "line", stack: "default", point: { visible: true, symbol: "circle", size: 12, border: { visible: false, width: 1 }, hoverMode: "onlyPoint", selectionMode: "onlyPoint", hoverStyle: { border: { visible: true, width: 4 } }, selectionStyle: { border: { visible: true, width: 4 } } }, scatter: {}, line: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, stackedline: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, stackedspline: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, fullstackedline: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, fullstackedspline: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, stepline: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, area: { point: { visible: false }, opacity: .5 }, stackedarea: { point: { visible: false }, opacity: .5 }, fullstackedarea: { point: { visible: false }, opacity: .5 }, fullstackedsplinearea: { point: { visible: false }, opacity: .5 }, steparea: { border: { visible: true, width: 2 }, point: { visible: false }, hoverStyle: { border: { visible: true, width: 3 } }, selectionStyle: { border: { visible: true, width: 3 } }, opacity: .5 }, spline: { width: 2, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, splinearea: { point: { visible: false }, opacity: .5 }, stackedsplinearea: { point: { visible: false }, opacity: .5 }, bar: { cornerRadius: 0, point: { hoverStyle: { border: { visible: false } }, selectionStyle: { border: { visible: false } } } }, stackedbar: { cornerRadius: 0, point: { hoverStyle: { border: { visible: false } }, selectionStyle: { border: { visible: false } } }, label: { position: INSIDE } }, fullstackedbar: { cornerRadius: 0, point: { hoverStyle: { border: { visible: false } }, selectionStyle: { border: { visible: false } } }, label: { position: INSIDE } }, rangebar: { cornerRadius: 0, point: { hoverStyle: { border: { visible: false } }, selectionStyle: { border: { visible: false } } } }, rangearea: { point: { visible: false }, opacity: .5 }, rangesplinearea: { point: { visible: false }, opacity: .5 }, bubble: { opacity: .5, point: { hoverStyle: { border: { visible: false } }, selectionStyle: { border: { visible: false } } } }, candlestick: { width: 1, reduction: { color: RED }, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 }, point: { border: { visible: true } } }, stock: { width: 1, reduction: { color: RED }, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 }, point: { border: { visible: true } } } }, crosshair: { enabled: false, color: "#f05b41", width: 1, dashStyle: SOLID, label: { visible: false, font: { color: WHITE, size: 12 } }, verticalLine: { visible: true }, horizontalLine: { visible: true } }, commonAxisSettings: { multipleAxesSpacing: 5, forceUserTickInterval: false, label: { displayMode: "standard", overlappingBehavior: "hide", indentFromAxis: 10 }, title: { font: { size: 16 }, margin: 6 }, constantLineStyle: { paddingLeftRight: 10, paddingTopBottom: 10 } }, horizontalAxis: { position: BOTTOM, axisDivisionFactor: 50, label: { rotationAngle: 90, staggeringSpacing: 5, alignment: CENTER }, stripStyle: { label: { horizontalAlignment: CENTER, verticalAlignment: TOP } }, constantLineStyle: { label: { horizontalAlignment: RIGHT, verticalAlignment: TOP } }, constantLines: [] }, verticalAxis: { position: LEFT, axisDivisionFactor: 30, label: { alignment: RIGHT }, stripStyle: { label: { horizontalAlignment: LEFT, verticalAlignment: CENTER } }, constantLineStyle: { label: { horizontalAlignment: LEFT, verticalAlignment: TOP } }, constantLines: [] }, argumentAxis: {}, valueAxis: { grid: { visible: true } }, commonPaneSettings: { backgroundColor: NONE, border: { color: LIGHT_GREY, width: 1, visible: false, top: true, bottom: true, left: true, right: true, dashStyle: SOLID } }, scrollBar: { visible: false, offset: 5, color: "gray", width: 10 }, useAggregation: false, adjustOnZoom: true, rotated: false, zoomingMode: NONE, scrollingMode: NONE, synchronizeMultiAxes: true, equalBarWidth: true, minBubbleSize: 12, maxBubbleSize: .2 }, pie: { innerRadius: .5, minDiameter: .7, type: "pie", commonSeriesSettings: { pie: { border: { visible: false, width: 2, color: WHITE }, hoverStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .75 }, border: { visible: false, width: 2 } }, selectionStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .5 }, border: { visible: false, width: 2 } } }, doughnut: { border: { visible: false, width: 2, color: WHITE }, hoverStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .75 }, border: { visible: false, width: 2 } }, selectionStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .5 }, border: { visible: false, width: 2 } } }, donut: { border: { visible: false, width: 2, color: WHITE }, hoverStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .75 }, border: { visible: false, width: 2 } }, selectionStyle: { hatching: { direction: RIGHT, width: 4, step: 10, opacity: .5 }, border: { visible: false, width: 2 } } } }, legend: { hoverMode: "allArgumentPoints", backgroundColor: NONE }, adaptiveLayout: { keepLabels: false } }, gauge: { scale: { tick: { visible: true, length: 5, width: 2, opacity: 1 }, minorTick: { visible: false, length: 3, width: 1, opacity: 1 }, label: { visible: true, alignment: CENTER, hideFirstOrLast: "last", overlappingBehavior: "hide" }, position: TOP }, rangeContainer: { offset: 0, width: 5, backgroundColor: "#808080" }, valueIndicators: { _default: { color: "#c2c2c2" }, rangebar: { space: 2, size: 10, color: "#cbc5cf", backgroundColor: NONE, text: { indent: 0, font: { size: 14, color: null } } }, twocolorneedle: { secondColor: "#e18e92" }, trianglemarker: { space: 2, length: 14, width: 13, color: "#8798a5" }, textcloud: { arrowLength: 5, horizontalOffset: 6, verticalOffset: 3, color: "#679ec5", text: { font: { color: WHITE, size: 18 } } } }, indicator: { hasPositiveMeaning: true, layout: { horizontalAlignment: CENTER, verticalAlignment: BOTTOM }, text: { font: { size: 18 } } }, _circular: { scale: { orientation: OUTSIDE, label: { indentFromTick: 10 } }, rangeContainer: { orientation: OUTSIDE }, valueIndicatorType: "rectangleneedle", subvalueIndicatorType: "trianglemarker", valueIndicators: { _type: "rectangleneedle", _default: { offset: 20, indentFromCenter: 0, width: 2, spindleSize: 14, spindleGapSize: 10 }, triangleneedle: { width: 4 }, twocolorneedle: { space: 2, secondFraction: .4 }, rangebar: { offset: 30 }, trianglemarker: { offset: 6 }, textcloud: { offset: -6 } } }, _linear: { scale: { horizontalOrientation: RIGHT, verticalOrientation: BOTTOM, label: { indentFromTick: -10 } }, rangeContainer: { horizontalOrientation: RIGHT, verticalOrientation: BOTTOM }, valueIndicatorType: "rangebar", subvalueIndicatorType: "trianglemarker", valueIndicators: { _type: "rectangle", _default: { offset: 2.5, length: 15, width: 15 }, rectangle: { width: 10 }, rangebar: { offset: 10, horizontalOrientation: RIGHT, verticalOrientation: BOTTOM }, trianglemarker: { offset: 10, horizontalOrientation: LEFT, verticalOrientation: TOP }, textcloud: { offset: -1, horizontalOrientation: LEFT, verticalOrientation: TOP } } } }, barGauge: { backgroundColor: "#e0e0e0", relativeInnerRadius: .3, barSpacing: 4, label: { indent: 20, connectorWidth: 2, font: { size: 16 } }, indicator: { hasPositiveMeaning: true, layout: { horizontalAlignment: CENTER, verticalAlignment: BOTTOM }, text: { font: { size: 18 } } } }, rangeSelector: { scale: { width: 1, color: BLACK, opacity: .1, showCustomBoundaryTicks: true, showMinorTicks: true, setTicksAtUnitBeginning: true, label: { overlappingBehavior: "hide", alignment: "center", visible: true, topIndent: 7, font: { size: 11 } }, tick: { width: 1, color: BLACK, opacity: .17, visible: true, length: 12 }, minorTick: { width: 1, color: BLACK, opacity: .05, visible: true, length: 12 }, marker: { width: 1, color: "#000000", opacity: .1, visible: true, separatorHeight: 33, topIndent: 10, textLeftIndent: 7, textTopIndent: 11, label: {} }, logarithmBase: 10 }, selectedRangeColor: "#606060", sliderMarker: { visible: true, paddingTopBottom: 2, paddingLeftRight: 4, color: "#606060", invalidRangeColor: RED, font: { color: WHITE, size: 11 } }, sliderHandle: { width: 1, color: BLACK, opacity: .2 }, shutter: { opacity: .75 }, background: { color: "#c0bae1", visible: true, image: { location: "full" } }, behavior: { snapToTicks: true, animationEnabled: true, moveSelectedRangeByClick: true, manualRangeSelectionEnabled: true, allowSlidersSwap: true, callSelectedRangeChanged: "onMovingComplete" }, redrawOnResize: true, chart: { useAggregation: false, equalBarWidth: true, minBubbleSize: 12, maxBubbleSize: .2, topIndent: .1, bottomIndent: 0, valueAxis: { inverted: false, logarithmBase: 10 }, commonSeriesSettings: { type: "area", point: { visible: false }, scatter: { point: { visible: true } } } } }, map: { title: { margin: 10 }, background: { borderWidth: 1, borderColor: "#cacaca" }, layer: { label: { enabled: false, stroke: WHITE, "stroke-width": 1, "stroke-opacity": .7, font: { color: SOME_GREY, size: 12 } } }, "layer:area": { borderWidth: 1, borderColor: WHITE, color: "#d2d2d2", hoveredBorderColor: GREY_GREEN, selectedBorderWidth: 2, selectedBorderColor: GREY_GREEN, label: { "stroke-width": 2, font: { size: 16 } } }, "layer:line": { borderWidth: 2, color: "#ba8365", hoveredColor: "#a94813", selectedBorderWidth: 3, selectedColor: "#e55100", label: { "stroke-width": 2, font: { size: 16 } } }, "layer:marker": { label: { enabled: true, "stroke-width": 1, font: { size: 12 } } }, "layer:marker:dot": { borderWidth: 2, borderColor: WHITE, color: "#ba4d51", size: 8, selectedStep: 2, backStep: 18, backColor: WHITE, backOpacity: .32, shadow: true }, "layer:marker:bubble": { minSize: 20, maxSize: 50, color: "#ba4d51", hoveredBorderWidth: 1, hoveredBorderColor: GREY_GREEN, selectedBorderWidth: 2, selectedBorderColor: GREY_GREEN }, "layer:marker:pie": { size: 50, hoveredBorderWidth: 1, hoveredBorderColor: GREY_GREEN, selectedBorderWidth: 2, selectedBorderColor: GREY_GREEN }, "layer:marker:image": { size: 20 }, legend: { verticalAlignment: BOTTOM, horizontalAlignment: RIGHT, position: INSIDE, backgroundOpacity: .65, border: { visible: true }, paddingLeftRight: 16, paddingTopBottom: 12, markerColor: "#ba4d51" }, controlBar: { borderColor: "#5d5d5d", borderWidth: 3, color: WHITE, margin: 20, opacity: .3 }, _rtl: { legend: { itemTextPosition: LEFT } } }, treeMap: { tile: { border: { width: 1, opacity: .2, color: "#000000" }, color: "#5f8b95", hoverStyle: { hatching: { opacity: .75, step: 6, width: 2, direction: "right" }, border: {} }, selectionStyle: { hatching: { opacity: .5, step: 6, width: 2, direction: "right" }, border: { opacity: 1 } }, label: { visible: true, paddingLeftRight: 5, paddingTopBottom: 4, stroke: "#000000", "stroke-width": 1, "stroke-opacity": .3, font: { color: "#ffffff", weight: 300 }, shadow: { opacity: .8, offsetX: 0, offsetY: 1, blur: 1, color: "#000000" } } }, group: { padding: 4, border: { width: 1 }, color: "#eeeeee", hoverStyle: { hatching: { opacity: 0, step: 6, width: 2, direction: "right" }, border: {} }, selectionStyle: { hatching: { opacity: 0, step: 6, width: 2, direction: "right" }, border: {} }, label: { visible: true, paddingLeftRight: 5, paddingTopBottom: 4, font: { weight: 600 } } }, title: { subtitle: {} }, tooltip: {}, loadingIndicator: {} }, sparkline: { lineColor: "#666666", lineWidth: 2, areaOpacity: .2, minColor: "#e8c267", maxColor: "#e55253", barPositiveColor: "#a9a9a9", barNegativeColor: "#d7d7d7", winColor: "#a9a9a9", lossColor: "#d7d7d7", firstLastColor: "#666666", pointSymbol: "circle", pointColor: WHITE, pointSize: 4, type: "line", argumentField: "arg", valueField: "val", winlossThreshold: 0, showFirstLast: true, showMinMax: false, tooltip: { enabled: true } }, bullet: { color: "#e8c267", targetColor: "#666666", targetWidth: 4, showTarget: true, showZeroLevel: true, tooltip: { enabled: true } }, polar: { commonSeriesSettings: { type: "scatter", closed: true, point: { visible: true, symbol: "circle", size: 12, border: { visible: false, width: 1 }, hoverMode: "onlyPoint", selectionMode: "onlyPoint", hoverStyle: { border: { visible: true, width: 4 }, size: 12 }, selectionStyle: { border: { visible: true, width: 4 }, size: 12 } }, scatter: {}, line: { width: 2, dashStyle: SOLID, hoverStyle: { width: 3, hatching: { direction: NONE } }, selectionStyle: { width: 3 } }, area: { point: { visible: false }, opacity: .5 }, stackedline: { width: 2 }, bar: { opacity: .8 }, stackedbar: { opacity: .8 } }, adaptiveLayout: { width: 170, height: 170, keepLabels: true }, equalBarWidth: true, commonAxisSettings: { visible: true, forceUserTickInterval: false, label: { overlappingBehavior: "hide", indentFromAxis: 5 }, grid: { visible: true }, minorGrid: { visible: true }, tick: { visible: true }, title: { font: { size: 16 }, margin: 10 } }, argumentAxis: { startAngle: 0, firstPointOnStartAngle: false, period: void 0 }, valueAxis: { tick: { visible: false } }, horizontalAxis: { position: TOP, axisDivisionFactor: 50, label: { alignment: CENTER } }, verticalAxis: { position: TOP, axisDivisionFactor: 30, label: { alignment: RIGHT } } } }); registerTheme({ name: "generic.dark", font: { color: "#808080" }, backgroundColor: "#2a2a2a", primaryTitleColor: "#dedede", secondaryTitleColor: "#a3a3a3", axisColor: "#555555", axisLabelColor: "#a3a3a3", "export": { backgroundColor: "#2a2a2a", font: { color: "#dbdbdb" }, button: { "default": { color: "#dedede", borderColor: "#4d4d4d", backgroundColor: "#2e2e2e" }, hover: { color: "#dedede", borderColor: "#6c6c6c", backgroundColor: "#444" }, focus: { color: "#dedede", borderColor: "#8d8d8d", backgroundColor: "#444444" }, active: { color: "#dedede", borderColor: "#8d8d8d", backgroundColor: "#555555" } }, shadowColor: "#292929" }, tooltip: { color: SOME_GREY, border: { color: "#494949" }, font: { color: "#929292" } }, "chart:common": { commonSeriesSettings: { label: { border: { color: "#494949" } }, valueErrorBar: { color: WHITE } } }, "chart:common:axis": { constantLineStyle: { color: WHITE } }, chart: { commonPaneSettings: { border: { color: "#494949" } } }, gauge: { rangeContainer: { backgroundColor: RANGE_COLOR }, valueIndicators: { _default: { color: RANGE_COLOR }, rangebar: { color: "#84788b" }, twocolorneedle: { secondColor: "#ba544d" }, trianglemarker: { color: "#b7918f" }, textcloud: { color: "#ba544d" } } }, barGauge: { backgroundColor: "#3c3c3c" }, rangeSelector: { scale: { tick: { color: WHITE, opacity: .32 }, minorTick: { color: WHITE, opacity: .1 } }, selectedRangeColor: RANGE_COLOR, sliderMarker: { color: RANGE_COLOR, font: { color: GREY_GREEN } }, sliderHandle: { color: WHITE, opacity: .2 }, shutter: { color: SOME_GREY, opacity: .9 } }, map: { background: { borderColor: "#3f3f3f" }, layer: { label: { stroke: BLACK, font: { color: WHITE } } }, "layer:area": { borderColor: GREY_GREEN, color: AREA_LAYER_COLOR, hoveredBorderColor: WHITE, selectedBorderColor: WHITE }, "layer:line": { color: "#c77244", hoveredColor: "#ff5d04", selectedColor: "#ff784f" }, "layer:marker:bubble": { hoveredBorderColor: WHITE, selectedBorderColor: WHITE }, "layer:marker:pie": { hoveredBorderColor: WHITE, selectedBorderColor: WHITE }, legend: { border: { color: "#3f3f3f" }, font: { color: WHITE } }, controlBar: { borderColor: LINE_COLOR, color: GREY_GREEN } }, treeMap: { group: { color: "#4c4c4c" } }, sparkline: { lineColor: LINE_COLOR, firstLastColor: LINE_COLOR, barPositiveColor: POSITIVE_COLOR, barNegativeColor: TARGET_COLOR, winColor: POSITIVE_COLOR, lossColor: TARGET_COLOR, pointColor: GREY_GREEN }, bullet: { targetColor: TARGET_COLOR } }, "generic.light"); registerTheme({ name: "generic.contrast", defaultPalette: "Bright", font: { color: WHITE }, backgroundColor: BLACK, primaryTitleColor: WHITE, secondaryTitleColor: WHITE, axisColor: WHITE, axisLabelColor: WHITE, "export": { backgroundColor: BLACK, font: { color: WHITE }, button: { "default": { color: WHITE, borderColor: WHITE, backgroundColor: BLACK }, hover: { color: WHITE, borderColor: WHITE, backgroundColor: "#cf00d7" }, focus: { color: WHITE, borderColor: "#cf00d7", backgroundColor: BLACK }, active: { color: BLACK, borderColor: WHITE, backgroundColor: WHITE } }, borderColor: WHITE, menuButtonColor: BLACK, activeBackgroundColor: WHITE, activeColor: BLACK, selectedBorderColor: CONTRAST_ACTIVE, selectedColor: CONTRAST_ACTIVE, shadowColor: "none" }, tooltip: { border: { color: WHITE }, font: { color: WHITE }, color: BLACK }, "chart:common": { commonSeriesSettings: { valueErrorBar: { color: WHITE }, hoverStyle: { hatching: { opacity: .5 } }, selectionStyle: { hatching: { opacity: .35 } }, label: { font: { color: WHITE }, border: { color: WHITE } } } }, "chart:common:axis": { constantLineStyle: { color: WHITE } }, chart: { commonSeriesSettings: {}, commonPaneSettings: { backgroundColor: BLACK, border: { color: WHITE } }, scrollBar: { color: WHITE } }, pie: { commonSeriesSettings: { pie: { hoverStyle: { hatching: { opacity: .5 } }, selectionStyle: { hatching: { opacity: .35 } } }, doughnut: { hoverStyle: { hatching: { opacity: .5 } }, selectionStyle: { hatching: { opacity: .35 } } }, donut: { hoverStyle: { hatching: { opacity: .5 } }, selectionStyle: { hatching: { opacity: .35 } } } } }, gauge: { rangeContainer: { backgroundColor: WHITE }, valueIndicators: { _default: { color: WHITE }, rangebar: { color: WHITE, backgroundColor: BLACK }, twocolorneedle: { secondColor: WHITE }, trianglemarker: { color: WHITE }, textcloud: { color: WHITE, text: { font: { color: BLACK } } } } }, barGauge: { backgroundColor: "#3c3c3c" }, rangeSelector: { scale: { tick: { opacity: .4 }, minorTick: { opacity: .12 } }, selectedRangeColor: CONTRAST_ACTIVE, sliderMarker: { color: CONTRAST_ACTIVE }, sliderHandle: { color: CONTRAST_ACTIVE, opacity: 1 }, shutter: { opacity: .75 }, background: { color: BLACK } }, map: { background: { borderColor: WHITE }, layer: { label: { stroke: BLACK, font: { color: WHITE } } }, "layer:area": { borderColor: BLACK, color: AREA_LAYER_COLOR, hoveredBorderColor: WHITE, selectedBorderColor: WHITE, label: { font: { opacity: 1 } } }, "layer:line": { color: "#267cff", hoveredColor: "#f613ff", selectedColor: WHITE }, "layer:marker:dot": { borderColor: BLACK, color: MARKER_COLOR, backColor: BLACK, backOpacity: .32 }, "layer:marker:bubble": { color: MARKER_COLOR, hoveredBorderColor: WHITE, selectedBorderColor: WHITE }, "layer:marker:pie": { hoveredBorderColor: WHITE, selectedBorderColor: WHITE }, legend: { markerColor: MARKER_COLOR }, controlBar: { borderColor: WHITE, color: BLACK, opacity: .3 } }, treeMap: { tile: { color: "#70c92f" }, group: { color: "#797979" } }, sparkline: { pointColor: BLACK }, bullet: {}, polar: { commonSeriesSettings: {} } }, "generic.light"); themeModule.currentTheme("generic.light"); registerThemeAlias("desktop.light", "generic.light"); registerThemeAlias("desktop.dark", "generic.dark") }, /*!****************************!*\ !*** ./js/viz/core/ios.js ***! \****************************/ function(module, exports, __webpack_require__) { var themeModule = __webpack_require__( /*! ../themes */ 508), IOS7_DEFAULT = "ios7.default", SECONDARY_TEXT_COLOR = "#767676", BORDER_COLOR = "#d3d3d3", BLACK = "#000000"; themeModule.registerTheme({ name: IOS7_DEFAULT, backgroundColor: "#ffffff", primaryTitleColor: BLACK, secondaryTitleColor: SECONDARY_TEXT_COLOR, axisColor: "#ececec", axisLabelColor: SECONDARY_TEXT_COLOR, legend: { font: { color: BLACK } }, tooltip: { font: { color: SECONDARY_TEXT_COLOR } }, "chart:common": { commonSeriesSettings: { label: { border: { color: BORDER_COLOR } } } }, chart: { commonPaneSettings: { border: { color: BORDER_COLOR } } }, rangeSelector: { scale: { tick: { color: BLACK, opacity: .1 }, minorTick: { color: BLACK, opacity: .03 } } } }, "generic.light"); themeModule.registerThemeAlias("ios", IOS7_DEFAULT) }, /*!********************************!*\ !*** ./js/viz/core/android.js ***! \********************************/ function(module, exports, __webpack_require__) { var ANDROID5_LIGHT = "android5.light", themeModule = __webpack_require__( /*! ../themes */ 508), registerThemeAlias = themeModule.registerThemeAlias, SECONDARY_TEXT_COLOR = "#767676", BORDER_COLOR = "#e8e8e8", BLACK = "#000000"; themeModule.registerTheme({ name: ANDROID5_LIGHT, backgroundColor: "#ffffff", primaryTitleColor: "#232323", secondaryTitleColor: SECONDARY_TEXT_COLOR, axisColor: "#d3d3d3", axisLabelColor: SECONDARY_TEXT_COLOR, tooltip: { color: BORDER_COLOR, font: { color: SECONDARY_TEXT_COLOR } }, legend: { font: { color: BLACK } }, rangeSelector: { scale: { tick: { color: BLACK, opacity: .17 }, minorTick: { color: BLACK, opacity: .05 } } } }, "generic.light"); registerThemeAlias("android", ANDROID5_LIGHT); registerThemeAlias("android.holo-dark", ANDROID5_LIGHT); registerThemeAlias("android.holo-light", ANDROID5_LIGHT); registerThemeAlias("android.dark", ANDROID5_LIGHT); registerThemeAlias("android.light", ANDROID5_LIGHT) }, /*!****************************!*\ !*** ./js/viz/core/win.js ***! \****************************/ function(module, exports, __webpack_require__) { var themeModule = __webpack_require__( /*! ../themes */ 508), registerTheme = themeModule.registerTheme, registerThemeSchemeAlias = themeModule.registerThemeSchemeAlias, BLACK = "#000000", WHITE = "#ffffff", WIN10_WHITE = "win10.white", WIN10_BLACK = "win10.black", WIN8_WHITE = "win8.white", WIN8_BLACK = "win8.black"; registerTheme({ name: WIN10_BLACK, backgroundColor: BLACK, primaryTitleColor: WHITE, secondaryTitleColor: "#d8d8d8", axisColor: "#4c4c4c", axisLabelColor: WHITE, title: { font: { color: WHITE } }, legend: { font: { color: WHITE } }, tooltip: { color: BLACK, font: { color: WHITE } }, "chart:common": { commonSeriesSettings: { label: { border: { color: "#454545" } } } }, chart: { commonPaneSettings: { border: { color: "#454545" } } }, barGauge: { backgroundColor: "#2b3036" }, rangeSelector: { scale: { tick: { color: WHITE, opacity: .23 }, minorTick: { color: WHITE, opacity: .07 } } } }, "generic.dark"); registerTheme({ name: WIN10_WHITE, backgroundColor: WHITE, primaryTitleColor: BLACK, secondaryTitleColor: "#767676", axisColor: "#ececec", axisLabelColor: BLACK, title: { font: { color: BLACK } }, legend: { font: { color: BLACK } }, tooltip: { font: { color: BLACK } }, rangeSelector: { scale: { tick: { color: BLACK, opacity: .1 }, minorTick: { color: BLACK, opacity: .03 } } } }, "generic.light"); registerThemeSchemeAlias("win10.dark", WIN10_BLACK); registerThemeSchemeAlias("win10.light", WIN10_WHITE); registerTheme({ name: WIN8_BLACK }, WIN10_BLACK); registerTheme({ name: WIN8_WHITE }, WIN10_WHITE); registerThemeSchemeAlias("win8.dark", WIN8_BLACK); registerThemeSchemeAlias("win8.light", WIN8_WHITE) }, /*!***************************************************!*\ !*** ./js/viz/chart_components/layout_manager.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, layoutElementModule = __webpack_require__( /*! ../core/layout_element */ 522), _isNumber = commonUtils.isNumeric, _min = Math.min, _max = Math.max, _floor = Math.floor, _sqrt = Math.sqrt, _extend = extend, consts = __webpack_require__( /*! ../components/consts */ 527), pieLabelIndent = consts.pieLabelIndent, pieLabelSpacing = consts.pieLabelSpacing; function getNearestCoord(firstCoord, secondCoord, pointCenterCoord) { var nearestCoord; if (pointCenterCoord < firstCoord) { nearestCoord = firstCoord } else { if (secondCoord < pointCenterCoord) { nearestCoord = secondCoord } else { nearestCoord = pointCenterCoord } } return nearestCoord } function getLabelLayout(point) { if (point._label.isVisible() && "inside" !== point._label.getLayoutOptions().position) { return point._label.getBoundingRect() } } function getPieRadius(series, paneCenterX, paneCenterY, accessibleRadius, minR) { var radiusIsFound = false; series.forEach(function(singleSeries) { if (radiusIsFound) { return false } singleSeries.getVisiblePoints().forEach(function(point) { var labelBBox = getLabelLayout(point); if (labelBBox) { var xCoords = getNearestCoord(labelBBox.x, labelBBox.x + labelBBox.width, paneCenterX), yCoords = getNearestCoord(labelBBox.y, labelBBox.y + labelBBox.height, paneCenterY); accessibleRadius = _min(_max(getLengthFromCenter(xCoords, yCoords, paneCenterX, paneCenterY) - pieLabelIndent, minR), accessibleRadius); radiusIsFound = true } }) }); return accessibleRadius } function getSizeLabels(series) { var sizes = [], commonWidth = 0; series.forEach(function(singleSeries) { var maxWidth = 0; singleSeries.getVisiblePoints().forEach(function(point) { var labelBBox = getLabelLayout(point); if (labelBBox) { maxWidth = _max(labelBBox.width + pieLabelSpacing, maxWidth) } }); sizes.push(maxWidth); commonWidth += maxWidth }); return { sizes: sizes, common: commonWidth } } function correctLabelRadius(sizes, radius, series, canvas, averageWidthLabels) { var curRadius, i, centerX = (canvas.width - canvas.left - canvas.right) / 2; for (i = 0; i < series.length; i++) { if (0 === sizes[i]) { curRadius && (curRadius += sizes[i - 1]); continue } curRadius = _floor(curRadius ? curRadius + sizes[i - 1] : radius); series[i].correctLabelRadius(curRadius); if (averageWidthLabels && i !== series.length - 1) { sizes[i] = averageWidthLabels; series[i].setVisibleArea({ left: centerX - radius - averageWidthLabels * (i + 1), right: canvas.width - (centerX + radius + averageWidthLabels * (i + 1)), top: canvas.top, bottom: canvas.bottom, width: canvas.width, height: canvas.height }) } } } function getLengthFromCenter(x, y, paneCenterX, paneCenterY) { return _sqrt((x - paneCenterX) * (x - paneCenterX) + (y - paneCenterY) * (y - paneCenterY)) } function getInnerRadius(series) { var innerRadius; if ("pie" === series.type) { innerRadius = 0 } else { innerRadius = _isNumber(series.innerRadius) ? Number(series.innerRadius) : .5; innerRadius = innerRadius < .2 ? .2 : innerRadius; innerRadius = innerRadius > .8 ? .8 : innerRadius } return innerRadius } var inverseAlign = { left: "right", right: "left", top: "bottom", bottom: "top", center: "center" }; function downSize(canvas, layoutOptions) { canvas[layoutOptions.cutLayoutSide] += "horizontal" === layoutOptions.cutSide ? layoutOptions.width : layoutOptions.height } function getOffset(layoutOptions, offsets) { var side = layoutOptions.cutLayoutSide, offset = { horizontal: 0, vertical: 0 }; switch (side) { case "top": case "left": offset[layoutOptions.cutSide] = -offsets[side]; break; case "bottom": case "right": offset[layoutOptions.cutSide] = offsets[side] } return offset } function LayoutManager() {} function toLayoutElementCoords(canvas) { return new layoutElementModule.WrapperLayoutElement(null, { x: canvas.left, y: canvas.top, width: canvas.width - canvas.left - canvas.right, height: canvas.height - canvas.top - canvas.bottom }) } function correctAvailableRadius(availableRadius, canvas, series, minPiePercentage, paneCenterX, paneCenterY) { var averageWidthLabels, minR = minPiePercentage * availableRadius, sizeLabels = getSizeLabels(series), countSeriesWithOuterLabels = 0, fullRadiusWithLabels = paneCenterX - sizeLabels.common + canvas.left; if (fullRadiusWithLabels < minR) { availableRadius = minR; sizeLabels.sizes.forEach(function(size) { 0 !== size && countSeriesWithOuterLabels++ }); averageWidthLabels = (paneCenterX - availableRadius - canvas.left) / countSeriesWithOuterLabels } else { availableRadius = _min(getPieRadius(series, paneCenterX, paneCenterY, availableRadius, minR), fullRadiusWithLabels) } correctLabelRadius(sizeLabels.sizes, availableRadius, series, canvas, averageWidthLabels); return availableRadius } LayoutManager.prototype = { constructor: LayoutManager, setOptions: function(options) { this._options = options }, applyPieChartSeriesLayout: function(canvas, series, hideLayoutLabels) { var availableRadius, paneSpaceHeight = canvas.height - canvas.top - canvas.bottom, paneSpaceWidth = canvas.width - canvas.left - canvas.right, paneCenterX = paneSpaceWidth / 2 + canvas.left, paneCenterY = paneSpaceHeight / 2 + canvas.top, piePercentage = this._options.piePercentage; if (_isNumber(piePercentage)) { availableRadius = piePercentage * _min(canvas.height, canvas.width) / 2 } else { availableRadius = _min(paneSpaceWidth, paneSpaceHeight) / 2; if (!hideLayoutLabels) { availableRadius = correctAvailableRadius(availableRadius, canvas, series, this._options.minPiePercentage, paneCenterX, paneCenterY) } } return { centerX: _floor(paneCenterX), centerY: _floor(paneCenterY), radiusInner: _floor(availableRadius * getInnerRadius(series[0])), radiusOuter: _floor(availableRadius) } }, applyEqualPieChartLayout: function(series, layout) { var radius = layout.radius; return { centerX: _floor(layout.x), centerY: _floor(layout.y), radiusInner: _floor(radius * getInnerRadius(series[0])), radiusOuter: _floor(radius) } }, needMoreSpaceForPanesCanvas: function(panes, rotated) { var options = this._options, width = options.width, height = options.height, piePercentage = options.piePercentage, percentageIsValid = _isNumber(piePercentage), needHorizontalSpace = 0, needVerticalSpace = 0; panes.forEach(function(pane) { var paneCanvas = pane.canvas, minSize = percentageIsValid ? _min(paneCanvas.width, paneCanvas.height) * piePercentage : void 0, needPaneHorizontalSpace = (percentageIsValid ? minSize : width) - (paneCanvas.width - paneCanvas.left - paneCanvas.right), needPaneVerticalSpace = (percentageIsValid ? minSize : height) - (paneCanvas.height - paneCanvas.top - paneCanvas.bottom); if (rotated) { needHorizontalSpace += needPaneHorizontalSpace > 0 ? needPaneHorizontalSpace : 0; needVerticalSpace = _max(needPaneVerticalSpace > 0 ? needPaneVerticalSpace : 0, needVerticalSpace) } else { needHorizontalSpace = _max(needPaneHorizontalSpace > 0 ? needPaneHorizontalSpace : 0, needHorizontalSpace); needVerticalSpace += needPaneVerticalSpace > 0 ? needPaneVerticalSpace : 0 } }); return needHorizontalSpace > 0 || needVerticalSpace > 0 ? { width: needHorizontalSpace, height: needVerticalSpace } : false }, layoutElements: function(elements, canvas, funcAxisDrawer, panes, rotated) { this._elements = elements; this._probeDrawing(canvas); this._drawElements(canvas); funcAxisDrawer(); this._processAdaptiveLayout(panes, rotated, canvas, funcAxisDrawer); this._positionElements(canvas) }, _processAdaptiveLayout: function(panes, rotated, canvas, funcAxisDrawer) { var that = this, size = that.needMoreSpaceForPanesCanvas(panes, rotated), items = this._elements; if (!size) { return } function processCanvases(item, layoutOptions, side) { if (!item.getLayoutOptions()[side]) { canvas[layoutOptions.cutLayoutSide] -= layoutOptions[side]; size[side] = Math.max(size[side] - layoutOptions[side], 0) } } items.slice().reverse().forEach(function(item) { var sizeObject, layoutOptions = _extend({}, item.getLayoutOptions()); if (!layoutOptions) { return } sizeObject = extend({}, layoutOptions); if ("vertical" === layoutOptions.cutSide && size.height) { item.draw(sizeObject.width, sizeObject.height - size.height); processCanvases(item, layoutOptions, "height") } if ("horizontal" === layoutOptions.cutSide && size.width) { item.draw(sizeObject.width - size.width, sizeObject.height); processCanvases(item, layoutOptions, "width") } }); funcAxisDrawer(size) }, _probeDrawing: function(canvas) { var that = this; this._elements.forEach(function(item) { var sizeObject, layoutOptions = item.getLayoutOptions(); if (!layoutOptions) { return } sizeObject = { width: canvas.width - canvas.left - canvas.right, height: canvas.height - canvas.top - canvas.bottom }; if ("vertical" === layoutOptions.cutSide) { sizeObject.height -= that._options.height } else { sizeObject.width -= that._options.width } item.probeDraw(sizeObject.width, sizeObject.height); downSize(canvas, item.getLayoutOptions()) }) }, _drawElements: function(canvas) { this._elements.slice().reverse().forEach(function(item) { var sizeObject, cutSide, length, layoutOptions = item.getLayoutOptions(); if (!layoutOptions) { return } sizeObject = { width: canvas.width - canvas.left - canvas.right, height: canvas.height - canvas.top - canvas.bottom }; cutSide = layoutOptions.cutSide; length = "horizontal" === cutSide ? "width" : "height"; sizeObject[length] = layoutOptions[length]; item.draw(sizeObject.width, sizeObject.height) }) }, _positionElements: function(canvas) { var offsets = { left: 0, right: 0, top: 0, bottom: 0 }; this._elements.slice().reverse().forEach(function(item) { var position, cutSide, my, layoutOptions = item.getLayoutOptions(); if (!layoutOptions) { return } position = layoutOptions.position; cutSide = layoutOptions.cutSide; my = { horizontal: position.horizontal, vertical: position.vertical }; my[cutSide] = inverseAlign[my[cutSide]]; item.position({ of: toLayoutElementCoords(canvas), my: my, at: position, offset: getOffset(layoutOptions, offsets) }); offsets[layoutOptions.cutLayoutSide] += layoutOptions["horizontal" === layoutOptions.cutSide ? "width" : "height"] }) } }; exports.LayoutManager = LayoutManager }, /*!********************************************!*\ !*** ./js/viz/chart_components/tracker.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), clickEvent = __webpack_require__( /*! ../../events/click */ 75), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, consts = __webpack_require__( /*! ../components/consts */ 527), eventsConsts = consts.events, vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), pointerEvents = __webpack_require__( /*! ../../events/pointer */ 76), wheelEvent = __webpack_require__( /*! ../../events/core/wheel */ 85), holdEvent = __webpack_require__( /*! ../../events/hold */ 164), addNamespace = __webpack_require__( /*! ../../events/utils */ 71).addNamespace, devices = __webpack_require__( /*! ../../core/devices */ 53), isDefined = commonUtils.isDefined, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _floor = Math.floor, _each = $.each, _noop = commonUtils.noop, HOVER_STATE = consts.states.hoverMark, NORMAL_STATE = consts.states.normalMark, EVENT_NS = "dxChartTracker", DOT_EVENT_NS = "." + EVENT_NS, POINTER_ACTION = addNamespace([pointerEvents.down, pointerEvents.move], EVENT_NS), LEGEND_CLICK = "legendClick", SERIES_CLICK = "seriesClick", POINT_CLICK = "pointClick", ZOOM_START = "zoomStart", POINT_DATA = "chart-data-point", SERIES_DATA = "chart-data-series", ARG_DATA = "chart-data-argument", DELAY = 100, NONE_MODE = "none", ALL_ARGUMENT_POINTS_MODE = "allargumentpoints", INCLUDE_POINTS_MODE = "includepoints", EXLUDE_POINTS_MODE = "excludepoints", LEGEND_HOVER_MODES = [INCLUDE_POINTS_MODE, EXLUDE_POINTS_MODE, NONE_MODE]; function getData(event, dataKey) { var target = event.target; return ("tspan" === target.tagName ? target.parentNode : target)[dataKey] } function eventCanceled(event, target) { return event.cancel || !target.getOptions() } function inCanvas(canvas, x, y) { return x >= canvas.left && x <= canvas.right && y >= canvas.top && y <= canvas.bottom } function correctLegendHoverMode(mode) { if (LEGEND_HOVER_MODES.indexOf(mode) > -1) { return mode } else { return INCLUDE_POINTS_MODE } } function correctHoverMode(target) { var mode = target.getOptions().hoverMode; return mode === NONE_MODE ? mode : ALL_ARGUMENT_POINTS_MODE } var baseTrackerPrototype = { ctor: function(options) { var that = this, data = { tracker: that }; that._renderer = options.renderer; that._legend = options.legend; that._tooltip = options.tooltip; that._eventTrigger = options.eventTrigger; that._seriesGroup = options.seriesGroup; options.seriesGroup.off(DOT_EVENT_NS).on(addNamespace(eventsConsts.showPointTooltip, EVENT_NS), data, that._showPointTooltip).on(addNamespace(eventsConsts.hidePointTooltip, EVENT_NS), data, that._hidePointTooltip); that._renderer.root.off(DOT_EVENT_NS).on(POINTER_ACTION, data, that._pointerHandler).on(addNamespace(clickEvent.name, EVENT_NS), data, that._clickHandler).on(addNamespace(holdEvent.name, EVENT_NS), { timeout: 300 }, _noop) }, update: function(options) { this._prepare() }, updateSeries: function(series) { var that = this; if (that._storedSeries !== series) { that._storedSeries = series || []; that._clean() } else { that._hideTooltip(that.pointAtShownTooltip); that._clearHover(); that.clearSelection() } }, setCanvases: function(mainCanvas, paneCanvases) { this._mainCanvas = mainCanvas; this._canvases = paneCanvases }, repairTooltip: function() { var point = this.pointAtShownTooltip; if (point && !point.isVisible()) { this._hideTooltip(point, true) } else { this._showTooltip(point) } }, _prepare: function() { this._toggleParentsScrollSubscription(true) }, _toggleParentsScrollSubscription: function(subscribe) { var that = this, $parents = $(that._renderer.root.element).parents(), scrollEvents = addNamespace("scroll", EVENT_NS); if ("generic" === devices.real().platform) { $parents = $parents.add(window) } $().add(that._$prevRootParents).off(scrollEvents); if (subscribe) { $parents.on(scrollEvents, function() { that._pointerOut() }); that._$prevRootParents = $parents } }, _setHoveredPoint: function(point) { if (point === this._hoveredPoint) { return } this._releaseHoveredPoint(); point.hover(); this._hoveredPoint = point }, _releaseHoveredPoint: function() { if (this._hoveredPoint && this._hoveredPoint.getOptions()) { this._hoveredPoint.clearHover(); this._hoveredPoint = null; if (this._tooltip.isEnabled()) { this._hideTooltip(this._hoveredPoint) } } }, _setHoveredSeries: function(series, mode) { this._releaseHoveredSeries(); this._releaseHoveredPoint(); series.hover(mode); this.hoveredSeries = series }, _releaseHoveredSeries: function(needSetHoverView, hoveredPoint) { if (this.hoveredSeries) { this.hoveredSeries.clearHover(); this.hoveredSeries = null } }, clearSelection: function() { this._storedSeries.forEach(function(series) { series.clearSelection(); series.getPoints().forEach(function(point) { point.clearSelection() }) }) }, _clean: function() { var that = this; that.hoveredPoint = that.hoveredSeries = that._hoveredArgumentPoints = null; that._hideTooltip(that.pointAtShownTooltip) }, _clearHover: function() { this._resetHoveredArgument(); this._releaseHoveredSeries(); this._releaseHoveredPoint() }, _hideTooltip: function(point, silent) { var that = this; if (!that._tooltip || point && that.pointAtShownTooltip !== point) { return } if (!silent && that.pointAtShownTooltip) { that.pointAtShownTooltip = null } that._tooltip.hide() }, _showTooltip: function(point) { var tooltipFormatObject, eventData, that = this; if (point && point.getOptions()) { tooltipFormatObject = point.getTooltipFormatObject(that._tooltip); if (!isDefined(tooltipFormatObject.valueText) && !tooltipFormatObject.points || !point.isVisible()) { return } if (!that.pointAtShownTooltip || that.pointAtShownTooltip !== point) { eventData = { target: point } } var coords = point.getTooltipParams(that._tooltip.getLocation()), rootOffset = that._renderer.getRootOffset(); coords.x += rootOffset.left; coords.y += rootOffset.top; if (!that._tooltip.show(tooltipFormatObject, coords, eventData)) { return } that.pointAtShownTooltip = point } }, _showPointTooltip: function(event, point) { var that = event.data.tracker, pointWithTooltip = that.pointAtShownTooltip; if (pointWithTooltip && pointWithTooltip !== point) { that._hideTooltip(pointWithTooltip) } that._showTooltip(point) }, _hidePointTooltip: function(event, point) { event.data.tracker._hideTooltip(point) }, _enableOutHandler: function() { if (this._outHandler) { return } var that = this, handler = function(e) { var rootOffset = that._renderer.getRootOffset(), x = _floor(e.pageX - rootOffset.left), y = _floor(e.pageY - rootOffset.top); if (!inCanvas(that._mainCanvas, x, y)) { that._pointerOut(); that._disableOutHandler() } }; $(document).on(POINTER_ACTION, handler); this._outHandler = handler }, _disableOutHandler: function() { this._outHandler && $(document).off(POINTER_ACTION, this._outHandler); this._outHandler = null }, _pointerOut: function() { this._clearHover(); this._tooltip.isEnabled() && this._hideTooltip(this.pointAtShownTooltip) }, _triggerLegendClick: function(eventArgs, elementClick) { var eventTrigger = this._eventTrigger; eventTrigger(LEGEND_CLICK, eventArgs, function() { !eventCanceled(eventArgs.jQueryEvent, eventArgs.target) && eventTrigger(elementClick, eventArgs) }) }, _hoverLegendItem: function(x, y) { var series, that = this, item = that._legend.getItemByCoord(x, y), legendHoverMode = correctLegendHoverMode(that._legend.getOptions().hoverMode); if (item) { series = that._storedSeries[item.id]; if (!series.isHovered() || series.lastHoverMode !== legendHoverMode) { that._setHoveredSeries(series, legendHoverMode) } that._tooltip.isEnabled() && that._hideTooltip(that.pointAtShownTooltip) } else { that._clearHover() } }, _hoverArgument: function(argument, argumentIndex) { var that = this, hoverMode = that._getArgumentHoverMode(); if (isDefined(argument)) { that._releaseHoveredPoint(); that._hoveredArgument = argument; that._argumentIndex = argumentIndex; that._notifySeries({ action: "pointHover", notifyLegend: that._notifyLegendOnHoverArgument, target: { argument: argument, fullState: HOVER_STATE, argumentIndex: argumentIndex, getOptions: function() { return { hoverMode: hoverMode } } } }) } }, _resetHoveredArgument: function() { var hoverMode, that = this; if (isDefined(that._hoveredArgument)) { hoverMode = that._getArgumentHoverMode(); that._notifySeries({ action: "clearPointHover", notifyLegend: that._notifyLegendOnHoverArgument, target: { fullState: NORMAL_STATE, argumentIndex: that._argumentIndex, argument: that._hoveredArgument, getOptions: function() { return { hoverMode: hoverMode } } } }); that._hoveredArgument = null } }, _notifySeries: function(data) { this._storedSeries.forEach(function(series) { series.notify(data) }) }, _pointerHandler: function(e) { var that = e.data.tracker, rootOffset = that._renderer.getRootOffset(), x = _floor(e.pageX - rootOffset.left), y = _floor(e.pageY - rootOffset.top), canvas = that._getCanvas(x, y), series = getData(e, SERIES_DATA), point = getData(e, POINT_DATA) || series && series.getPointByCoord(x, y); that._enableOutHandler(); if (that._checkGestureEvents(e, canvas, rootOffset)) { return } if (that._legend.coordsIn(x, y)) { that._hoverLegendItem(x, y); return } if (that.hoveredSeries && that.hoveredSeries !== that._stuckSeries) { that._releaseHoveredSeries() } if (that._hoverArgumentAxis(x, y, e)) { return } if (that._isPointerOut(canvas, point)) { that._pointerOut() } if (!canvas && !point) { return } if (series && !point) { point = series.getNeighborPoint(x, y); if (series !== that.hoveredSeries) { that._setTimeout(function() { that._setHoveredSeries(series); that._setStuckSeries(e, series, x, y); that._pointerComplete(point, x, y) }, series); return } } else { if (point) { if (that.hoveredSeries) { that._setTimeout(function() { that._pointerOnPoint(point, x, y, e) }, point) } else { that._pointerOnPoint(point, x, y, e) } return } else { if (that._setStuckSeries(e, void 0, x, y)) { series = that._stuckSeries; point = series.getNeighborPoint(x, y); that._releaseHoveredSeries(); point && that._setHoveredPoint(point) } } } that._pointerComplete(point, x, y) }, _pointerOnPoint: function(point, x, y) { this._setHoveredPoint(point); this._pointerComplete(point, x, y) }, _pointerComplete: function(point) { this.pointAtShownTooltip !== point && this._tooltip.isEnabled() && this._showTooltip(point) }, _clickHandler: function(e) { var that = e.data.tracker, rootOffset = that._renderer.getRootOffset(), x = _floor(e.pageX - rootOffset.left), y = _floor(e.pageY - rootOffset.top), point = getData(e, POINT_DATA), series = that._stuckSeries || getData(e, SERIES_DATA) || point && point.series, axis = that._argumentAxis; if (that._legend.coordsIn(x, y)) { var item = that._legend.getItemByCoord(x, y); if (item) { that._legendClick(item, e) } } else { if (axis && axis.coordsIn(x, y)) { var argument = getData(e, ARG_DATA); if (isDefined(argument)) { that._eventTrigger("argumentAxisClick", { argument: argument, jQueryEvent: e }) } } else { if (series) { point = point || series.getPointByCoord(x, y); if (point) { that._pointClick(point, e) } else { getData(e, SERIES_DATA) && that._eventTrigger(SERIES_CLICK, { target: series, jQueryEvent: e }) } } } } }, dispose: function() { var that = this; that._disableOutHandler(); that._toggleParentsScrollSubscription(); that._renderer.root.off(DOT_EVENT_NS); that._seriesGroup.off(DOT_EVENT_NS) } }; var ChartTracker = function(options) { this.ctor(options) }; extend(ChartTracker.prototype, baseTrackerPrototype, { _pointClick: function(point, event) { var that = this, eventTrigger = that._eventTrigger, series = point.series; eventTrigger(POINT_CLICK, { target: point, jQueryEvent: event }, function() { !eventCanceled(event, series) && eventTrigger(SERIES_CLICK, { target: series, jQueryEvent: event }) }) }, __trackerDelay: DELAY, update: function(options) { var that = this; that._zoomingMode = _normalizeEnum(options.zoomingMode); that._scrollingMode = _normalizeEnum(options.scrollingMode); baseTrackerPrototype.update.call(this, options); that._argumentAxis = options.argumentAxis || {}; that._axisHoverEnabled = that._argumentAxis && _normalizeEnum(that._argumentAxis.getOptions().hoverMode) === ALL_ARGUMENT_POINTS_MODE; that._chart = options.chart; that._rotated = options.rotated; that._crosshair = options.crosshair }, _getCanvas: function(x, y) { var that = this, canvases = that._canvases || []; for (var i = 0; i < canvases.length; i++) { var c = canvases[i]; if (inCanvas(c, x, y)) { return c } } return null }, _isPointerOut: function(canvas) { return !canvas && this._stuckSeries }, _hideCrosshair: function() { this._crosshair && this._crosshair.hide() }, _moveCrosshair: function(point, x, y) { if (point && this._crosshair && point.isVisible()) { this._crosshair.show({ point: point, x: x, y: y }) } }, _prepare: function() { var that = this, root = that._renderer.root, touchScrollingEnabled = "all" === that._scrollingMode || "touch" === that._scrollingMode, touchZoomingEnabled = "all" === that._zoomingMode || "touch" === that._zoomingMode, cssValue = (!touchScrollingEnabled ? "pan-x pan-y " : "") + (!touchZoomingEnabled ? "pinch-zoom" : "") || "none", rootStyles = { "touch-action": cssValue, "-ms-touch-action": cssValue }, wheelZoomingEnabled = "all" === that._zoomingMode || "mouse" === that._zoomingMode; root.off(addNamespace([wheelEvent.name, "dxc-scroll-start", "dxc-scroll-move"], EVENT_NS)); baseTrackerPrototype._prepare.call(that); if (!that._gestureEndHandler) { that._gestureEndHandler = function() { that._gestureEnd && that._gestureEnd() }; $(document).on(addNamespace(pointerEvents.up, EVENT_NS), that._gestureEndHandler) } wheelZoomingEnabled && root.on(addNamespace(wheelEvent.name, EVENT_NS), function(e) { var rootOffset = that._renderer.getRootOffset(), x = that._rotated ? e.pageY - rootOffset.top : e.pageX - rootOffset.left, scale = that._argumentAxis.getTranslator().getMinScale(e.delta > 0), translate = x - x * scale, zoom = that._argumentAxis.getTranslator().zoom(-translate, scale); that._pointerOut(); that._eventTrigger(ZOOM_START); that._chart.zoomArgument(zoom.min, zoom.max, true); e.preventDefault(); e.stopPropagation() }); root.on(addNamespace("dxc-scroll-start", EVENT_NS), function(e) { that._startScroll = true; that._gestureStart(that._getGestureParams(e, { left: 0, top: 0 })) }).on(addNamespace("dxc-scroll-move", EVENT_NS), function(e) { that._gestureChange(that._getGestureParams(e, { left: 0, top: 0 })) && e.preventDefault() }); root.css(rootStyles) }, _getGestureParams: function(e, offset) { var x1, x2, left, right, that = this, touches = e.pointers.length, eventCoordField = that._rotated ? "pageY" : "pageX"; offset = that._rotated ? offset.top : offset.left; if (2 === touches) { x1 = e.pointers[0][eventCoordField] - offset; x2 = e.pointers[1][eventCoordField] - offset } else { if (1 === touches) { x1 = x2 = e.pointers[0][eventCoordField] - offset } } left = Math.min(x1, x2); right = Math.max(x1, x2); return { center: left + (right - left) / 2, distance: right - left, touches: touches, scale: 1, pointerType: e.pointerType } }, _gestureStart: function(gestureParams) { var that = this; that._startGesture = that._startGesture || gestureParams; if (that._startGesture.touches !== gestureParams.touches) { that._startGesture = gestureParams } }, _gestureChange: function(gestureParams) { var that = this, startGesture = that._startGesture, gestureChanged = false, scrollingEnabled = "all" === that._scrollingMode || "none" !== that._scrollingMode && that._scrollingMode === gestureParams.pointerType, zoomingEnabled = "all" === that._zoomingMode || "touch" === that._zoomingMode; if (!startGesture) { return gestureChanged } if (1 === startGesture.touches && Math.abs(startGesture.center - gestureParams.center) < 3) { that._gestureStart(gestureParams); return gestureChanged } if (2 === startGesture.touches && zoomingEnabled) { gestureChanged = true; startGesture.scale = gestureParams.distance / startGesture.distance; startGesture.scroll = gestureParams.center - startGesture.center + (startGesture.center - startGesture.center * startGesture.scale) } else { if (1 === startGesture.touches && scrollingEnabled) { gestureChanged = true; startGesture.scroll = gestureParams.center - startGesture.center } } if (gestureChanged) { if (that._startScroll) { that._eventTrigger(ZOOM_START); that._startScroll = false } startGesture.changed = gestureChanged; that._chart._transformArgument(startGesture.scroll, startGesture.scale) } return gestureChanged }, _gestureEnd: function() { var zoom, that = this, startGesture = that._startGesture, renderer = that._renderer; that._startGesture = null; that._startScroll = false; function complete() { that._chart.zoomArgument(zoom.min, zoom.max, true) } if (startGesture && startGesture.changed) { zoom = that._argumentAxis._translator.zoom(-startGesture.scroll, startGesture.scale); if (renderer.animationEnabled() && (-startGesture.scroll !== zoom.translate || startGesture.scale !== zoom.scale)) { var translateDelta = -(startGesture.scroll + zoom.translate), scaleDelta = startGesture.scale - zoom.scale; renderer.root.animate({ _: 0 }, { step: function(pos) { var translateValue = -startGesture.scroll - translateDelta * pos, scaleValue = startGesture.scale - scaleDelta * pos; that._chart._transformArgument(-translateValue, scaleValue) }, complete: complete, duration: 250 }) } else { complete() } } }, _clean: function() { var that = this; baseTrackerPrototype._clean.call(that); that._resetTimer(); that._stuckSeries = null }, _getSeriesForShared: function(x, y) { var that = this, points = [], point = null, distance = 1 / 0; if (that._tooltip.isShared() && !that.hoveredSeries) { _each(that._storedSeries, function(_, series) { var point = series.getNeighborPoint(x, y); point && points.push(point) }); _each(points, function(_, p) { var coords = p.getCrosshairData(x, y), d = vizUtils.getDistance(x, y, coords.x, coords.y); if (d < distance) { point = p; distance = d } }) } return point && point.series }, _setTimeout: function(callback, keeper) { var that = this; if (that._timeoutKeeper !== keeper) { that._resetTimer(); that._hoverTimeout = setTimeout(function() { callback(); that._timeoutKeeper = null }, DELAY); that._timeoutKeeper = keeper } }, _resetTimer: function() { clearTimeout(this._hoverTimeout); this._timeoutKeeper = this._hoverTimeout = null }, _checkGestureEvents: function(e, canvas, rootOffset) { var that = this; if (e.type === pointerEvents.down) { if (canvas) { that._startScroll = true; that._gestureStart(that._getGestureParams(e, rootOffset)) } } else { if (that._startGesture && canvas) { if (that._gestureChange(that._getGestureParams(e, rootOffset))) { that._pointerOut(); e.preventDefault(); return true } } } }, _setStuckSeries: function(e, series, x, y) { if ("mouse" !== e.pointerType) { this._stuckSeries = null } else { this._stuckSeries = series || this._stuckSeries || this._getSeriesForShared(x, y) } return !!this._stuckSeries }, _pointerOut: function() { var that = this; that._stuckSeries = null; that._hideCrosshair(); that._resetTimer(); baseTrackerPrototype._pointerOut.call(that) }, _hoverArgumentAxis: function(x, y, e) { var that = this; that._resetHoveredArgument(); if (that._axisHoverEnabled && that._argumentAxis.coordsIn(x, y)) { that._hoverArgument(getData(e, ARG_DATA)); return true } }, _pointerComplete: function(point, x, y) { var that = this; that.hoveredSeries && that.hoveredSeries.updateHover(x, y); that._resetTimer(); that._moveCrosshair(point, x, y); baseTrackerPrototype._pointerComplete.call(that, point) }, _legendClick: function(item, e) { var series = this._storedSeries[item.id]; this._triggerLegendClick({ target: series, jQueryEvent: e }, SERIES_CLICK) }, _hoverLegendItem: function(x, y) { this._stuckSeries = null; this._hideCrosshair(); baseTrackerPrototype._hoverLegendItem.call(this, x, y) }, _pointerOnPoint: function(point, x, y, e) { this._setStuckSeries(e, point.series, x, y); this._releaseHoveredSeries(); baseTrackerPrototype._pointerOnPoint.call(this, point, x, y, e) }, _notifyLegendOnHoverArgument: false, _getArgumentHoverMode: function() { return correctHoverMode(this._argumentAxis) }, dispose: function() { $(document).off(DOT_EVENT_NS, this._gestureEndHandler); this._resetTimer(); baseTrackerPrototype.dispose.call(this) } }); var PieTracker = function(options) { this.ctor(options) }; extend(PieTracker.prototype, baseTrackerPrototype, { _isPointerOut: function(_, point) { return !point }, _legendClick: function(item, e) { var that = this, points = []; that._storedSeries.forEach(function(s) { points.push.apply(points, s.getPointsByKeys(item.argument, item.id)) }); that._eventTrigger(LEGEND_CLICK, { target: item.argument, points: points, jQueryEvent: e }) }, _pointClick: function(point, e) { this._eventTrigger(POINT_CLICK, { target: point, jQueryEvent: e }) }, _hoverLegendItem: function(x, y) { var that = this, item = that._legend.getItemByCoord(x, y); that._resetHoveredArgument(); if (item) { that._hoverArgument(item.argument, item.argumentIndex) } else { that._clearHover() } }, _getArgumentHoverMode: function() { return correctHoverMode(this._legend) }, _hoverArgumentAxis: _noop, _setStuckSeries: _noop, _getCanvas: _noop, _checkGestureEvents: _noop, _notifyLegendOnHoverArgument: true }); exports.ChartTracker = ChartTracker; exports.PieTracker = PieTracker }, /*!*************************************************!*\ !*** ./js/viz/chart_components/header_block.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), LayoutElementModule = __webpack_require__( /*! ../core/layout_element */ 522), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _extend = extend, _each = $.each; function HeaderBlock() {} _extend(HeaderBlock.prototype, LayoutElementModule.LayoutElement.prototype, { update: function(elements, canvas) { this._elements = $.map(elements, function(element) { return element.getLayoutOptions() ? element : null }); this._canvas = canvas }, dispose: function() { this._elements = null }, measure: function() { var result, that = this, layoutOptions = that.getLayoutOptions(); if (layoutOptions) { result = { size: [layoutOptions.width, layoutOptions.height], alignment: [layoutOptions.horizontalAlignment, layoutOptions.verticalAlignment], side: 1 }; _each(that._elements, function(_, elem) { elem.draw(layoutOptions.width, layoutOptions.height, that._canvas) }) } return result || null }, getLayoutOptions: function() { var firstElement, layout, elementLayout, that = this, elements = that._elements, length = elements.length, i = 1; if (!length) { return null } firstElement = elements[0]; layout = _extend(true, {}, firstElement.getLayoutOptions()); layout.position = layout.position || {}; for (i; i < length; i++) { elementLayout = elements[i].getLayoutOptions(); if (elementLayout.height > layout.height) { layout.height = elementLayout.height } layout.width += elementLayout.width; if (elementLayout.position) { layout.position = elementLayout.position; layout.verticalAlignment = elementLayout.position.vertical; layout.horizontalAlignment = elementLayout.position.horizontal } } return layout }, probeDraw: function(width, height) { this._elements.forEach(function(e) { e.probeDraw(width, height); width -= e.getLayoutOptions().width }) }, draw: function(width, height) { var canvas = this._canvas; this._elements.forEach(function(e) { e.draw(width, height, canvas); width -= e.getLayoutOptions().width }) }, shift: function(x, y) { _each(this._elements, function(_, elem) { elem.shift(x, y) }) } }); exports.HeaderBlock = HeaderBlock }, /*!******************************!*\ !*** ./js/viz/core/title.js ***! \******************************/ function(module, exports, __webpack_require__) { var _Number = Number, _isString = __webpack_require__( /*! ../../core/utils/common */ 14).isString, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _patchFontOptions = __webpack_require__( /*! ./utils */ 509).patchFontOptions, parseHorizontalAlignment = __webpack_require__( /*! ./utils */ 509).enumParser(["left", "center", "right"]), parseVerticalAlignment = __webpack_require__( /*! ./utils */ 509).enumParser(["top", "bottom"]), DEFAULT_MARGIN = 10, DEFAULT_GAP = 3; function hasText(text) { return !!(text && String(text).length > 0) } function processTitleLength(elem, text, width) { if (elem.attr({ text: text }).applyEllipsis(width)) { elem.setTitle(text) } } function pickMarginValue(value) { return value >= 0 ? _Number(value) : DEFAULT_MARGIN } function validateMargin(margin) { var result; if (margin >= 0) { result = { left: _Number(margin), top: _Number(margin), right: _Number(margin), bottom: _Number(margin) } } else { margin = margin || {}; result = { left: pickMarginValue(margin.left), top: pickMarginValue(margin.top), right: pickMarginValue(margin.right), bottom: pickMarginValue(margin.bottom) } } return result } function Title(params) { this._params = params; this._group = params.renderer.g().attr({ "class": params.cssClass }).linkOn(params.renderer.root, { name: "title", after: "peripheral" }); this._hasText = false } extend(Title.prototype, __webpack_require__( /*! ./layout_element */ 522).LayoutElement.prototype, { dispose: function() { var that = this; that._group.linkRemove(); that._group.linkOff(); if (that._titleElement) { that._clipRect.dispose(); that._titleElement = that._subtitleElement = that._clipRect = null } that._params = that._group = that._options = null }, _updateOptions: function(options) { this._options = options; this._options.horizontalAlignment = parseHorizontalAlignment(options.horizontalAlignment, "center"); this._options.verticalAlignment = parseVerticalAlignment(options.verticalAlignment, "top"); this._options.margin = validateMargin(options.margin) }, _updateStructure: function() { var that = this, renderer = that._params.renderer, group = that._group, alignObj = { align: that._options.horizontalAlignment }; if (!that._titleElement) { that._titleElement = renderer.text().attr(alignObj).append(group); that._subtitleElement = renderer.text().attr(alignObj); that._clipRect = renderer.clipRect(); group.attr({ "clip-path": that._clipRect.id }) } group.linkAppend(); hasText(that._options.subtitle.text) ? that._subtitleElement.append(group) : that._subtitleElement.remove() }, _updateTexts: function() { var titleBox, y, that = this, options = that._options, subtitleOptions = options.subtitle, titleElement = that._titleElement, subtitleElement = that._subtitleElement, testText = "A"; titleElement.attr({ text: testText, y: 0 }).css(_patchFontOptions(options.font)); titleBox = titleElement.getBBox(); that._titleTextY = titleBox.height + titleBox.y; titleElement.attr({ text: options.text }); titleBox = titleElement.getBBox(); y = -titleBox.y; titleElement.attr({ y: y }); if (hasText(subtitleOptions.text)) { y += titleBox.height + titleBox.y; subtitleElement.attr({ text: subtitleOptions.text, y: 0 }).css(_patchFontOptions(subtitleOptions.font)); y += -subtitleElement.getBBox().y - that._titleTextY + DEFAULT_GAP; subtitleElement.attr({ y: y }) } }, _updateBoundingRectAlignment: function() { var boundingRect = this._boundingRect, options = this._options; boundingRect.verticalAlignment = options.verticalAlignment; boundingRect.horizontalAlignment = options.horizontalAlignment; boundingRect.cutLayoutSide = options.verticalAlignment; boundingRect.cutSide = "vertical"; boundingRect.position = { horizontal: options.horizontalAlignment, vertical: options.verticalAlignment } }, update: function(options) { var that = this, _hasText = hasText(options.text), isLayoutChanged = _hasText || _hasText !== that._hasText; if (_hasText) { that._updateOptions(options); that._updateStructure(); that._updateTexts(); that._boundingRect = {}; that._updateBoundingRect(); that._updateBoundingRectAlignment() } else { that._group.linkRemove(); that._boundingRect = null } that._hasText = _hasText; return isLayoutChanged }, draw: function(width, height) { var layoutOptions, that = this; that._group.linkAppend(); that._correctTitleLength(width); layoutOptions = that.getLayoutOptions(); if (layoutOptions.height > height) { that._params.incidentOccurred("W2103"); that._group.linkRemove(); that._boundingRect.width = that._boundingRect.height = 0 } return that }, probeDraw: function(width, height) { this.draw(width, height); return this }, _correctTitleLength: function(width) { var that = this, options = that._options, margin = options.margin, maxWidth = width - margin.left - margin.right; processTitleLength(that._titleElement, options.text, maxWidth); that._subtitleElement && processTitleLength(that._subtitleElement, options.subtitle.text, maxWidth); that._updateBoundingRect() }, getLayoutOptions: function() { return this._boundingRect || null }, shift: function(x, y) { var that = this, box = that.getLayoutOptions(); that._group.move(x - box.x, y - box.y); that._setClipRectSettings(); return that }, _setClipRectSettings: function() { var bBox = this.getLayoutOptions(); this._clipRect.attr({ x: bBox.x, y: bBox.y, width: bBox.width, height: bBox.height }) }, _updateBoundingRect: function() { var box, that = this, options = that._options, margin = options.margin, boundingRect = that._boundingRect; box = that._group.getBBox(); box.height += margin.top + margin.bottom - that._titleTextY; box.width += margin.left + margin.right; box.x -= margin.left; box.y += that._titleTextY - margin.top; if (options.placeholderSize > 0) { box.height = options.placeholderSize } boundingRect.height = box.height; boundingRect.width = box.width; boundingRect.x = box.x; boundingRect.y = box.y }, layoutOptions: function() { return this._boundingRect && { horizontalAlignment: this._boundingRect.horizontalAlignment, verticalAlignment: this._boundingRect.verticalAlignment } }, measure: function(size) { this.draw(size[0], size[1]); return [this._boundingRect.width, this._boundingRect.height] }, move: function(rect) { var boundingRect = this._boundingRect; if (rect[2] - rect[0] < boundingRect.width || rect[3] - rect[1] < boundingRect.height) { this.draw(rect[2] - rect[0], rect[3] - rect[1]) } this.shift(Math.round(rect[0]), Math.round(rect[1])) } }); exports.Title = Title; Title.prototype.DEBUG_getOptions = function() { return this._options }; function processTitleOptions(options) { var newOptions = _isString(options) ? { text: options } : options || {}; newOptions.subtitle = _isString(newOptions.subtitle) ? { text: newOptions.subtitle } : newOptions.subtitle || {}; return newOptions } exports.plugin = { name: "title", init: function() { var that = this; that._title = new exports.Title({ renderer: that._renderer, cssClass: that._rootClassPrefix + "-title", incidentOccurred: that._incidentOccurred }); that._layout.add(that._title) }, dispose: function() { this._title.dispose(); this._title = null }, members: { _getTitleOptions: function() { return extend(true, {}, this._themeManager.theme("title"), processTitleOptions(this.option("title"))) } }, customize: function(constructor) { constructor.addChange({ code: "TITLE", handler: function() { if (this._title.update(this._getTitleOptions())) { this._change(["LAYOUT"]) } }, isThemeDependent: true, option: "title", isOptionChange: true }) } } }, /*!********************************!*\ !*** ./js/viz/core/tooltip.js ***! \********************************/ function(module, exports, __webpack_require__) { var doc = document, win = window, $ = __webpack_require__( /*! ../../core/renderer */ 9), rendererModule = __webpack_require__( /*! ./renderers/renderer */ 518), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), typeUtils = __webpack_require__( /*! ../../core/utils/type */ 12), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, HALF_ARROW_WIDTH = 10, vizUtils = __webpack_require__( /*! ./utils */ 509), _format = __webpack_require__( /*! ./format */ 530), mathCeil = Math.ceil; function hideElement($element) { $element.css({ left: "-9999px" }).detach() } function getSpecialFormatOptions(options, specialFormat) { var result = options; switch (specialFormat) { case "argument": result = { format: options.argumentFormat, precision: options.argumentPrecision }; break; case "percent": result = { format: { type: "percent", precision: options.format && options.format.percentPrecision || options.percentPrecision } } } return result } function Tooltip(params) { var renderer, root, that = this; that._eventTrigger = params.eventTrigger; that._wrapper = $("<div>").css({ position: "absolute", overflow: "visible", height: "1px", "pointer-events": "none" }).addClass(params.cssClass); that._renderer = renderer = new rendererModule.Renderer({ pathModified: params.pathModified, container: that._wrapper[0] }); root = renderer.root; root.attr({ "pointer-events": "none" }); that._cloud = renderer.path([], "area").sharp().append(root); that._shadow = renderer.shadowFilter(); that._textGroup = renderer.g().attr({ align: "center" }).append(root); that._text = renderer.text(void 0, 0, 0).append(that._textGroup); that._textGroupHtml = $("<div>").css({ position: "absolute", width: 0, padding: 0, margin: 0, border: "0px solid transparent" }).appendTo(that._wrapper); that._textHtml = $("<div>").css({ position: "relative", display: "inline-block", padding: 0, margin: 0, border: "0px solid transparent" }).appendTo(that._textGroupHtml) } Tooltip.prototype = { constructor: Tooltip, dispose: function() { this._wrapper.remove(); this._renderer.dispose(); this._options = null }, _getContainer: function() { var container = $(this._options.container); return (container.length ? container : $("body")).get(0) }, setOptions: function(options) { options = options || {}; var that = this, cloudSettings = that._cloudSettings = { opacity: options.opacity, filter: that._shadow.id, "stroke-width": null, stroke: null }, borderOptions = options.border || {}; that._shadowSettings = extend({ x: "-50%", y: "-50%", width: "200%", height: "200%" }, options.shadow); that._options = options; if (borderOptions.visible) { extend(cloudSettings, { "stroke-width": borderOptions.width, stroke: borderOptions.color, "stroke-opacity": borderOptions.opacity, dashStyle: borderOptions.dashStyle }) } that._textFontStyles = vizUtils.patchFontOptions(options.font); that._textFontStyles.color = options.font.color; that._wrapper.css({ "z-index": options.zIndex }); that._customizeTooltip = commonUtils.isFunction(options.customizeTooltip) ? options.customizeTooltip : null; return that }, setRendererOptions: function(options) { this._renderer.setOptions(options); this._textGroupHtml.css({ direction: options.rtl ? "rtl" : "ltr" }); return this }, render: function() { var that = this; hideElement(that._wrapper); that._cloud.attr(that._cloudSettings); that._shadow.attr(that._shadowSettings); that._textGroupHtml.css(that._textFontStyles); that._textGroup.css(that._textFontStyles); that._text.css(that._textFontStyles); that._eventData = null; return that }, update: function(options) { return this.setOptions(options).render() }, _prepare: function(formatObject, state) { var options = this._options, customize = {}; if (this._customizeTooltip) { customize = this._customizeTooltip.call(formatObject, formatObject); customize = typeUtils.isPlainObject(customize) ? customize : {}; if ("text" in customize) { state.text = commonUtils.isDefined(customize.text) ? String(customize.text) : "" } if ("html" in customize) { state.html = commonUtils.isDefined(customize.html) ? String(customize.html) : "" } } if (!("text" in state) && !("html" in state)) { state.text = formatObject.valueText || "" } state.color = customize.color || options.color; state.borderColor = customize.borderColor || (options.border || {}).color; state.textColor = customize.fontColor || (options.font || {}).color; return !!state.text || !!state.html }, show: function(formatObject, params, eventData) { var bBox, contentSize, that = this, state = {}, options = that._options, paddingLeftRight = options.paddingLeftRight, paddingTopBottom = options.paddingTopBottom, textGroupHtml = that._textGroupHtml, textHtml = that._textHtml, ss = that._shadowSettings, xOff = ss.offsetX, yOff = ss.offsetY, blur = 2 * ss.blur + 1, getComputedStyle = win.getComputedStyle; if (!that._prepare(formatObject, state)) { return false } that._state = state; state.tc = {}; that._wrapper.appendTo(that._getContainer()); that._cloud.attr({ fill: state.color, stroke: state.borderColor }); if (state.html) { that._text.attr({ text: "" }); textGroupHtml.css({ color: state.textColor, width: that._getCanvas().width }); textHtml.html(state.html); if (getComputedStyle) { bBox = getComputedStyle(textHtml.get(0)); bBox = { x: 0, y: 0, width: mathCeil(parseFloat(bBox.width)), height: mathCeil(parseFloat(bBox.height)) } } else { bBox = textHtml.get(0).getBoundingClientRect(); bBox = { x: 0, y: 0, width: mathCeil(bBox.width ? bBox.width : bBox.right - bBox.left), height: mathCeil(bBox.height ? bBox.height : bBox.bottom - bBox.top) } } textGroupHtml.width(bBox.width); textGroupHtml.height(bBox.height) } else { textHtml.html(""); that._text.css({ fill: state.textColor }).attr({ text: state.text }); bBox = that._textGroup.css({ fill: state.textColor }).getBBox() } contentSize = state.contentSize = { x: bBox.x - paddingLeftRight, y: bBox.y - paddingTopBottom, width: bBox.width + 2 * paddingLeftRight, height: bBox.height + 2 * paddingTopBottom, lm: blur - xOff > 0 ? blur - xOff : 0, rm: blur + xOff > 0 ? blur + xOff : 0, tm: blur - yOff > 0 ? blur - yOff : 0, bm: blur + yOff > 0 ? blur + yOff : 0 }; contentSize.fullWidth = contentSize.width + contentSize.lm + contentSize.rm; contentSize.fullHeight = contentSize.height + contentSize.tm + contentSize.bm + options.arrowLength; that.move(params.x, params.y, params.offset); that._eventData && that._eventTrigger("tooltipHidden", that._eventData); that._eventData = eventData; that._eventTrigger("tooltipShown", that._eventData); return true }, hide: function() { var that = this; hideElement(that._wrapper); that._eventData && that._eventTrigger("tooltipHidden", that._eventData); that._eventData = null }, move: function(x, y, offset) { offset = offset || 0; var that = this, canvas = that._getCanvas(), state = that._state, coords = state.tc, contentSize = state.contentSize; if (that._calculatePosition(x, y, offset, canvas)) { that._cloud.attr({ points: coords.cloudPoints }).move(contentSize.lm, contentSize.tm); if (state.html) { that._textGroupHtml.css({ left: -contentSize.x + contentSize.lm, top: -contentSize.y + contentSize.tm + coords.correction }) } else { that._textGroup.move(-contentSize.x + contentSize.lm, -contentSize.y + contentSize.tm + coords.correction) } that._renderer.resize("out" === coords.hp ? canvas.fullWidth - canvas.left : contentSize.fullWidth, "out" === coords.vp ? canvas.fullHeight - canvas.top : contentSize.fullHeight) } offset = that._wrapper.css({ left: 0, top: 0 }).offset(); that._wrapper.css({ left: coords.x - offset.left, top: coords.y - offset.top, width: contentSize.fullWidth }) }, formatValue: function(value, _specialFormat) { var options = _specialFormat ? getSpecialFormatOptions(this._options, _specialFormat) : this._options; return _format(value, options) }, getLocation: function() { return vizUtils.normalizeEnum(this._options.location) }, isEnabled: function() { return !!this._options.enabled }, isShared: function() { return !!this._options.shared }, _calculatePosition: function(x, y, offset, canvas) { var cloudPoints, y1, y3, hasDeprecatedPosition, that = this, options = that._options, arrowLength = options.arrowLength, state = that._state, coords = state.tc, contentSize = state.contentSize, contentWidth = contentSize.width, halfContentWidth = contentWidth / 2, contentHeight = contentSize.height, cTop = y - canvas.top, cBottom = canvas.top + canvas.height - y, cLeft = x - canvas.left, cRight = canvas.width + canvas.left - x, tTop = contentHeight + arrowLength + offset + contentSize.tm, tBottom = contentHeight + arrowLength + offset + contentSize.bm, tLeft = contentWidth + contentSize.lm, tRight = contentWidth + contentSize.rm, tHalfLeft = halfContentWidth + contentSize.lm, tHalfRight = halfContentWidth + contentSize.rm, correction = 0, arrowPoints = [6, 0], x1 = halfContentWidth + HALF_ARROW_WIDTH, x2 = halfContentWidth, x3 = halfContentWidth - HALF_ARROW_WIDTH, y2 = contentHeight + arrowLength, hp = "center", vp = "bottom"; y1 = y3 = contentHeight; switch (options.verticalAlignment) { case "top": vp = "bottom"; hasDeprecatedPosition = true; break; case "bottom": vp = "top"; hasDeprecatedPosition = true } if (!hasDeprecatedPosition) { if (tTop > cTop && tBottom > cBottom) { vp = "out" } else { if (tTop > cTop) { vp = "top" } } } hasDeprecatedPosition = false; switch (options.horizontalAlignment) { case "left": hp = "right"; hasDeprecatedPosition = true; break; case "center": hp = "center"; hasDeprecatedPosition = true; break; case "right": hp = "left"; hasDeprecatedPosition = true } if (!hasDeprecatedPosition) { if (tLeft > cLeft && tRight > cRight) { hp = "out" } else { if (tHalfLeft > cLeft && tRight < cRight) { hp = "left" } else { if (tHalfRight > cRight && tLeft < cLeft) { hp = "right" } } } } if ("out" === hp) { x = canvas.left } else { if ("left" === hp) { x1 = HALF_ARROW_WIDTH; x2 = x3 = 0 } else { if ("right" === hp) { x1 = x2 = contentWidth; x3 = contentWidth - HALF_ARROW_WIDTH; x -= contentWidth } else { if ("center" === hp) { x -= halfContentWidth } } } } if ("out" === vp) { y = canvas.top } else { if ("top" === vp) { "out" !== hp && (correction = arrowLength); arrowPoints[0] = 2; y1 = y3 = arrowLength; y2 = x1; x1 = x3; x3 = y2; y2 = 0; y += offset } else { y -= contentHeight + arrowLength + offset } } coords.x = x - contentSize.lm; coords.y = y - contentSize.tm; coords.correction = correction; if (hp === coords.hp && vp === coords.vp) { return false } coords.hp = hp; coords.vp = vp; cloudPoints = [0, 0 + correction, contentWidth, 0 + correction, contentWidth, contentHeight + correction, 0, contentHeight + correction]; if ("out" !== hp && "out" !== vp) { arrowPoints.splice(2, 0, x1, y1, x2, y2, x3, y3); cloudPoints.splice.apply(cloudPoints, arrowPoints) } coords.cloudPoints = cloudPoints; return true }, _getCanvas: function() { var html = doc.documentElement, body = doc.body; return { left: win.pageXOffset || html.scrollLeft || 0, top: win.pageYOffset || html.scrollTop || 0, width: html.clientWidth || 0, height: html.clientHeight || 0, fullWidth: Math.max(body.scrollWidth, html.scrollWidth, body.offsetWidth, html.offsetWidth, body.clientWidth, html.clientWidth), fullHeight: Math.max(body.scrollHeight, html.scrollHeight, body.offsetHeight, html.offsetHeight, body.clientHeight, html.clientHeight) } } }; exports.Tooltip = Tooltip; exports.plugin = { name: "tooltip", init: function() { this._initTooltip() }, dispose: function() { this._disposeTooltip() }, members: { _initTooltip: function() { this._tooltip = new exports.Tooltip({ cssClass: this._rootClassPrefix + "-tooltip", eventTrigger: this._eventTrigger, pathModified: this.option("pathModified") }) }, _disposeTooltip: function() { this._tooltip.dispose(); this._tooltip = null }, _hideTooltip: function() { this._tooltip.hide() }, _onRender: function() { if (!this._$element.is(":visible")) { this._hideTooltip() } }, _setTooltipRendererOptions: function() { this._tooltip.setRendererOptions(this._getRendererOptions()) }, _setTooltipOptions: function() { this._tooltip.update(this._getOption("tooltip")) } }, customize: function(constructor) { var proto = constructor.prototype; proto._eventsMap.onTooltipShown = { name: "tooltipShown" }; proto._eventsMap.onTooltipHidden = { name: "tooltipHidden" }; constructor.addChange({ code: "TOOLTIP_RENDERER", handler: function() { this._setTooltipRendererOptions() }, isThemeDependent: true, isOptionChange: true }); constructor.addChange({ code: "TOOLTIP", handler: function() { this._setTooltipOptions() }, isThemeDependent: true, isOptionChange: true, option: "tooltip" }) } } }, /*!******************************************!*\ !*** ./js/viz/core/loading_indicator.js ***! \******************************************/ function(module, exports, __webpack_require__) { var _patchFontOptions = __webpack_require__( /*! ./utils */ 509).patchFontOptions, STATE_HIDDEN = 0, STATE_SHOWN = 1, ANIMATION_EASING = "linear", ANIMATION_DURATION = 400, LOADING_INDICATOR_READY = "loadingIndicatorReady"; function LoadingIndicator(parameters) { var that = this, renderer = parameters.renderer; that._group = renderer.g().attr({ "class": "dx-loading-indicator" }).linkOn(renderer.root, { name: "loading-indicator", after: "peripheral" }); that._rect = renderer.rect().attr({ opacity: 0 }).append(that._group); that._text = renderer.text().attr({ align: "center" }).append(that._group); that._createStates(parameters.eventTrigger, that._group, renderer.root, parameters.notify) } LoadingIndicator.prototype = { constructor: LoadingIndicator, _createStates: function(eventTrigger, group, root, notify) { var that = this; that._states = [{ opacity: 0, start: function() { notify(false) }, complete: function() { group.linkRemove(); root.css({ "pointer-events": "" }); eventTrigger(LOADING_INDICATOR_READY) } }, { opacity: .85, start: function() { group.linkAppend(); root.css({ "pointer-events": "none" }); notify(true) }, complete: function() { eventTrigger(LOADING_INDICATOR_READY) } }]; that._state = STATE_HIDDEN }, setSize: function(size) { var width = size.width, height = size.height; this._rect.attr({ width: width, height: height }); this._text.attr({ x: width / 2, y: height / 2 }) }, setOptions: function(options) { this._rect.attr({ fill: options.backgroundColor }); this._text.css(_patchFontOptions(options.font)).attr({ text: options.text }); this[options.show ? "show" : "hide"]() }, dispose: function() { var that = this; that._group.linkRemove().linkOff(); that._group = that._rect = that._text = that._states = null }, _transit: function(stateId) { var state, that = this; if (that._state !== stateId) { that._state = stateId; that._isHiding = false; state = that._states[stateId]; that._rect.stopAnimation().animate({ opacity: state.opacity }, { complete: state.complete, easing: ANIMATION_EASING, duration: ANIMATION_DURATION, unstoppable: true }); that._noHiding = true; state.start(); that._noHiding = false } }, show: function() { this._transit(STATE_SHOWN) }, hide: function() { this._transit(STATE_HIDDEN) }, scheduleHiding: function() { if (!this._noHiding) { this._isHiding = true } }, fulfillHiding: function() { if (this._isHiding) { this.hide() } } }; exports.LoadingIndicator = LoadingIndicator; exports.plugin = { name: "loading_indicator", init: function() { var that = this; that._loadingIndicator = new exports.LoadingIndicator({ eventTrigger: that._eventTrigger, renderer: that._renderer, notify: notify }); that._scheduleLoadingIndicatorHiding(); function notify(state) { that._skipLoadingIndicatorOptions = true; that.option("loadingIndicator", { show: state }); that._skipLoadingIndicatorOptions = false; if (state) { that._hideTooltip && that._hideTooltip() } } }, dispose: function() { this._loadingIndicator.dispose(); this._loadingIndicator = null }, members: { _scheduleLoadingIndicatorHiding: function() { this._loadingIndicator.scheduleHiding() }, _fulfillLoadingIndicatorHiding: function() { this._loadingIndicator.fulfillHiding() }, showLoadingIndicator: function() { this._loadingIndicator.show() }, hideLoadingIndicator: function() { this._loadingIndicator.hide() }, _onBeginUpdate: function() { this._scheduleLoadingIndicatorHiding() } }, customize: function(constructor) { var proto = constructor.prototype; if (proto._dataSourceChangedHandler) { var _dataSourceChangedHandler = proto._dataSourceChangedHandler; proto._dataSourceChangedHandler = function() { this._scheduleLoadingIndicatorHiding(); _dataSourceChangedHandler.apply(this, arguments) } } var _setContentSize = proto._setContentSize; proto._setContentSize = function() { _setContentSize.apply(this, arguments); this._loadingIndicator.setSize(this._canvas) }; constructor.addChange({ code: "LOADING_INDICATOR", handler: function() { if (!this._skipLoadingIndicatorOptions) { this._loadingIndicator.setOptions(this._getOption("loadingIndicator")) } this._scheduleLoadingIndicatorHiding() }, isThemeDependent: true, option: "loadingIndicator", isOptionChange: true }); proto._eventsMap.onLoadingIndicatorReady = { name: "loadingIndicatorReady" }; var _drawn = proto._drawn; proto._drawn = function() { _drawn.apply(this, arguments); if (this._dataIsReady()) { this._fulfillLoadingIndicatorHiding() } } } } }, /*!************************************!*\ !*** ./js/viz/core/data_source.js ***! \************************************/ function(module, exports, __webpack_require__) { var name, noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, DataHelperMixin = __webpack_require__( /*! ../../data_helper */ 152), postCtor = DataHelperMixin.postCtor, members = { _dataSourceLoadErrorHandler: function() { this._dataSourceChangedHandler() }, _dataSourceOptions: function() { return { paginate: false } }, _updateDataSource: function() { this._refreshDataSource(); if (!this.option("dataSource")) { this._dataSourceChangedHandler() } }, _dataIsLoaded: function() { return !this._dataSource || this._dataSource.isLoaded() }, _dataSourceItems: function() { return this._dataSource && this._dataSource.items() } }; for (name in DataHelperMixin) { if ("postCtor" === name) { continue } members[name] = DataHelperMixin[name] } exports.plugin = { name: "data_source", init: function() { postCtor.call(this) }, dispose: noop, members: members } }, /*!************************************************************!*\ !*** ./js/viz/chart_components/multi_axes_synchronizer.js ***! \************************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), debug = __webpack_require__( /*! ../../core/utils/console */ 13).debug, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), vizUtils = __webpack_require__( /*! ../core/utils */ 509), _adjustValue = vizUtils.adjustValue, _applyPrecisionByMinDelta = vizUtils.applyPrecisionByMinDelta, _isDefined = commonUtils.isDefined, _math = Math, _floor = _math.floor, _max = _math.max, _abs = _math.abs, _each = $.each, _map = __webpack_require__( /*! ../core/utils */ 509).map, MIN_RANGE_FOR_ADJUST_BOUNDS = .1; var getValueAxesPerPanes = function(valueAxes) { var result = {}; _each(valueAxes, function(_, axis) { var pane = axis.pane; if (!result[pane]) { result[pane] = [] } result[pane].push(axis) }); return result }; var linearConverter = { transform: function(v, b) { return vizUtils.getLog(v, b) }, addInterval: function(v, i) { return v + i }, getInterval: function(base, tickInterval) { return tickInterval }, adjustValue: _floor }; var logConverter = { transform: function(v, b) { return vizUtils.raiseTo(v, b) }, addInterval: function(v, i) { return v * i }, getInterval: function(base, tickInterval) { return _math.pow(base, tickInterval) }, adjustValue: _adjustValue }; var convertAxisInfo = function(axisInfo, converter) { if (!axisInfo.isLogarithmic) { return } var tick, interval, i, base = axisInfo.logarithmicBase, tickValues = axisInfo.tickValues, ticks = []; axisInfo.minValue = converter.transform(axisInfo.minValue, base); axisInfo.oldMinValue = converter.transform(axisInfo.oldMinValue, base); axisInfo.maxValue = converter.transform(axisInfo.maxValue, base); axisInfo.oldMaxValue = converter.transform(axisInfo.oldMaxValue, base); axisInfo.tickInterval = _math.round(axisInfo.tickInterval); if (axisInfo.tickInterval < 1) { axisInfo.tickInterval = 1 } interval = converter.getInterval(base, axisInfo.tickInterval); tick = converter.transform(tickValues[0], base); for (i = 0; i < tickValues.length; i++) { ticks.push(converter.adjustValue(tick)); tick = converter.addInterval(tick, interval) } ticks.tickInterval = axisInfo.tickInterval; axisInfo.tickValues = ticks }; var populateAxesInfo = function(axes) { return _map(axes, function(axis) { var minValue, maxValue, businessRange, tickInterval, synchronizedValue, ticksValues = axis.getTicksValues(), majorTicks = ticksValues.majorTicksValues, options = axis.getOptions(), axisInfo = null; if (majorTicks && majorTicks.length > 0 && commonUtils.isNumeric(majorTicks[0]) && "discrete" !== options.type) { businessRange = axis.getTranslator().getBusinessRange(); tickInterval = axis._tickManager.getTickInterval(); minValue = businessRange.minVisible; maxValue = businessRange.maxVisible; synchronizedValue = options.synchronizedValue; if (minValue === maxValue && _isDefined(synchronizedValue)) { tickInterval = _abs(majorTicks[0] - synchronizedValue) || 1; minValue = majorTicks[0] - tickInterval; maxValue = majorTicks[0] + tickInterval } axisInfo = { axis: axis, isLogarithmic: "logarithmic" === options.type, logarithmicBase: businessRange.base, tickValues: majorTicks, minorValues: ticksValues.minorTicksValues, minValue: minValue, oldMinValue: minValue, maxValue: maxValue, oldMaxValue: maxValue, inverted: businessRange.invert, tickInterval: tickInterval, synchronizedValue: synchronizedValue }; if (businessRange.stubData) { axisInfo.stubData = true; axisInfo.tickInterval = axisInfo.tickInterval || options.tickInterval; axisInfo.isLogarithmic = false } convertAxisInfo(axisInfo, linearConverter); debug.assert(void 0 !== axisInfo.tickInterval && null !== axisInfo.tickInterval, "tickInterval was not provided") } return axisInfo }) }; var updateTickValues = function(axesInfo) { var maxTicksCount = 0; _each(axesInfo, function(_, axisInfo) { maxTicksCount = _max(maxTicksCount, axisInfo.tickValues.length) }); _each(axesInfo, function(_, axisInfo) { var ticksMultiplier, ticksCount, additionalStartTicksCount = 0, synchronizedValue = axisInfo.synchronizedValue, tickValues = axisInfo.tickValues, tickInterval = axisInfo.tickInterval; if (_isDefined(synchronizedValue)) { axisInfo.baseTickValue = axisInfo.invertedBaseTickValue = synchronizedValue; axisInfo.tickValues = [axisInfo.baseTickValue] } else { if (tickValues.length > 1 && tickInterval) { ticksMultiplier = _floor((maxTicksCount + 1) / tickValues.length); ticksCount = ticksMultiplier > 1 ? _floor((maxTicksCount + 1) / ticksMultiplier) : maxTicksCount; additionalStartTicksCount = _floor((ticksCount - tickValues.length) / 2); while (additionalStartTicksCount > 0 && 0 !== tickValues[0]) { tickValues.unshift(_applyPrecisionByMinDelta(tickValues[0], tickInterval, tickValues[0] - tickInterval)); additionalStartTicksCount-- } while (tickValues.length < ticksCount) { tickValues.push(_applyPrecisionByMinDelta(tickValues[0], tickInterval, tickValues[tickValues.length - 1] + tickInterval)) } axisInfo.tickInterval = tickInterval / ticksMultiplier } axisInfo.baseTickValue = tickValues[0]; axisInfo.invertedBaseTickValue = tickValues[tickValues.length - 1] } }) }; var getAxisRange = function(axisInfo) { return axisInfo.maxValue - axisInfo.minValue || 1 }; var getMainAxisInfo = function(axesInfo) { for (var i = 0; i < axesInfo.length; i++) { if (!axesInfo[i].stubData) { return axesInfo[i] } } return null }; var correctMinMaxValues = function(axesInfo) { var mainAxisInfo = getMainAxisInfo(axesInfo), mainAxisInfoTickInterval = mainAxisInfo.tickInterval; _each(axesInfo, function(_, axisInfo) { var scale, move, mainAxisBaseValueOffset, valueFromAxisInfo; if (axisInfo !== mainAxisInfo) { if (mainAxisInfoTickInterval && axisInfo.tickInterval) { if (axisInfo.stubData && _isDefined(axisInfo.synchronizedValue)) { axisInfo.oldMinValue = axisInfo.minValue = axisInfo.baseTickValue - (mainAxisInfo.baseTickValue - mainAxisInfo.minValue) / mainAxisInfoTickInterval * axisInfo.tickInterval; axisInfo.oldMaxValue = axisInfo.maxValue = axisInfo.baseTickValue - (mainAxisInfo.baseTickValue - mainAxisInfo.maxValue) / mainAxisInfoTickInterval * axisInfo.tickInterval } scale = mainAxisInfoTickInterval / getAxisRange(mainAxisInfo) / axisInfo.tickInterval * getAxisRange(axisInfo); axisInfo.maxValue = axisInfo.minValue + getAxisRange(axisInfo) / scale } if (mainAxisInfo.inverted && !axisInfo.inverted || !mainAxisInfo.inverted && axisInfo.inverted) { mainAxisBaseValueOffset = mainAxisInfo.maxValue - mainAxisInfo.invertedBaseTickValue } else { mainAxisBaseValueOffset = mainAxisInfo.baseTickValue - mainAxisInfo.minValue } valueFromAxisInfo = getAxisRange(axisInfo); move = (mainAxisBaseValueOffset / getAxisRange(mainAxisInfo) - (axisInfo.baseTickValue - axisInfo.minValue) / valueFromAxisInfo) * valueFromAxisInfo; axisInfo.minValue -= move; axisInfo.maxValue -= move } }) }; var calculatePaddings = function(axesInfo) { var minPadding, maxPadding, startPadding = 0, endPadding = 0; _each(axesInfo, function(_, axisInfo) { var inverted = axisInfo.inverted; minPadding = axisInfo.minValue > axisInfo.oldMinValue ? (axisInfo.minValue - axisInfo.oldMinValue) / getAxisRange(axisInfo) : 0; maxPadding = axisInfo.maxValue < axisInfo.oldMaxValue ? (axisInfo.oldMaxValue - axisInfo.maxValue) / getAxisRange(axisInfo) : 0; startPadding = _max(startPadding, inverted ? maxPadding : minPadding); endPadding = _max(endPadding, inverted ? minPadding : maxPadding) }); return { start: startPadding, end: endPadding } }; var correctMinMaxValuesByPaddings = function(axesInfo, paddings) { _each(axesInfo, function(_, info) { var range = getAxisRange(info), inverted = info.inverted; info.minValue -= paddings[inverted ? "end" : "start"] * range; info.maxValue += paddings[inverted ? "start" : "end"] * range; if (range > MIN_RANGE_FOR_ADJUST_BOUNDS) { info.minValue = _math.min(info.minValue, _adjustValue(info.minValue)); info.maxValue = _max(info.maxValue, _adjustValue(info.maxValue)) } }) }; var updateTickValuesIfSynchronizedValueUsed = function(axesInfo) { var hasSynchronizedValue = false; _each(axesInfo, function(_, info) { hasSynchronizedValue = hasSynchronizedValue || _isDefined(info.synchronizedValue) }); _each(axesInfo, function(_, info) { var lastTickValue, tickInterval = info.tickInterval, tickValues = info.tickValues, maxValue = info.maxValue, minValue = info.minValue; if (hasSynchronizedValue && tickInterval) { while (tickValues[0] - tickInterval >= minValue) { tickValues.unshift(_adjustValue(tickValues[0] - tickInterval)) } lastTickValue = tickValues[tickValues.length - 1]; while ((lastTickValue += tickInterval) <= maxValue) { tickValues.push(commonUtils.isExponential(lastTickValue) ? _adjustValue(lastTickValue) : _applyPrecisionByMinDelta(minValue, tickInterval, lastTickValue)) } } while (tickValues[0] < minValue) { tickValues.shift() } while (tickValues[tickValues.length - 1] > maxValue) { tickValues.pop() } }) }; var applyMinMaxValues = function(axesInfo) { _each(axesInfo, function(_, info) { var axis = info.axis, range = axis.getTranslator().getBusinessRange(); if (range.min === range.minVisible) { range.min = info.minValue } if (range.max === range.maxVisible) { range.max = info.maxValue } range.minVisible = info.minValue; range.maxVisible = info.maxValue; if (_isDefined(info.stubData)) { range.stubData = info.stubData } if (range.min > range.minVisible) { range.min = range.minVisible } if (range.max < range.maxVisible) { range.max = range.maxVisible } range.isSynchronized = true; axis.getTranslator().updateBusinessRange(range); axis.setTicks({ majorTicks: info.tickValues, minorTicks: info.minorValues }) }) }; var correctAfterSynchronize = function(axesInfo) { var correctValue, validAxisInfo, invalidAxisInfo = []; _each(axesInfo, function(i, info) { if (info.oldMaxValue - info.oldMinValue === 0) { invalidAxisInfo.push(info) } else { if (!_isDefined(correctValue) && !_isDefined(info.synchronizedValue)) { correctValue = _abs((info.maxValue - info.minValue) / (info.tickValues[_floor(info.tickValues.length / 2)] - info.minValue || info.maxValue)); validAxisInfo = info } } }); if (!_isDefined(correctValue)) { return } _each(invalidAxisInfo, function(i, info) { var firstTick = info.tickValues[0], correctedTick = firstTick * correctValue, tickValues = validAxisInfo.tickValues, centralTick = tickValues[_floor(tickValues.length / 2)]; if (firstTick > 0) { info.maxValue = correctedTick; info.minValue = 0 } else { if (firstTick < 0) { info.minValue = correctedTick; info.maxValue = 0 } else { if (0 === firstTick) { info.maxValue = validAxisInfo.maxValue - centralTick; info.minValue = validAxisInfo.minValue - centralTick } } } }) }; var multiAxesSynchronizer = { synchronize: function(valueAxes) { _each(getValueAxesPerPanes(valueAxes), function(_, axes) { var axesInfo, paddings; if (axes.length > 1) { axesInfo = populateAxesInfo(axes); if (0 === axesInfo.length || !getMainAxisInfo(axesInfo)) { return } updateTickValues(axesInfo); correctMinMaxValues(axesInfo); paddings = calculatePaddings(axesInfo); correctMinMaxValuesByPaddings(axesInfo, paddings); correctAfterSynchronize(axesInfo); updateTickValuesIfSynchronizedValueUsed(axesInfo); _each(axesInfo, function() { convertAxisInfo(this, logConverter) }); applyMinMaxValues(axesInfo) } }) } }; module.exports = multiAxesSynchronizer }, /*!***************************************************!*\ !*** ./js/viz/chart_components/advanced_chart.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, rangeModule = __webpack_require__( /*! ../translators/range */ 564), DEFAULT_AXIS_NAME = "defaultAxisName", axisModule = __webpack_require__( /*! ../axes/base_axis */ 565), seriesFamilyModule = __webpack_require__( /*! ../core/series_family */ 580), BaseChart = __webpack_require__( /*! ./base_chart */ 514).BaseChart, crosshairModule = __webpack_require__( /*! ./crosshair */ 581), _isArray = Array.isArray, _isDefined = commonUtils.isDefined, _each = $.each, _noop = commonUtils.noop, _extend = extend, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _map = vizUtils.map; function getCrosshairMargins(crosshairOptions) { crosshairOptions = crosshairOptions || {}; var crosshairEnabled = crosshairOptions.enabled, margins = crosshairModule.getMargins(); return { x: crosshairEnabled && crosshairOptions.horizontalLine.visible ? margins.x : 0, y: crosshairEnabled && crosshairOptions.verticalLine.visible ? margins.y : 0 } } function prepareAxis(axisOptions) { return _isArray(axisOptions) ? 0 === axisOptions.length ? [{}] : axisOptions : [axisOptions] } var AdvancedChart = BaseChart.inherit({ _dispose: function() { var that = this, disposeObjectsInArray = this._disposeObjectsInArray; that.callBase(); that.panes = null; if (that._legend) { that._legend.dispose(); that._legend = null } disposeObjectsInArray.call(that, "panesBackground"); disposeObjectsInArray.call(that, "seriesFamilies"); that._disposeAxes() }, _reinitAxes: function() { this.panes = this._createPanes(); this._populateAxes() }, _populateAxes: function() { var argumentAxes, paneWithNonVirtualAxis, that = this, valueAxes = [], panes = that.panes, rotated = that._isRotated(), valueAxisOptions = that.option("valueAxis") || {}, argumentOption = that.option("argumentAxis") || {}, argumentAxesOptions = prepareAxis(argumentOption)[0], valueAxesOptions = prepareAxis(valueAxisOptions), axisNames = [], valueAxesCounter = 0, crosshairMargins = getCrosshairMargins(that._getCrosshairOptions()); function getNextAxisName() { return DEFAULT_AXIS_NAME + valueAxesCounter++ } that._disposeAxes(); if (rotated) { paneWithNonVirtualAxis = "right" === argumentAxesOptions.position ? panes[panes.length - 1].name : panes[0].name } else { paneWithNonVirtualAxis = "top" === argumentAxesOptions.position ? panes[0].name : panes[panes.length - 1].name } argumentAxes = _map(panes, function(pane, index) { return that._createAxis("argumentAxis", argumentAxesOptions, { pane: pane.name, crosshairMargin: rotated ? crosshairMargins.x : crosshairMargins.y }, rotated, pane.name !== paneWithNonVirtualAxis, index) }); _each(valueAxesOptions, function(priority, axisOptions) { var axisPanes = [], name = axisOptions.name; if (name && inArray(name, axisNames) !== -1) { that._incidentOccurred("E2102"); return } name && axisNames.push(name); if (axisOptions.pane) { axisPanes.push(axisOptions.pane) } if (axisOptions.panes && axisOptions.panes.length) { axisPanes = axisPanes.concat(axisOptions.panes.slice(0)) } axisPanes = vizUtils.unique(axisPanes); if (!axisPanes.length) { axisPanes.push(void 0) } _each(axisPanes, function(_, pane) { valueAxes.push(that._createAxis("valueAxis", axisOptions, { name: name || getNextAxisName(), pane: pane, priority: priority, crosshairMargin: rotated ? crosshairMargins.y : crosshairMargins.x }, rotated)) }) }); that._valueAxes = valueAxes; that._argumentAxes = argumentAxes }, _prepareStackPoints: function(singleSeries, stackPoints) { var points = singleSeries.getPoints(), stackName = singleSeries.getStackName(); _each(points, function(_, point) { var argument = point.argument; if (!stackPoints[argument]) { stackPoints[argument] = {}; stackPoints[argument][null] = [] } if (stackName && !_isArray(stackPoints[argument][stackName])) { stackPoints[argument][stackName] = []; _each(stackPoints[argument][null], function(_, point) { if (!point.stackName) { stackPoints[argument][stackName].push(point) } }) } if (stackName) { stackPoints[argument][stackName].push(point); stackPoints[argument][null].push(point) } else { _each(stackPoints[argument], function(_, stack) { stack.push(point) }) } point.stackPoints = stackPoints[argument][stackName]; point.stackName = stackName }) }, _resetStackPoints: function(singleSeries) { _each(singleSeries.getPoints(), function(_, point) { point.stackPoints = null; point.stackName = null }) }, _disposeAxes: function() { var that = this, disposeObjectsInArray = that._disposeObjectsInArray; disposeObjectsInArray.call(that, "_argumentAxes"); disposeObjectsInArray.call(that, "_valueAxes") }, _drawAxes: function(drawOptions, panesBorderOptions) { this._restoreOriginalBusinessRange(); this._prepareAxesAndDraw(drawOptions, panesBorderOptions) }, _restoreOriginalBusinessRange: _noop, _appendAdditionalSeriesGroups: function() { this._crosshairCursorGroup.linkAppend(); this._scrollBar && this._scrollBarGroup.linkAppend() }, _getLegendTargets: function() { var that = this; return _map(that.series, function(item) { if (item.getOptions().showInLegend) { return that._getLegendOptions(item) } return null }) }, _legendItemTextField: "name", _seriesPopulatedHandlerCore: function() { this._processSeriesFamilies(); this._processValueAxisFormat() }, _renderTrackers: function() { var i, that = this; for (i = 0; i < that.series.length; ++i) { that.series[i].drawTrackers() } }, _specialProcessSeries: function() { this._processSeriesFamilies() }, _processSeriesFamilies: function() { var paneSeries, that = this, types = [], families = [], themeManager = that._themeManager, negativesAsZeroes = themeManager.getOptions("negativesAsZeroes"), negativesAsZeros = themeManager.getOptions("negativesAsZeros"), familyOptions = { equalBarWidth: themeManager.getOptions("equalBarWidth"), minBubbleSize: themeManager.getOptions("minBubbleSize"), maxBubbleSize: themeManager.getOptions("maxBubbleSize"), barWidth: themeManager.getOptions("barWidth"), negativesAsZeroes: _isDefined(negativesAsZeroes) ? negativesAsZeroes : negativesAsZeros }; if (that.seriesFamilies && that.seriesFamilies.length) { _each(that.seriesFamilies, function(_, family) { family.updateOptions(familyOptions); family.adjustSeriesValues() }); return } _each(that.series, function(_, item) { if (inArray(item.type, types) === -1) { types.push(item.type) } }); _each(that._getLayoutTargets(), function(_, pane) { paneSeries = that._getSeriesForPane(pane.name); _each(types, function(_, type) { var family = new seriesFamilyModule.SeriesFamily({ type: type, pane: pane.name, equalBarWidth: familyOptions.equalBarWidth, minBubbleSize: familyOptions.minBubbleSize, maxBubbleSize: familyOptions.maxBubbleSize, barWidth: familyOptions.barWidth, negativesAsZeroes: familyOptions.negativesAsZeroes, rotated: that._isRotated() }); family.add(paneSeries); family.adjustSeriesValues(); families.push(family) }) }); that.seriesFamilies = families }, _updateSeriesDimensions: function() { var i, that = this, seriesFamilies = that.seriesFamilies || []; for (i = 0; i < seriesFamilies.length; i++) { var family = seriesFamilies[i]; family.updateSeriesValues(); family.adjustSeriesDimensions() } }, _getLegendCallBack: function(series) { return this._legend && this._legend.getActionCallback(series) }, _appendAxesGroups: function() { var that = this; that._stripsGroup.linkAppend(); that._gridGroup.linkAppend(); that._axesGroup.linkAppend(); that._constantLinesGroup.linkAppend(); that._labelAxesGroup.linkAppend() }, _populateBusinessRange: function() { var that = this, businessRanges = [], rotated = that._isRotated(), argAxes = that._argumentAxes, argRange = new rangeModule.Range({ rotated: !!rotated }), groupsData = that._groupsData; that.businessRanges = null; _each(argAxes, function(_, axis) { argRange.addRange(axis.getRangeData()) }); that._valueAxes.forEach(function(valueAxis) { var groupRange = new rangeModule.Range({ rotated: !!rotated, pane: valueAxis.pane, axis: valueAxis.name }), groupAxisRange = valueAxis.getRangeData(), groupSeries = that.series.filter(function(series) { return series.getValueAxis() === valueAxis }); groupRange.addRange(groupAxisRange); groupSeries.forEach(function(series) { var seriesRange = series.getRangeData(); groupRange.addRange(seriesRange.val); argRange.addRange(seriesRange.arg) }); if (!groupRange.isDefined()) { groupRange.setStubData(valueAxis.getOptions().valueType) } if (valueAxis.getOptions().showZero) { groupRange.correctValueZeroLevel() } groupRange.checkZeroStick(); valueAxis.setBusinessRange(groupRange); businessRanges.push({ val: groupRange, arg: argRange }) }); argRange.sortCategories(groupsData.categories); if (!argRange.isDefined()) { argRange.setStubData(argAxes[0].getOptions().argumentType) } that._argumentAxes.forEach(function(a) { a.setBusinessRange(argRange) }); that.businessRanges = businessRanges }, _getArgumentAxis: function() { return this._argumentAxes[0] }, _getArgumentAxes: function() { return this._argumentAxes }, _getValueAxes: function() { return this._valueAxes }, _getGroupsData: function() { var that = this, groups = []; that._valueAxes.forEach(function(axis) { groups.push({ series: that.series.filter(function(series) { return series.getValueAxis() === axis }), valueAxis: axis, valueOptions: axis.getOptions() }) }); return { groups: groups, argumentAxes: that._argumentAxes, argumentOptions: that._argumentAxes[0].getOptions() } }, _groupSeries: function() { var that = this; that._correctValueAxes(); that._groupsData = that._getGroupsData() }, _processValueAxisFormat: function() { var axesWithFullStackedFormat = []; this.series.forEach(function(series) { var axis = series.getValueAxis(); if (series.isFullStackedSeries()) { axis.setPercentLabelFormat(); axesWithFullStackedFormat.push(axis) } }); this._valueAxes.forEach(function(axis) { if (axesWithFullStackedFormat.indexOf(axis) === -1) { axis.resetAutoLabelFormat() } }) }, _createAxis: function(typeSelector, userOptions, axisOptions, rotated, virtual, index) { var axis, that = this, renderingSettings = _extend({ renderer: that._renderer, incidentOccurred: that._incidentOccurred, axisClass: "argumentAxis" === typeSelector ? "arg" : "val", widgetClass: "dxc", stripsGroup: that._stripsGroup, labelAxesGroup: that._labelAxesGroup, constantLinesGroup: that._constantLinesGroup, axesContainerGroup: that._axesGroup, gridGroup: that._gridGroup }, that._getAxisRenderingOptions(typeSelector)), preparedUserOptions = that._prepareStripsAndConstantLines(typeSelector, userOptions, rotated), options = _extend(true, {}, preparedUserOptions, axisOptions, that._prepareAxisOptions(typeSelector, preparedUserOptions, rotated)); if (virtual) { options.visible = options.tick.visible = options.minorTick.visible = options.label.visible = false; options.title = {} } axis = new axisModule.Axis(renderingSettings); axis.updateOptions(options); if (!virtual && _isDefined(index)) { that._displayedArgumentAxisIndex = index } return axis }, _getTrackerSettings: function() { return _extend(this.callBase(), { argumentAxis: this._argumentAxes[this._displayedArgumentAxisIndex] }) }, _prepareStripsAndConstantLines: function(typeSelector, userOptions, rotated) { userOptions = this._themeManager.getOptions(typeSelector, userOptions, rotated); if (userOptions.strips) { _each(userOptions.strips, function(i) { userOptions.strips[i] = _extend(true, {}, userOptions.stripStyle, userOptions.strips[i]) }) } if (userOptions.constantLines) { _each(userOptions.constantLines, function(i, line) { userOptions.constantLines[i] = _extend(true, {}, userOptions.constantLineStyle, line) }) } return userOptions }, _legendDataField: "series", _adjustSeries: _noop, _correctValueAxes: _noop }); exports.AdvancedChart = AdvancedChart }, /*!*************************************!*\ !*** ./js/viz/translators/range.js ***! \*************************************/ function(module, exports, __webpack_require__) { var _Range, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _isDefined = commonUtils.isDefined, _isDate = commonUtils.isDate, unique = __webpack_require__( /*! ../core/utils */ 509).unique, minSelector = "min", maxSelector = "max", minVisibleSelector = "minVisible", maxVisibleSelector = "maxVisible", baseSelector = "base", axisTypeSelector = "axisType"; function otherLessThan(thisValue, otherValue) { return otherValue < thisValue } function otherGreaterThan(thisValue, otherValue) { return otherValue > thisValue } function compareAndReplace(thisValue, otherValue, setValue, compare) { var otherValueDefined = _isDefined(otherValue); if (_isDefined(thisValue)) { if (otherValueDefined && compare(thisValue, otherValue)) { setValue(otherValue) } } else { if (otherValueDefined) { setValue(otherValue) } } } _Range = exports.Range = function(range) { range && extend(this, range) }; _Range.prototype = { constructor: _Range, addRange: function(otherRange) { var that = this, categories = that.categories, otherCategories = otherRange.categories; var compareAndReplaceByField = function(field, compare) { compareAndReplace(that[field], otherRange[field], function(value) { that[field] = value }, compare) }; var controlValuesByVisibleBounds = function(valueField, visibleValueField, compare) { compareAndReplace(that[valueField], that[visibleValueField], function(value) { _isDefined(that[valueField]) && (that[valueField] = value) }, compare) }; var checkField = function(field) { that[field] = that[field] || otherRange[field] }; if (commonUtils.isDefined(otherRange.stick)) { that.stick = otherRange.stick } checkField("addSpiderCategory"); checkField("percentStick"); checkField("minSpaceCorrection"); checkField("maxSpaceCorrection"); checkField("invert"); checkField(axisTypeSelector); checkField("dataType"); if ("logarithmic" === that[axisTypeSelector]) { checkField(baseSelector) } else { that[baseSelector] = void 0 } compareAndReplaceByField(minSelector, otherLessThan); compareAndReplaceByField(maxSelector, otherGreaterThan); if ("discrete" === that[axisTypeSelector]) { checkField(minVisibleSelector); checkField(maxVisibleSelector) } else { compareAndReplaceByField(minVisibleSelector, otherLessThan); compareAndReplaceByField(maxVisibleSelector, otherGreaterThan) } compareAndReplaceByField("interval", otherLessThan); controlValuesByVisibleBounds(minSelector, minVisibleSelector, otherLessThan); controlValuesByVisibleBounds(minSelector, maxVisibleSelector, otherLessThan); controlValuesByVisibleBounds(maxSelector, maxVisibleSelector, otherGreaterThan); controlValuesByVisibleBounds(maxSelector, minVisibleSelector, otherGreaterThan); if (void 0 === categories) { that.categories = otherCategories } else { that.categories = otherCategories ? unique(categories.concat(otherCategories)) : categories } return that }, isDefined: function() { return _isDefined(this[minSelector]) && _isDefined(this[maxSelector]) || this.categories && this.categories.length }, setStubData: function(dataType) { var that = this, year = (new Date).getFullYear() - 1, isDate = "datetime" === dataType, axisType = that[axisTypeSelector], min = "logarithmic" === axisType ? 1 : 0; if ("discrete" === axisType) { that.categories = isDate ? [new Date(year, 0, 1), new Date(year, 3, 1), new Date(year, 6, 1), new Date(year, 9, 1)] : ["0", "1", "2"] } else { that[minSelector] = isDate ? new Date(year, 0, 1) : min; that[maxSelector] = isDate ? new Date(year, 11, 31) : 10 } that.stubData = true; return that }, correctValueZeroLevel: function() { var that = this; if ("logarithmic" === that[axisTypeSelector] || _isDate(that[maxSelector]) || _isDate(that[minSelector])) { return that } function setZeroLevel(min, max) { that[min] < 0 && that[max] < 0 && (that[max] = 0); that[min] > 0 && that[max] > 0 && (that[min] = 0) } setZeroLevel(minSelector, maxSelector); setZeroLevel(minVisibleSelector, maxVisibleSelector); return that }, sortCategories: function(arr) { var cat = this.categories, callback = "datetime" === this.dataType ? function(item) { return cat.map(Number).indexOf(item.valueOf()) !== -1 } : function(item) { return cat.indexOf(item) !== -1 }; arr && cat && (this.categories = arr.filter(callback)) }, checkZeroStick: function() { var that = this; if (that.min >= 0 && that.max >= 0) { that.minStickValue = 0 } else { if (that.min <= 0 && that.max <= 0) { that.maxStickValue = 0 } } return that } } }, /*!**********************************!*\ !*** ./js/viz/axes/base_axis.js ***! \**********************************/ function(module, exports, __webpack_require__) { var Axis, $ = __webpack_require__( /*! ../../core/renderer */ 9), vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, constants = __webpack_require__( /*! ./axes_constants */ 566), parseUtils = __webpack_require__( /*! ../components/parse_utils */ 524), tickManagerModule = __webpack_require__( /*! ./base_tick_manager */ 567), Translator2DModule = __webpack_require__( /*! ../translators/translator2d */ 571), rangeModule = __webpack_require__( /*! ../translators/range */ 564), tick = __webpack_require__( /*! ./tick */ 577).tick, formatLabel = constants.formatLabel, convertTicksToValues = constants.convertTicksToValues, _isDefined = commonUtils.isDefined, _isNumber = commonUtils.isNumeric, _getSignificantDigitPosition = vizUtils.getSignificantDigitPosition, _roundValue = vizUtils.roundValue, patchFontOptions = vizUtils.patchFontOptions, _math = Math, _abs = _math.abs, _max = _math.max, _min = _math.min, _each = $.each, _noop = commonUtils.noop, DEFAULT_AXIS_LABEL_SPACING = 5, MAX_GRID_BORDER_ADHENSION = 4, TOP = constants.top, BOTTOM = constants.bottom, LEFT = constants.left, RIGHT = constants.right, CENTER = constants.center; function createMajorTick(axis, renderer) { var options = axis.getOptions(); return tick(axis, renderer, options.tick, options.grid, axis._getSkippedCategory(), axis._translator.getBusinessRange().stubData) } function createMinorTick(axis, renderer) { var options = axis.getOptions(); return tick(axis, renderer, options.minorTick, options.minorGrid) } function createBoundaryTick(axis, renderer, isFirst) { var options = axis.getOptions(); return tick(axis, renderer, extend({}, options.tick, { visible: options.showCustomBoundaryTicks }), options.grid, void 0, false, isFirst ? -1 : 1) } function callAction(ticks, action, actionArgument) { ticks.forEach(function(tick) { tick[action](actionArgument) }) } function initTickCoords(ticks) { callAction(ticks, "initCoords") } function drawTickMarks(ticks) { callAction(ticks, "drawMark") } function drawGrids(ticks, drawLine) { callAction(ticks, "drawGrid", drawLine) } function updateTicksPosition(ticks) { callAction(ticks, "updateTickPosition") } function updateGridsPosition(ticks) { callAction(ticks, "updateGridPosition") } function measureLabels(items) { items.forEach(function(item) { item.labelBBox = item.label ? item.label.getBBox() : { x: 0, y: 0, width: 0, height: 0 } }) } function isEmptyArray(categories) { return categories && categories.length } function getMarginValue(range, margin, checkMax) { var min = _isDefined(range.minVisible) ? range.minVisible : range.min, max = _isDefined(range.maxVisible) ? range.maxVisible : range.max; return vizUtils.applyPrecisionByMinDelta(checkMax ? max : min, margin || 0, _abs(max - min) * margin) } function getAddFunction(range) { if ("datetime" === range.dataType) { return function(rangeValue, marginValue) { return new Date(rangeValue.getTime() + marginValue) } } return function(rangeValue, marginValue) { return rangeValue + marginValue } } function validateAxisOptions(options) { var labelOptions = options.label, position = options.position, defaultPosition = options.isHorizontal ? BOTTOM : LEFT, secondaryPosition = options.isHorizontal ? TOP : RIGHT; if (position !== defaultPosition && position !== secondaryPosition) { position = defaultPosition } if (position === RIGHT && !labelOptions.userAlignment) { labelOptions.alignment = LEFT } options.position = position; options.hoverMode = options.hoverMode ? options.hoverMode.toLowerCase() : "none"; labelOptions.minSpacing = _isDefined(labelOptions.minSpacing) ? labelOptions.minSpacing : DEFAULT_AXIS_LABEL_SPACING } function getOptimalAngle(boxes, labelOpt) { var angle = 180 * _math.asin((boxes[0].height + labelOpt.minSpacing) / (boxes[1].x - boxes[0].x)) / _math.PI; return angle < 45 ? -45 : -90 } function updateLabels(ticks, step, func) { ticks.forEach(function(tick, index) { if (tick.label) { if (index % step !== 0) { tick.label.remove() } else { if (func) { func(tick, index) } } } }) } Axis = exports.Axis = function(renderSettings) { var that = this; that._renderer = renderSettings.renderer; that._incidentOccurred = renderSettings.incidentOccurred; that._stripsGroup = renderSettings.stripsGroup; that._labelAxesGroup = renderSettings.labelAxesGroup; that._constantLinesGroup = renderSettings.constantLinesGroup; that._axesContainerGroup = renderSettings.axesContainerGroup; that._gridContainerGroup = renderSettings.gridGroup; that._axisCssPrefix = renderSettings.widgetClass + "-" + (renderSettings.axisClass ? renderSettings.axisClass + "-" : ""); that._setType(renderSettings.axisType, renderSettings.drawingType); that._createAxisGroups(); that._tickManager = that._createTickManager(); that._translator = that._createTranslator() }; Axis.prototype = { constructor: Axis, _updateIntervalAndBounds: function() { var i, ticks, length, minInterval, bounds, that = this, translator = that._translator, businessRange = translator.getBusinessRange(); if (!isEmptyArray(businessRange.categories)) { ticks = that._majorTicks; length = ticks.length; if (!businessRange.isSynchronized) { bounds = this._tickManager.getTickBounds() } if (length > 1) { minInterval = _abs(ticks[0].value - ticks[1].value); for (i = 1; i < length - 1; i++) { minInterval = _min(_abs(ticks[i].value - ticks[i + 1].value), minInterval) } bounds = extend({ interval: minInterval }, bounds) } if (bounds) { businessRange.addRange(bounds); translator.reinit() } } }, _drawAxis: function() { var options = this._options; if (!options.visible) { return } this._axisElement = this._createAxisElement(); this._updateAxisElementPosition(); this._axisElement.attr({ "stroke-width": options.width, stroke: options.color, "stroke-opacity": options.opacity }).sharp(this._getSharpParam(true)).append(this._axisLineGroup) }, _correctMinForTicks: function(min, max, screenDelta) { var correctingValue, diff = _abs(max - min) / screenDelta, digitPosition = commonUtils.isExponential(diff) && diff < 1 ? vizUtils.getPrecision(diff) : _getSignificantDigitPosition(diff), newMin = _roundValue(Number(min), digitPosition); if (newMin < min) { correctingValue = _math.pow(10, -digitPosition); newMin = vizUtils.applyPrecisionByMinDelta(newMin, correctingValue, newMin + correctingValue) } if (newMin > max) { newMin = min } return newMin }, _getTickManagerData: function() { var that = this, options = that._options, screenDelta = that._getScreenDelta(), min = that._minBound, max = that._maxBound, categories = that._translator.getVisibleCategories() || that._translator.getBusinessRange().categories, customTicks = options.customTicks || (isEmptyArray(categories) ? categories : that._majorTicks && that._majorTicks.length && convertTicksToValues(that._majorTicks)), customMinorTicks = options.customMinorTicks || that._minorTicks && that._minorTicks.length && convertTicksToValues(that._minorTicks); if (_isNumber(min) && options.type !== constants.logarithmic) { min = that._correctMinForTicks(min, max, screenDelta) } return { min: min, max: max, customTicks: customTicks, customMinorTicks: customMinorTicks, customBoundTicks: options.customBoundTicks, screenDelta: screenDelta } }, _getTickManagerTypes: function() { return { axisType: this._options.type, dataType: this._options.dataType } }, _getTicksOptions: function() { var options = this._options; return { base: options.type === constants.logarithmic ? options.logarithmBase : void 0, tickInterval: this._translator.getBusinessRange().stubData ? null : options.tickInterval, gridSpacingFactor: options.axisDivisionFactor, minorGridSpacingFactor: options.minorAxisDivisionFactor, numberMultipliers: options.numberMultipliers, incidentOccurred: options.incidentOccurred, setTicksAtUnitBeginning: options.setTicksAtUnitBeginning, showMinorTicks: options.minorTick.visible || options.minorGrid.visible, minorTickInterval: options.minorTickInterval, minorTickCount: options.minorTickCount, showCalculatedTicks: options.tick.showCalculatedTicks, showMinorCalculatedTicks: options.minorTick.showCalculatedTicks } }, _createTickManager: function() { return new tickManagerModule.TickManager({}, {}) }, _getMarginsOptions: function() { var range = this._translator.getBusinessRange(); return { stick: range.stick || this._options.stick, minStickValue: range.minStickValue, maxStickValue: range.maxStickValue, percentStick: range.percentStick, minSpaceCorrection: range.minSpaceCorrection, maxSpaceCorrection: range.maxSpaceCorrection, minValueMargin: this._options.minValueMargin, maxValueMargin: this._options.maxValueMargin } }, _getLabelOptions: function() { return { hasLabelFormat: this._hasLabelFormat, isMarkersVisible: "discrete" === this._options.type ? false : this._options.marker.visible, addMinMax: this._options.showCustomBoundaryTicks ? this._boundaryTicksVisibility : void 0, forceUserTickInterval: "ignore" === this._options.label.overlappingBehavior.mode ? true : this._options.forceUserTickInterval } }, _updateTickManager: function() { var that = this, options = extend(true, that._getMarginsOptions(), that._getTicksOptions(), that._getLabelOptions()); this._tickManager.update(that._getTickManagerTypes(), that._getTickManagerData(), options) }, _correctLabelFormat: function() { var labelFormat = this._tickManager.getOptions().labelFormat; if (labelFormat) { this._options.label.format = labelFormat } }, _createPathElement: function(points, attr) { return this._renderer.path(points, "line").attr(attr).sharp(this._getSharpParam()) }, _getGridLineDrawer: function(borderOptions) { var that = this, isHorizontal = that._isHorizontal; return function(tick, gridStyle) { that.borderOptions = borderOptions; var element, canvasStart = isHorizontal ? LEFT : TOP, canvasEnd = isHorizontal ? RIGHT : BOTTOM, axisCanvas = that.getCanvas(), canvas = { left: axisCanvas.left, right: axisCanvas.width - axisCanvas.right, top: axisCanvas.top, bottom: axisCanvas.height - axisCanvas.bottom }, firstBorderLinePosition = borderOptions.visible && borderOptions[canvasStart] ? canvas[canvasStart] : void 0, lastBorderLinePosition = borderOptions.visible && borderOptions[canvasEnd] ? canvas[canvasEnd] : void 0, tickPositionField = isHorizontal ? "x" : "y", minDelta = MAX_GRID_BORDER_ADHENSION + firstBorderLinePosition, maxDelta = lastBorderLinePosition - MAX_GRID_BORDER_ADHENSION; if (void 0 === tick.coords[tickPositionField] || tick.coords[tickPositionField] < minDelta || tick.coords[tickPositionField] > maxDelta) { return } var grid = that._getGridPoints(tick.coords); if (grid.points) { element = that._createPathElement(grid.points, gridStyle) } return element } }, _getGridPoints: function(coords) { var isHorizontal = this._isHorizontal, tickPositionField = isHorizontal ? "x" : "y", orthogonalPositions = this._orthogonalPositions, positionFrom = orthogonalPositions.start, positionTo = orthogonalPositions.end; return { points: isHorizontal ? null !== coords[tickPositionField] ? [coords[tickPositionField], positionFrom, coords[tickPositionField], positionTo] : null : null !== coords[tickPositionField] ? [positionFrom, coords[tickPositionField], positionTo, coords[tickPositionField]] : null } }, _getConstantLinePos: function(lineValue, canvasStart, canvasEnd) { var parsedValue = this._validateUnit(lineValue, "E2105", "constantLine"), value = this._getTranslatedCoord(parsedValue); if (!_isDefined(value) || value < _min(canvasStart, canvasEnd) || value > _max(canvasStart, canvasEnd)) { return {} } return { value: value, parsedValue: parsedValue } }, _getConstantLineGraphicAttributes: function(value) { var positionFrom = this._orthogonalPositions.start, positionTo = this._orthogonalPositions.end; return { points: this._isHorizontal ? [value, positionFrom, value, positionTo] : [positionFrom, value, positionTo, value] } }, _createConstantLine: function(value, attr) { return this._createPathElement(this._getConstantLineGraphicAttributes(value).points, attr) }, _drawConstantLinesAndLabels: function(position, lineOptions, canvasStart, canvasEnd) { if (!_isDefined(lineOptions.value)) { return { line: null, label: null, options: lineOptions } } var side, that = this, pos = that._getConstantLinePos(lineOptions.value, canvasStart, canvasEnd), labelOptions = lineOptions.label || {}, value = pos.value, attr = { stroke: lineOptions.color, "stroke-width": lineOptions.width, dashStyle: lineOptions.dashStyle }, group = that._axisConstantLineGroups[position]; if (!group) { side = that._isHorizontal ? labelOptions.verticalAlignment : labelOptions.horizontalAlignment; group = that._axisConstantLineGroups[side] } if (!_isDefined(value)) { return { line: null, label: null, options: lineOptions } } return { line: that._createConstantLine(value, attr).append(that._axisConstantLineGroups.inside), label: labelOptions.visible ? that._drawConstantLineLabels(pos.parsedValue, labelOptions, value, group) : null, options: lineOptions, labelOptions: labelOptions, coord: value } }, _drawConstantLines: function(position) { var that = this, canvas = that._getCanvasStartEnd(); if (that._translator.getBusinessRange().stubData) { return [] } return (that._options.constantLines || []).reduce(function(result, constantLine) { var labelPos = constantLine.label.position; if (labelPos === position || !labelPos && "inside" === position) { result.push(that._drawConstantLinesAndLabels(position, constantLine, canvas.start, canvas.end)) } return result }, []) }, _drawConstantLineLabelText: function(text, x, y, constantLineLabelOptions, group) { var that = this, options = that._options, labelOptions = options.label; return that._renderer.text(text, x, y).css(patchFontOptions(extend({}, labelOptions.font, constantLineLabelOptions.font))).attr({ align: "center" }).append(group) }, _drawConstantLineLabels: function(parsedValue, lineLabelOptions, value, group) { var coords, that = this, text = lineLabelOptions.text, options = that._options, labelOptions = options.label; that._checkAlignmentConstantLineLabels(lineLabelOptions); text = _isDefined(text) ? text : formatLabel(parsedValue, labelOptions); coords = that._getConstantLineLabelsCoords(value, lineLabelOptions); return that._drawConstantLineLabelText(text, coords.x, coords.y, lineLabelOptions, group) }, _getStripPos: function(startValue, endValue, canvasStart, canvasEnd, range) { var start, end, swap, startCategoryIndex, endCategoryIndex, isContinuous = !!(range.minVisible || range.maxVisible), categories = range.categories || [], min = range.minVisible; if (!isContinuous) { if (_isDefined(startValue) && _isDefined(endValue)) { startCategoryIndex = inArray(startValue, categories); endCategoryIndex = inArray(endValue, categories); if (startCategoryIndex === -1 || endCategoryIndex === -1) { return { from: 0, to: 0 } } if (startCategoryIndex > endCategoryIndex) { swap = endValue; endValue = startValue; startValue = swap } } } if (_isDefined(startValue)) { startValue = this._validateUnit(startValue, "E2105", "strip"); start = this._getTranslatedCoord(startValue, -1); if (!_isDefined(start) && isContinuous) { start = startValue < min ? canvasStart : canvasEnd } } else { start = canvasStart } if (_isDefined(endValue)) { endValue = this._validateUnit(endValue, "E2105", "strip"); end = this._getTranslatedCoord(endValue, 1); if (!_isDefined(end) && isContinuous) { end = endValue > min ? canvasEnd : canvasStart } } else { end = canvasEnd } return start < end ? { from: start, to: end } : { from: end, to: start } }, _getStripGraphicAttributes: function(fromPoint, toPoint) { var x, y, width, height, orthogonalPositions = this._orthogonalPositions, positionFrom = orthogonalPositions.start, positionTo = orthogonalPositions.end; if (this._isHorizontal) { x = fromPoint; y = _min(positionFrom, positionTo); width = toPoint - fromPoint; height = _abs(positionFrom - positionTo) } else { x = _min(positionFrom, positionTo); y = fromPoint; width = _abs(positionFrom - positionTo); height = _abs(fromPoint - toPoint) } return { x: x, y: y, width: width, height: height } }, _createStrip: function(fromPoint, toPoint, attr) { var attrs = this._getStripGraphicAttributes(fromPoint, toPoint); return this._renderer.rect(attrs.x, attrs.y, attrs.width, attrs.height).attr(attr) }, _drawStrips: function() { var i, stripOptions, stripPos, stripLabelOptions, attr, labelCoords, that = this, options = that._options, stripData = options.strips, canvas = this._getCanvasStartEnd(), range = that._translator.getBusinessRange(), strips = []; if (!stripData || range.stubData) { return [] } for (i = 0; i < stripData.length; i++) { stripOptions = stripData[i]; stripLabelOptions = stripOptions.label || {}; attr = { fill: stripOptions.color }; if ((_isDefined(stripOptions.startValue) || _isDefined(stripOptions.endValue)) && _isDefined(stripOptions.color)) { stripPos = that._getStripPos(stripOptions.startValue, stripOptions.endValue, canvas.start, canvas.end, range); labelCoords = stripLabelOptions.text ? that._getStripLabelCoords(stripPos.from, stripPos.to, stripLabelOptions) : null; if (stripPos.to - stripPos.from === 0 || !_isDefined(stripPos.to) || !_isDefined(stripPos.from)) { continue } strips.push({ rect: that._createStrip(stripPos.from, stripPos.to, attr).append(that._axisStripGroup), options: stripOptions, label: stripLabelOptions.text ? that._drawStripLabel(stripLabelOptions, labelCoords) : null, labelCoords: labelCoords }) } } return strips }, _drawStripLabel: function(stripLabelOptions, coords) { return this._renderer.text(stripLabelOptions.text, coords.x, coords.y).css(patchFontOptions(extend({}, this._options.label.font, stripLabelOptions.font))).attr({ align: "center" }).append(this._axisStripLabelGroup) }, _adjustStripLabels: function() { var that = this; this._strips.forEach(function(strip) { if (strip.label) { strip.label.attr(that._getAdjustedStripLabelCoords(strip)) } }) }, _adjustLabels: function(offset) { var that = this, maxSize = that._majorTicks.reduce(function(size, tick) { var bBox = tick.labelRotationAngle ? vizUtils.rotateBBox(tick.labelBBox, [tick.labelCoords.x, tick.labelCoords.y], -tick.labelRotationAngle) : tick.labelBBox; return { width: _max(size.width || 0, bBox.width), height: _max(size.height || 0, bBox.height), offset: _max(size.offset || 0, tick.labelOffset || 0) } }, {}), additionalOffset = that._isHorizontal ? maxSize.height : maxSize.width; that._majorTicks.forEach(function(tick) { if (tick.label) { tick.label.attr(that._getLabelAdjustedCoord(tick, offset + (tick.labelOffset || 0), maxSize.width)) } }); return offset + additionalOffset + (additionalOffset && that._options.label.indentFromAxis) + maxSize.offset }, _getLabelAdjustedCoord: function(tick, offset, maxWidth) { offset = offset || 0; var translateX, translateY, that = this, options = that._options, box = vizUtils.rotateBBox(tick.labelBBox, [tick.labelCoords.x, tick.labelCoords.y], -tick.labelRotationAngle || 0), position = options.position, textAlign = tick.labelAlignment || options.label.alignment, indentFromAxis = options.label.indentFromAxis, axisPosition = that._axisPosition, labelCoords = tick.labelCoords, labelX = labelCoords.x; if (that._isHorizontal) { if (position === BOTTOM) { translateY = axisPosition + indentFromAxis - box.y + offset } else { translateY = axisPosition - indentFromAxis - (box.y + box.height) - offset } if (textAlign === RIGHT) { translateX = labelX - box.x - box.width } else { if (textAlign === LEFT) { translateX = labelX - box.x } else { translateX = labelX - box.x - box.width / 2 } } } else { translateY = labelCoords.y - box.y - box.height / 2; if (position === LEFT) { if (textAlign === LEFT) { translateX = axisPosition - indentFromAxis - maxWidth - box.x } else { if (textAlign === CENTER) { translateX = axisPosition - indentFromAxis - maxWidth / 2 - box.x - box.width / 2 } else { translateX = axisPosition - indentFromAxis - box.x - box.width } } translateX -= offset } else { if (textAlign === RIGHT) { translateX = axisPosition + indentFromAxis + maxWidth - box.x - box.width } else { if (textAlign === CENTER) { translateX = axisPosition + indentFromAxis + maxWidth / 2 - box.x - box.width / 2 } else { translateX = axisPosition + indentFromAxis - box.x } } translateX += offset } } return { translateX: translateX, translateY: translateY } }, _createAxisGroups: function() { var insideGroup, outsideGroup1, outsideGroup2, that = this, renderer = that._renderer, classSelector = that._axisCssPrefix, constantLinesClass = classSelector + "constant-lines"; that._axisGroup = renderer.g().attr({ "class": classSelector + "axis" }); that._axisStripGroup = renderer.g().attr({ "class": classSelector + "strips" }); that._axisGridGroup = renderer.g().attr({ "class": classSelector + "grid" }); that._axisElementsGroup = renderer.g().attr({ "class": classSelector + "elements" }).append(that._axisGroup); that._axisLineGroup = renderer.g().attr({ "class": classSelector + "line" }).append(that._axisGroup); that._axisTitleGroup = renderer.g().attr({ "class": classSelector + "title" }).append(that._axisGroup); insideGroup = renderer.g().attr({ "class": constantLinesClass }); outsideGroup1 = renderer.g().attr({ "class": constantLinesClass }); outsideGroup2 = renderer.g().attr({ "class": constantLinesClass }); that._axisConstantLineGroups = { inside: insideGroup, outside1: outsideGroup1, left: outsideGroup1, top: outsideGroup1, outside2: outsideGroup2, right: outsideGroup2, bottom: outsideGroup2 }; that._axisStripLabelGroup = renderer.g().attr({ "class": classSelector + "axis-labels" }) }, _clearAxisGroups: function() { var that = this; that._axisGroup.remove(); that._axisStripGroup.remove(); that._axisStripLabelGroup.remove(); that._axisConstantLineGroups.inside.remove(); that._axisConstantLineGroups.outside1.remove(); that._axisConstantLineGroups.outside2.remove(); that._axisGridGroup.remove(); that._axisTitleGroup.clear(); that._axisElementsGroup.clear(); that._axisLineGroup && that._axisLineGroup.clear(); that._axisStripGroup && that._axisStripGroup.clear(); that._axisGridGroup && that._axisGridGroup.clear(); that._axisConstantLineGroups.inside.clear(); that._axisConstantLineGroups.outside1.clear(); that._axisConstantLineGroups.outside2.clear(); that._axisStripLabelGroup && that._axisStripLabelGroup.clear() }, _formatTickLabel: function(value) { return formatLabel(value, this._options.label, { min: this._minBound, max: this._maxBound }) }, _setTickOffset: function() { var options = this._options, discreteAxisDivisionMode = options.discreteAxisDivisionMode; this._tickOffset = +("crossLabels" !== discreteAxisDivisionMode || !discreteAxisDivisionMode) }, getMargins: function() { var that = this, options = that._options, position = options.position, placeholderSize = options.placeholderSize, canvas = that.getCanvas(), cLeft = canvas.left, cTop = canvas.top, cRight = canvas.width - canvas.right, cBottom = canvas.height - canvas.bottom, boxes = [that._axisElementsGroup, that._axisConstantLineGroups.outside1, that._axisConstantLineGroups.outside2].map(function(group) { return group && group.getBBox() }).concat(function(group) { var box = group && group.getBBox(); if (!box || box.isEmpty) { return box } if (that._isHorizontal) { box.x = cLeft; box.width = cRight - cLeft } else { box.y = cTop; box.height = cBottom - cTop } return box }(that._axisTitleGroup)), margins = boxes.reduce(function(margins, bBox) { if (!bBox || bBox.isEmpty) { return margins } return { left: _max(margins.left, cLeft - bBox.x), top: _max(margins.top, cTop - bBox.y), right: _max(margins.right, bBox.x + bBox.width - cRight), bottom: _max(margins.bottom, bBox.y + bBox.height - cBottom) } }, { left: 0, right: 0, top: 0, bottom: 0 }); margins[position] += options.crosshairMargin; if (placeholderSize) { margins[position] = placeholderSize } return margins }, _validateUnit: function(unit, idError, parameters) { var that = this; unit = that.parser(unit); if (void 0 === unit && idError) { that._incidentOccurred(idError, [parameters]) } return unit }, _setType: function(axisType, drawingType) { var axisTypeMethods, that = this; switch (axisType) { case "xyAxes": axisTypeMethods = __webpack_require__( /*! ./xy_axes */ 578); break; case "polarAxes": axisTypeMethods = __webpack_require__( /*! ./polar_axes */ 579) } _each(axisTypeMethods[drawingType], function(methodName, method) { that[methodName] = method }) }, _getSharpParam: function() { return true }, dispose: function() { var that = this; that._axisElementsGroup && that._axisElementsGroup.dispose(); that._strips = null; that._title = null; that._axisStripGroup = that._axisConstantLineGroups = that._axisStripLabelGroup = null; that._axisLineGroup = that._axisElementsGroup = that._axisGridGroup = null; that._axisGroup = that._axisTitleGroup = null; that._axesContainerGroup = that._stripsGroup = that._constantLinesGroup = null; that._renderer = that._options = that._textOptions = that._textFontStyles = null; that._translator = null; that._majorTicks = that._minorTicks = null; that._tickManager = null }, getOptions: function() { return this._options }, setPane: function(pane) { this.pane = pane; this._options.pane = pane }, setTypes: function(type, axisType, typeSelector) { this._options.type = type || this._options.type; this._options[typeSelector] = axisType || this._options[typeSelector] }, resetTypes: function(typeSelector) { this._options.type = this._initTypes.type; this._options[typeSelector] = this._initTypes[typeSelector] }, getTranslator: function() { return this._translator }, updateOptions: function(options) { var that = this, labelOpt = options.label; that._options = options; options.tick = options.tick || {}; options.minorTick = options.minorTick || {}; options.grid = options.grid || {}; options.minorGrid = options.minorGrid || {}; options.title = options.title || {}; options.marker = options.marker || {}; that._initTypes = { type: options.type, argumentType: options.argumentType, valueType: options.valueType }; validateAxisOptions(options); that._setTickOffset(); that._isHorizontal = options.isHorizontal; that.pane = options.pane; that.name = options.name; that.priority = options.priority; that._hasLabelFormat = "" !== labelOpt.format && _isDefined(labelOpt.format); that._textOptions = { opacity: labelOpt.opacity, align: "center" }; that._textFontStyles = vizUtils.patchFontOptions(labelOpt.font); if (options.type === constants.logarithmic) { if (options.logarithmBaseError) { that._incidentOccurred("E2104"); delete options.logarithmBaseError } that.calcInterval = function(value, prevValue) { return vizUtils.getLog(value / prevValue, options.logarithmBase) } } that._updateTranslator() }, _processCanvas: function(canvas) { return canvas }, updateCanvas: function(canvas) { var positions = this._orthogonalPositions = { start: !this._isHorizontal ? canvas.left : canvas.top, end: !this._isHorizontal ? canvas.width - canvas.right : canvas.height - canvas.bottom }; this._canvas = canvas; positions.center = positions.start + (positions.end - positions.start) / 2; this._translator.updateCanvas(this._processCanvas(canvas)); this._initAxisPositions() }, getCanvas: function() { return this._canvas }, hideTitle: function() { var that = this; if (that._options.title.text) { that._incidentOccurred("W2105", [that._isHorizontal ? "horizontal" : "vertical"]); that._axisTitleGroup.clear() } }, hideOuterElements: function() { var that = this, options = that._options, constantLineLabels = that._outsideConstantLines.map(function(line) { return line.label }); if ((options.label.visible || constantLineLabels.length) && !that._translator.getBusinessRange().stubData) { that._incidentOccurred("W2106", [that._isHorizontal ? "horizontal" : "vertical"]); that._axisElementsGroup.clear(); constantLineLabels.forEach(function(label) { label && label.remove() }) } }, _saveBusinessRange: function() { this._storedBusinessRange = new rangeModule.Range(this._translator.getBusinessRange()) }, restoreBusinessRange: function() { var zoomArgs = this._zoomArgs, range = new rangeModule.Range(this._storedBusinessRange); if (zoomArgs) { this.zoom(zoomArgs.min, zoomArgs.max, zoomArgs.stick) } else { this._updateBusinessRange(range) } }, _applyMargins: function(range) { var minMarginValue, maxMarginValue, options = this._options, type = options.type, valueMarginsEnabled = options.valueMarginsEnabled && "logarithmic" !== type && "discrete" !== type, add = getAddFunction(range); if (valueMarginsEnabled) { minMarginValue = getMarginValue(range, options.minValueMargin); maxMarginValue = getMarginValue(range, options.maxValueMargin, true); range.addRange({ min: add(range.min, -minMarginValue), max: add(range.max, maxMarginValue), minVisible: _isDefined(range.minVisible) ? add(range.minVisible, -minMarginValue) : void 0, maxVisible: _isDefined(range.maxVisible) ? add(range.maxVisible, maxMarginValue) : void 0 }) } }, setBusinessRange: function(range) { this._applyMargins(range); this._updateBusinessRange(range); this._saveBusinessRange(range) }, _updateBusinessRange: function(range) { var that = this; that._translator.updateBusinessRange(range); that._minBound = range.minVisible; that._maxBound = range.maxVisible }, getLabelsPosition: function() { var that = this, options = that._options, position = options.position, labelShift = options.label.indentFromAxis + (that._axisShift || 0) + that._constantLabelOffset, axisPosition = that._axisPosition; return position === TOP || position === LEFT ? axisPosition - labelShift : axisPosition + labelShift }, getFormattedValue: function(value, options, point) { var labelOptions = this._options.label; return _isDefined(value) ? formatLabel(value, extend(true, {}, labelOptions, options), void 0, point) : null }, _getBoundaryTicks: function() { var categories = this._translator.getVisibleCategories() || this._translator.getBusinessRange().categories; return isEmptyArray(categories) && this._tickOffset ? [categories[0], categories[categories.length - 1]] : this._tickManager.getBoundaryTicks() }, setPercentLabelFormat: function() { if (!this._hasLabelFormat) { this._options.label.format = "percent" } }, resetAutoLabelFormat: function() { if (!this._hasLabelFormat) { delete this._options.label.format } }, getMultipleAxesSpacing: function() { return this._options.multipleAxesSpacing || 0 }, getTicksValues: function() { return { majorTicksValues: convertTicksToValues(this._majorTicks), minorTicksValues: convertTicksToValues(this._minorTicks) } }, setTicks: function(ticks) { this._majorTicks = (ticks.majorTicks || []).map(createMajorTick(this, this._renderer)); this._minorTicks = (ticks.minorTicks || []).map(createMinorTick(this, this._renderer)); this._updateTickManager() }, createTicks: function(canvas) { var boundaryTicks, that = this, renderer = that._renderer, tickManager = that._tickManager; if (!canvas) { that._updateIntervalAndBounds(); return } that.updateCanvas(canvas); that._majorTicks = that._minorTicks = null; that._updateTickManager(); that._majorTicks = tickManager.getTicks().map(createMajorTick(this, renderer)); that._minorTicks = tickManager.getMinorTicks().map(createMinorTick(this, renderer)); that.correctTicksOnDeprecated(); boundaryTicks = that._getBoundaryTicks(); if (this._options.showCustomBoundaryTicks && boundaryTicks.length) { that._boundaryTicks = [boundaryTicks[0]].map(createBoundaryTick(this, renderer, true)); if (boundaryTicks.length > 1) { that._boundaryTicks = that._boundaryTicks.concat([boundaryTicks[1]].map(createBoundaryTick(this, renderer, false))) } } that._correctLabelFormat(); that._updateIntervalAndBounds() }, correctTicksOnDeprecated: function() { var behavior = this._options.label.overlappingBehavior, majorTicks = this._majorTicks, length = majorTicks.length; if (length) { majorTicks[0].withoutLabel = behavior.hideFirstLabel; majorTicks[length - 1].withoutLabel = behavior.hideLastLabel; majorTicks[0].withoutPath = behavior.hideFirstTick; majorTicks[length - 1].withoutPath = behavior.hideLastTick } }, draw: function(canvas, borderOptions) { var that = this, drawGridLine = that._getGridLineDrawer(borderOptions || { visible: false }); that.createTicks(canvas); that._clearAxisGroups(); initTickCoords(that._majorTicks); initTickCoords(that._minorTicks); initTickCoords(that._boundaryTicks || []); that._drawAxis(); that._drawTitle(); drawTickMarks(that._majorTicks); drawTickMarks(that._minorTicks); drawTickMarks(that._boundaryTicks || []); drawGrids(that._majorTicks, drawGridLine); drawGrids(that._minorTicks, drawGridLine); callAction(that._majorTicks, "drawLabel"); that._outsideConstantLines = that._drawConstantLines("outside"); that._insideConstantLines = that._drawConstantLines("inside"); that._strips = that._drawStrips(); that._dateMarkers = that._drawDateMarkers() || []; that._axisGroup.append(that._axesContainerGroup); that._labelAxesGroup && that._axisStripLabelGroup.append(that._labelAxesGroup); that._gridContainerGroup && that._axisGridGroup.append(that._gridContainerGroup); that._stripsGroup && that._axisStripGroup.append(that._stripsGroup); if (that._constantLinesGroup) { that._axisConstantLineGroups.inside.append(that._constantLinesGroup); that._axisConstantLineGroups.outside1.append(that._constantLinesGroup); that._axisConstantLineGroups.outside2.append(that._constantLinesGroup) } that._measureTitle(); measureLabels(that._majorTicks); measureLabels(that._outsideConstantLines); measureLabels(that._insideConstantLines); measureLabels(that._strips); measureLabels(that._dateMarkers); that._adjustConstantLineLabels(that._insideConstantLines); that._adjustStripLabels(); var offset = that._constantLabelOffset = that._adjustConstantLineLabels(that._outsideConstantLines); if (!that._translator.getBusinessRange().stubData) { that._setLabelsPlacement(); offset = that._adjustLabels(offset) } offset = that._adjustDateMarkers(offset); that._adjustTitle(offset) }, _measureTitle: _noop, updateSize: function(canvas) { var that = this; that.updateCanvas(canvas); var canvasStartEnd = that._getCanvasStartEnd(); initTickCoords(that._majorTicks); initTickCoords(that._minorTicks); initTickCoords(that._boundaryTicks || []); that._updateAxisElementPosition(); updateTicksPosition(that._majorTicks); updateTicksPosition(that._minorTicks); updateTicksPosition(that._boundaryTicks || []); callAction(that._majorTicks, "updateLabelPosition"); that._outsideConstantLines.concat(that._insideConstantLines || []).forEach(function(item) { var coord = that._getConstantLinePos(item.options.value, canvasStartEnd.start, canvasStartEnd.end).value; item.label && item.label.attr(that._getConstantLineLabelsCoords(coord, item.labelOptions)); item.line && item.line.attr(that._getConstantLineGraphicAttributes(coord)) }); (that._strips || []).forEach(function(item) { var range = that._translator.getBusinessRange(), stripPos = that._getStripPos(item.options.startValue, item.options.endValue, canvasStartEnd.start, canvasStartEnd.end, range); item.label && item.label.attr(that._getStripLabelCoords(stripPos.from, stripPos.to, item.options.label)); item.rect && item.rect.attr(that._getStripGraphicAttributes(stripPos.from, stripPos.to)) }); that._updateTitleCoords(); that._checkTitleOverflow(); updateGridsPosition(that._majorTicks); updateGridsPosition(that._minorTicks) }, applyClipRects: function(elementsClipID, canvasClipID) { this._axisGroup.attr({ "clip-path": canvasClipID }); this._axisStripGroup.attr({ "clip-path": elementsClipID }) }, validate: function(isArgumentAxis) { var that = this, options = that._options, dataType = isArgumentAxis ? options.argumentType : options.valueType, parser = dataType ? parseUtils.getParser(dataType) : function(unit) { return unit }; that.parser = parser; options.dataType = dataType; if (void 0 !== options.min) { options.min = that._validateUnit(options.min, "E2106") } if (void 0 !== options.max) { options.max = that._validateUnit(options.max, "E2106") } if (void 0 !== that._minBound) { that._minBound = that._validateUnit(that._minBound) } if (void 0 !== that._maxBound) { that._maxBound = that._validateUnit(that._maxBound) } }, zoom: function(min, max, skipAdjusting) { var that = this, minOpt = that._options.min, maxOpt = that._options.max, stick = skipAdjusting, businessRange = new rangeModule.Range(this._storedBusinessRange), translatorRange = this._translator.getBusinessRange(), isDiscrete = that._options.type === constants.discrete; skipAdjusting = skipAdjusting || isDiscrete; min = that._validateUnit(min); max = that._validateUnit(max); if (!isDiscrete && _isDefined(min) && _isDefined(max) && min > max) { max = [min, min = max][0] } if (!skipAdjusting) { if (void 0 !== minOpt) { min = minOpt > min ? minOpt : min; max = minOpt > max ? minOpt : max } if (void 0 !== maxOpt) { max = maxOpt < max ? maxOpt : max; min = maxOpt < min ? maxOpt : min } } that._zoomArgs = { min: min, max: max, stick: stick }; businessRange.minVisible = min; businessRange.maxVisible = max; if (stick && !isDiscrete) { businessRange.min = translatorRange.min; businessRange.max = translatorRange.max; businessRange.stick = stick } this._updateBusinessRange(businessRange); return that._zoomArgs }, resetZoom: function() { this._zoomArgs = null }, getViewport: function() { var that = this, minOpt = that._options.min, maxOpt = that._options.max; if (that._zoomArgs) { return that._zoomArgs } if (_isDefined(minOpt) || _isDefined(maxOpt)) { return { min: minOpt, max: maxOpt } } }, getRangeData: function() { var rangeMin, rangeMax, rangeMinVisible, rangeMaxVisible, that = this, options = that._options, minMax = that._getMinMax(), min = minMax.min, max = minMax.max, zoomArgs = that._zoomArgs || {}, type = options.type; if (type === constants.logarithmic) { min = min <= 0 ? void 0 : min; max = max <= 0 ? void 0 : max } if (type !== constants.discrete) { rangeMin = min; rangeMax = max; if (_isDefined(min) && _isDefined(max)) { rangeMin = min < max ? min : max; rangeMax = max > min ? max : min } rangeMinVisible = _isDefined(zoomArgs.min) ? zoomArgs.min : rangeMin; rangeMaxVisible = _isDefined(zoomArgs.max) ? zoomArgs.max : rangeMax } else { rangeMinVisible = _isDefined(zoomArgs.min) ? zoomArgs.min : min; rangeMaxVisible = _isDefined(zoomArgs.max) ? zoomArgs.max : max } return { min: rangeMin, max: rangeMax, stick: that._getStick(), categories: options.categories, dataType: options.dataType, axisType: type, base: options.logarithmBase, invert: options.inverted, addSpiderCategory: that._getSpiderCategoryOption(), minVisible: rangeMinVisible, maxVisible: rangeMaxVisible } }, getFullTicks: function() { return this._tickManager.getFullTicks() }, measureLabels: function(withIndents) { var ticks, maxText, text, box, that = this, options = that._options, widthAxis = options.visible ? options.width : 0, indent = withIndents ? options.label.indentFromAxis + .5 * options.tick.length : 0; if (!options.label.visible || !that._axisElementsGroup) { return { height: widthAxis, width: widthAxis, x: 0, y: 0 } } ticks = that._tickManager.getTicks(); maxText = ticks.reduce(function(prevValue, tick, index) { var label = that._formatTickLabel(tick); if (prevValue[0].length < label.length) { return [label, tick] } else { return prevValue } }, [that._formatTickLabel(ticks[0]), ticks[0]]); text = that._renderer.text(maxText[0], 0, 0).css(that._textFontStyles).attr(that._textOptions).append(that._renderer.root); box = text.getBBox(); text.remove(); return { x: box.x, y: box.y, width: box.width + indent, height: box.height + indent } }, _setLabelsPlacement: function() { if (!this._options.label.visible) { return } var notRecastStep, step, that = this, labelOpt = that._options.label, displayMode = that._validateDisplayMode(labelOpt.displayMode), overlappingMode = that._validateOverlappingMode(labelOpt.overlappingBehavior.mode, displayMode), rotationAngle = labelOpt.overlappingBehavior.rotationAngle, staggeringSpacing = labelOpt.overlappingBehavior.staggeringSpacing, ignoreOverlapping = "none" === overlappingMode || "ignore" === overlappingMode, behavior = { rotationAngle: _isDefined(rotationAngle) ? rotationAngle : labelOpt.rotationAngle, staggeringSpacing: _isDefined(staggeringSpacing) ? staggeringSpacing : labelOpt.staggeringSpacing }, boxes = that._majorTicks.map(function(tick) { return tick.labelBBox }); step = that._getStep(boxes); switch (displayMode) { case "rotate": if (ignoreOverlapping) { notRecastStep = true; step = 1 } that._applyLabelMode(displayMode, step, boxes, labelOpt, notRecastStep); break; case "stagger": if (ignoreOverlapping) { step = 2 } that._applyLabelMode(displayMode, _max(step, 2), boxes, labelOpt); break; default: that._applyLabelOverlapping(boxes, overlappingMode, step, behavior) } }, _applyLabelOverlapping: function(boxes, mode, step, behavior) { var that = this, labelOpt = that._options.label, majorTicks = that._majorTicks; if ("none" === mode || "ignore" === mode) { return } var checkLabels = function(box, index, array) { if (0 === index) { return false } return constants.areLabelsOverlap(box, array[index - 1], labelOpt.minSpacing, labelOpt.alignment) }; if (step > 1 && boxes.some(checkLabels)) { that._applyLabelMode(mode, step, boxes, behavior) } if ("hide" === mode) { that._checkBoundedLabelsOverlapping(step, majorTicks, boxes) } }, _applyLabelMode: function(mode, step, boxes, behavior, notRecastStep) { var labelHeight, alignment, func, that = this, majorTicks = that._majorTicks, labelOpt = that._options.label, angle = behavior.rotationAngle; switch (mode) { case "rotate": if (!labelOpt.userAlignment) { alignment = angle < 0 ? RIGHT : LEFT; if (angle % 90 === 0) { alignment = CENTER } } step = notRecastStep ? step : that._getStep(boxes, angle); func = function(tick) { tick.label.rotate(angle); tick.labelRotationAngle = angle; alignment && (tick.labelAlignment = alignment) }; updateLabels(majorTicks, step, func); break; case "stagger": labelHeight = that._getMaxLabelHeight(that._options.position === TOP, boxes, behavior.staggeringSpacing); func = function(tick, index) { if (index / (step - 1) % 2 !== 0) { tick.labelOffset = labelHeight } }; updateLabels(majorTicks, step - 1, func); break; case "auto": case "_auto": if (2 === step) { that._applyLabelMode("stagger", step, boxes, behavior) } else { that._applyLabelMode("rotate", step, boxes, { rotationAngle: getOptimalAngle(boxes, labelOpt) }) } break; default: updateLabels(majorTicks, step) } }, getMarkerTrackers: _noop, _drawDateMarkers: _noop, _adjustDateMarkers: _noop, coordsIn: _noop, _getSkippedCategory: _noop, _initAxisPositions: _noop, _drawTitle: _noop, _updateTitleCoords: _noop, _adjustConstantLineLabels: _noop, _createTranslator: function() { return new Translator2DModule.Translator2D({}, {}, {}) }, _updateTranslator: function() { this._translator.update({}, {}, { isHorizontal: this._isHorizontal, interval: this._options.semiDiscreteInterval }) }, _adjustTitle: _noop, _checkTitleOverflow: _noop, getSpiderTicks: _noop, setSpiderTicks: _noop, _checkBoundedLabelsOverlapping: _noop, _getTickMarkPoints: _noop, _validateOverlappingMode: _noop, _getStep: _noop, _validateDisplayMode: _noop, shift: _noop } }, /*!***************************************!*\ !*** ./js/viz/axes/axes_constants.js ***! \***************************************/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__( /*! ../../core/utils/common */ 14).isFunction, _map = __webpack_require__( /*! ../core/utils */ 509).map, _format = __webpack_require__( /*! ../core/format */ 530); function getFormatObject(value, options, axisMinMax, point) { var formatObject = { value: value, valueText: _format(value, options) || "" }; if (axisMinMax) { formatObject.min = axisMinMax.min; formatObject.max = axisMinMax.max } if (point) { formatObject.point = point } return formatObject } module.exports = { logarithmic: "logarithmic", discrete: "discrete", numeric: "numeric", left: "left", right: "right", top: "top", bottom: "bottom", center: "center", canvasPositionPrefix: "canvas_position_", canvasPositionTop: "canvas_position_top", canvasPositionBottom: "canvas_position_bottom", canvasPositionLeft: "canvas_position_left", canvasPositionRight: "canvas_position_right", canvasPositionStart: "canvas_position_start", canvasPositionEnd: "canvas_position_end", horizontal: "horizontal", vertical: "vertical", convertTicksToValues: function(ticks) { return _map(ticks || [], function(item) { return item.value }) }, validateOverlappingMode: function(mode) { return "ignore" === mode || "none" === mode ? mode : "hide" }, formatLabel: function(value, options, axisMinMax, point) { var formatObject = getFormatObject(value, options, axisMinMax, point); return isFunction(options.customizeText) ? options.customizeText.call(formatObject, formatObject) : formatObject.valueText }, formatHint: function(value, options, axisMinMax) { var formatObject = getFormatObject(value, options, axisMinMax); return isFunction(options.customizeHint) ? options.customizeHint.call(formatObject, formatObject) : void 0 }, getTicksCountInRange: function(ticks, valueKey, range) { var i = 1; if (ticks.length > 1) { for (; i < ticks.length; i++) { if (Math.abs(ticks[i].coords[valueKey] - ticks[0].coords[valueKey]) >= range) { break } } } return i }, areLabelsOverlap: function(bBox1, bBox2, spacing, alignment) { var hasHorizontalOverlapping, hasVerticalOverlapping, horizontalInverted = bBox1.x > bBox2.x, verticalInverted = bBox1.y > bBox2.y, x1 = bBox1.x, x2 = bBox2.x, width1 = bBox1.width, width2 = bBox2.width; if ("center" === alignment) { x1 -= width1 / 2; x2 -= width2 / 2 } else { if ("right" === alignment) { x1 -= width1; x2 -= width2 } } hasHorizontalOverlapping = horizontalInverted ? x2 + width2 + spacing > x1 : x1 + width1 + spacing > x2; hasVerticalOverlapping = verticalInverted ? bBox2.y + bBox2.height > bBox1.y : bBox1.y + bBox1.height > bBox2.y; return hasHorizontalOverlapping && hasVerticalOverlapping } } }, /*!******************************************!*\ !*** ./js/viz/axes/base_tick_manager.js ***! \******************************************/ function(module, exports, __webpack_require__) { var TickManager, $ = __webpack_require__( /*! ../../core/renderer */ 9), coreTickManager = __webpack_require__( /*! ./numeric_tick_manager */ 568), dateTimeManager = __webpack_require__( /*! ./datetime_tick_manager */ 569), logarithmicMethods = __webpack_require__( /*! ./logarithmic_tick_manager */ 570), dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, formatHelper = __webpack_require__( /*! ../../format_helper */ 66), _isDefined = commonUtils.isDefined, _isNumber = commonUtils.isNumeric, _addInterval = dateUtils.addInterval, utils = __webpack_require__( /*! ../core/utils */ 509), _adjustValue = utils.adjustValue, _map = utils.map, _each = $.each, _inArray = inArray, _noop = commonUtils.noop, DEFAULT_GRID_SPACING_FACTOR = 30, DEFAULT_MINOR_GRID_SPACING_FACTOR = 15, DEFAULT_NUMBER_MULTIPLIERS = [1, 2, 3, 5], TICKS_COUNT_LIMIT = 2e3, MIN_ARRANGEMENT_TICKS_COUNT = 2; function getUniqueValues(array) { var currentValue, lastValue = array[0], result = [lastValue.obj], length = array.length, i = 1; for (i; i < length; i++) { currentValue = array[i]; if (lastValue.value !== currentValue.value) { result.push(currentValue.obj); lastValue = currentValue } } return result } function concatAndSort(array1, array2) { if (!array1.length && !array2.length) { return [] } var array = array1.concat(array2), values = [], length = array.length, hasNull = false, i = 0; for (i; i < length; i++) { if (null !== array[i]) { values.push({ obj: array[i], value: array[i].valueOf() }) } else { hasNull = true } } values.sort(function(x, y) { return x.value - y.value }); values = getUniqueValues(values); hasNull && values.push(null); return values } function convertTickIntervalToNumeric(interval) { if (!_isNumber(interval)) { var date = new Date; interval = _addInterval(date, interval) - date } return interval } function checkUserTickInterval(userTickInterval, calculatedTickInterval, forceUserTickInterval) { if (forceUserTickInterval && userTickInterval) { return userTickInterval } if (!userTickInterval) { return calculatedTickInterval } var tickInterval1 = convertTickIntervalToNumeric(userTickInterval), tickInterval2 = convertTickIntervalToNumeric(calculatedTickInterval); if (_isNumber(tickInterval1) && _isNumber(tickInterval2)) { if (tickInterval1 > tickInterval2) { return userTickInterval } } return calculatedTickInterval } exports.discrete = extend({}, coreTickManager.continuous, { _calculateMinorTicks: _noop, _findTickInterval: _noop, _createTicks: function() { return [] }, _generateBounds: _noop, _correctMin: _noop, _correctMax: _noop, _findBusinessDelta: _noop, _addBoundedTicks: _noop, getFullTicks: function() { return this._customTicks }, getMinorTicks: function() { return [] }, _findTickIntervalForCustomTicks: function() { return 1 } }); TickManager = exports.TickManager = function(types, data, options) { options = options || {}; this.update(types || {}, data || {}, options) }; TickManager.prototype = { constructor: TickManager, dispose: function() { this._ticks = null; this._minorTicks = null; this._boundaryTicks = null; this._options = null }, update: function(types, data, options) { this._updateOptions(options || {}); this._min = data.min; this._updateTypes(types || {}); this._updateData(data || {}) }, _updateMinMax: function(data) { var min = data.min || 0, max = data.max || 0, newMinMax = this._applyMinMaxMargins(min, max); this._min = this._originalMin = newMinMax.min; this._max = this._originalMax = newMinMax.max; this._updateBusinessDelta() }, _updateBusinessDelta: function() { this._businessDelta = this._findBusinessDelta && this._findBusinessDelta(this._min, this._max) }, _updateTypes: function(types) { var that = this, axisType = that._validateAxisType(types.axisType), dataType = that._validateDataType(types.dataType); that._resetMethods(); this._axisType = axisType; this._dataType = dataType; this._initMethods() }, _updateData: function(data) { data = extend({}, data); data.min = _isDefined(data.min) ? data.min : this._originalMin; data.max = _isDefined(data.max) ? data.max : this._originalMax; this._updateMinMax(data); this._customTicks = data.customTicks && data.customTicks.slice(); this._customMinorTicks = data.customMinorTicks; this._customBoundTicks = data.customBoundTicks; this._screenDelta = data.screenDelta || 0 }, _updateOptions: function(options) { var opt; this._options = opt = options; opt.gridSpacingFactor = opt.gridSpacingFactor || DEFAULT_GRID_SPACING_FACTOR; opt.minorGridSpacingFactor = opt.minorGridSpacingFactor || DEFAULT_MINOR_GRID_SPACING_FACTOR; opt.numberMultipliers = opt.numberMultipliers || DEFAULT_NUMBER_MULTIPLIERS }, getTickBounds: function() { return { minVisible: this._minBound, maxVisible: this._maxBound } }, getTicks: function() { var that = this, options = that._options; that._ticks = that._calculateMajorTicks(); that._checkLabelFormat(); that._generateBounds(); if (options.showMinorTicks) { that._minorTicks = that._calculateMinorTicks() } that._addBoundedTicks(); return that._ticks }, getMinorTicks: function() { return concatAndSort(this._minorTicks || [], []) }, getFullTicks: function() { var that = this, needCalculateMinorTicks = that._ticks && !that._minorTicks, minorTicks = needCalculateMinorTicks ? that._calculateMinorTicks() : that._minorTicks || []; return concatAndSort(that._ticks || [], minorTicks.concat(that.getBoundaryTicks())) }, getBoundaryTicks: function() { return this._boundaryTicks || [] }, getTickInterval: function() { return this._tickInterval }, getMinorTickInterval: function() { return this._minorTickInterval }, getOptions: function() { return this._options }, _calculateMajorTicks: function() { var ticks, that = this; if (that._options.showCalculatedTicks || !that._customTicks) { ticks = that._createTicks(that._options.showCalculatedTicks ? that._customTicks || [] : [], that._findTickInterval(), that._min, that._max) } else { ticks = that._customTicks.slice(); that._tickInterval = ticks.length > 1 ? that._findTickIntervalForCustomTicks() : 0 } return ticks }, _applyMinMaxMargins: function(min, max) { var newMin = min > max ? max : min, newMax = max > min ? max : min; this._minCorrectionEnabled = this._getCorrectionEnabled(min, "min"); this._maxCorrectionEnabled = this._getCorrectionEnabled(max, "max"); return { min: newMin, max: newMax } }, _checkBoundedTickInArray: function(value, array) { var arrayValues = _map(array || [], function(item) { return item.valueOf() }), minorTicksIndex = _inArray(value.valueOf(), arrayValues); if (minorTicksIndex !== -1) { array.splice(minorTicksIndex, 1) } }, _checkLabelFormat: function() { var options = this._options; if ("datetime" === this._dataType && !options.hasLabelFormat && this._ticks.length) { options.labelFormat = options.isMarkersVisible ? dateUtils.getDateFormatByTickInterval(this._tickInterval) : formatHelper.getDateFormatByTicks(this._ticks) } }, _generateBounds: function() { var that = this, interval = that._getBoundInterval(), stick = that._options.stick, minStickValue = that._options.minStickValue, maxStickValue = that._options.maxStickValue, minBound = that._minCorrectionEnabled && !stick ? that._getNextTickValue(that._min, interval, true) : that._originalMin, maxBound = that._maxCorrectionEnabled && !stick ? that._getNextTickValue(that._max, interval) : that._originalMax; that._minBound = minBound < minStickValue ? minStickValue : minBound; that._maxBound = maxBound > maxStickValue ? maxStickValue : maxBound }, _addBoundedTicks: function() { var that = this, tickValues = _map(that._ticks, function(tick) { return tick.valueOf() }), customBounds = that._customBoundTicks, min = that._originalMin, max = that._originalMax, addMinMax = that._options.addMinMax || {}; function processTick(tick) { that._boundaryTicks.push(tick); that._checkBoundedTickInArray(tick, that._minorTicks) } that._boundaryTicks = []; if (customBounds) { if (addMinMax.min && _isDefined(customBounds[0])) { processTick(customBounds[0]) } if (addMinMax.max && _isDefined(customBounds[1])) { processTick(customBounds[1]) } } else { if (addMinMax.min && _inArray(min.valueOf(), tickValues) === -1) { processTick(min) } if (addMinMax.max && _inArray(max.valueOf(), tickValues) === -1) { processTick(max) } } }, _getCorrectionEnabled: function(value, marginSelector) { var options = this._options || {}, hasPercentStick = options.percentStick && 1 === Math.abs(value), hasValueMargin = options[marginSelector + "ValueMargin"]; return !hasPercentStick && !hasValueMargin }, _validateAxisType: function(type) { var defaultType = "continuous", allowedTypes = { continuous: true, discrete: true, logarithmic: true }; return allowedTypes[type] ? type : defaultType }, _validateDataType: function(type) { var allowedTypes = { numeric: true, datetime: true, string: true }; if (!allowedTypes[type]) { type = _isDefined(this._min) ? this._getDataType(this._min) : "numeric" } return type }, _getDataType: function(value) { return commonUtils.isDate(value) ? "datetime" : "numeric" }, _getMethods: function() { var methods; if ("continuous" === this._axisType) { methods = "datetime" === this._dataType ? dateTimeManager.datetime : coreTickManager.continuous } else { switch (this._axisType) { case "discrete": methods = exports.discrete; break; case "logarithmic": methods = logarithmicMethods.logarithmic; break; default: methods = coreTickManager.continuous } } return methods }, _resetMethods: function() { var that = this, methods = that._getMethods(); _each(methods, function(name) { if (that[name]) { delete that[name] } }) }, _initMethods: function(methods) { var that = this; methods = methods || that._getMethods(); _each(methods, function(name, func) { that[name] = func }) }, _getDeltaCoef: function(screenDelta, businessDelta, gridSpacingFactor) { var count; gridSpacingFactor = gridSpacingFactor || this._options.gridSpacingFactor; screenDelta = screenDelta || this._screenDelta; businessDelta = businessDelta || this._businessDelta; count = screenDelta / gridSpacingFactor; count = count <= 1 ? MIN_ARRANGEMENT_TICKS_COUNT : count; return businessDelta / count }, _adjustNumericTickValue: function(value, interval, min) { return commonUtils.isExponential(value) ? _adjustValue(value) : utils.applyPrecisionByMinDelta(min, interval, value) }, _isTickIntervalCorrect: function(tickInterval, tickCountLimit, businessDelta) { var date; businessDelta = businessDelta || this._businessDelta; if (!_isNumber(tickInterval)) { date = new Date; tickInterval = _addInterval(date, tickInterval) - date; if (!tickInterval) { return false } } if (_isNumber(tickInterval)) { if (tickInterval > 0 && businessDelta / tickInterval > tickCountLimit) { if (this._options.incidentOccurred) { this._options.incidentOccurred("W2003") } } else { return true } } return false }, _correctValue: function(valueTypeSelector, tickInterval, correctionMethod) { var that = this, correctionEnabledSelector = "_" + valueTypeSelector + "CorrectionEnabled", spaceCorrectionSelector = valueTypeSelector + "SpaceCorrection", valueSelector = "_" + valueTypeSelector, minStickValue = that._options.minStickValue, maxStickValue = that._options.maxStickValue; if (that[correctionEnabledSelector]) { if (that._options[spaceCorrectionSelector]) { that[valueSelector] = that._getNextTickValue(that[valueSelector], tickInterval, "min" === valueTypeSelector) } correctionMethod.call(this, tickInterval) } if ("min" === valueTypeSelector) { that[valueSelector] = that[valueSelector] < minStickValue ? minStickValue : that[valueSelector] } if ("max" === valueTypeSelector) { that[valueSelector] = that[valueSelector] > maxStickValue ? maxStickValue : that[valueSelector] } }, _findTickInterval: function() { var tickInterval, that = this, options = that._options, calculatedTickInterval = that._getInterval(), userTickInterval = that._isTickIntervalValid(options.tickInterval) && that._isTickIntervalCorrect(options.tickInterval, TICKS_COUNT_LIMIT) && options.tickInterval; tickInterval = checkUserTickInterval(userTickInterval, calculatedTickInterval, options.forceUserTickInterval); if (that._isTickIntervalValid(tickInterval)) { that._correctValue("min", tickInterval, that._correctMin); that._correctValue("max", tickInterval, that._correctMax); that._updateBusinessDelta() } that._tickInterval = tickInterval; return tickInterval }, _findMinorTickInterval: function(firstTick, secondTick) { var that = this, ticks = that._ticks, intervals = that._options.stick ? ticks.length - 1 : ticks.length; if (intervals < 1) { intervals = 1 } that._getMinorInterval(that._screenDelta / intervals, that._findBusinessDelta(firstTick, secondTick, false)); return that._minorTickInterval }, _createMinorTicks: function(ticks, firstTick, secondTick) { var that = this, tickInterval = that._findMinorTickInterval(firstTick, secondTick), isTickIntervalNegative = false, isTickIntervalWithPow = false, needCorrectTick = false, startTick = that._getNextTickValue(firstTick, tickInterval, isTickIntervalNegative, isTickIntervalWithPow, needCorrectTick); if (that._isTickIntervalValid(tickInterval)) { ticks = that._createCountedTicks(ticks, tickInterval, startTick, secondTick, that._minorTickCount, isTickIntervalNegative, isTickIntervalWithPow, needCorrectTick) } return ticks }, _calculateMinorTicks: function() { var that = this, options = that._options, minorTicks = [], ticks = that._ticks, ticksLength = ticks.length, hasUnitBeginningTick = that._hasUnitBeginningTickCorrection(), i = hasUnitBeginningTick ? 1 : 0; if (options.showMinorCalculatedTicks || !that._customMinorTicks) { if (ticks.length) { minorTicks = that._getBoundedMinorTicks(minorTicks, that._minBound, ticks[0], true); if (hasUnitBeginningTick) { minorTicks = that._getUnitBeginningMinorTicks(minorTicks) } for (i; i < ticksLength - 1; i++) { minorTicks = that._createMinorTicks(minorTicks, ticks[i], ticks[i + 1]) } minorTicks = that._getBoundedMinorTicks(minorTicks, that._maxBound, ticks[ticksLength - 1]) } else { minorTicks = that._createMinorTicks(minorTicks, that._minBound, that._maxBound) } options.showMinorCalculatedTicks && (minorTicks = minorTicks.concat(that._customMinorTicks || [])) } else { minorTicks = that._customMinorTicks } return minorTicks }, _createCountedTicks: function(ticks, tickInterval, min, max, count, isTickIntervalWithPow, needMax) { var i, value = min; for (i = 0; i < count; i++) { if (!(false === needMax && value.valueOf() === max.valueOf())) { ticks.push(value) } value = this._getNextTickValue(value, tickInterval, false, isTickIntervalWithPow, false) } return ticks }, _createTicks: function(ticks, tickInterval, min, max, isTickIntervalNegative, isTickIntervalWithPow, withCorrection) { var leftBound, rightBound, boundedRule, that = this, value = min, newValue = min; if (that._isTickIntervalValid(tickInterval)) { boundedRule = min - max < 0; do { value = newValue; if (that._options.stick) { if (value >= that._originalMin && value <= that._originalMax) { ticks.push(value) } } else { ticks.push(value) } newValue = that._getNextTickValue(value, tickInterval, isTickIntervalNegative, isTickIntervalWithPow, withCorrection); if (value.valueOf() === newValue.valueOf()) { break } leftBound = newValue - min >= 0; rightBound = max - newValue >= 0 } while (boundedRule === leftBound && boundedRule === rightBound) } else { ticks.push(value) } return ticks }, _getBoundedMinorTicks: function(minorTicks, boundedTick, tick, isNegative) { var startTick, endTick, that = this, needCorrectTick = false, nextTick = that._tickInterval ? this._getNextTickValue(tick, that._tickInterval, isNegative, true, needCorrectTick) : boundedTick, tickInterval = that._findMinorTickInterval(tick, nextTick), isTickIntervalCorrect = that._isTickIntervalCorrect(tickInterval, TICKS_COUNT_LIMIT, that._findBusinessDelta(tick, boundedTick, false)), boundedTickValue = boundedTick.valueOf(); if (isTickIntervalCorrect && that._isTickIntervalValid(tickInterval) && that._minorTickCount > 0) { if (isNegative) { if (tick.valueOf() <= boundedTickValue) { return minorTicks } while (nextTick.valueOf() < boundedTickValue) { nextTick = this._getNextTickValue(nextTick, tickInterval, false, false, needCorrectTick) } startTick = nextTick; endTick = that._getNextTickValue(tick, tickInterval, true, false, false) } else { startTick = that._getNextTickValue(tick, tickInterval, false, false, false); endTick = boundedTick } minorTicks = that._createTicks(minorTicks, tickInterval, startTick, endTick, false, false, needCorrectTick) } return minorTicks }, getTypes: function() { return { axisType: this._axisType, dataType: this._dataType } }, getData: function() { return { min: this._min, max: this._max, customTicks: this._customTicks, customMinorTicks: this._customMinorTicks, screenDelta: this._screenDelta } } } }, /*!*********************************************!*\ !*** ./js/viz/axes/numeric_tick_manager.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), _isDefined = commonUtils.isDefined, _adjustValue = vizUtils.adjustValue, _math = Math, _abs = _math.abs, _ceil = _math.ceil, _floor = _math.floor, _noop = commonUtils.noop, MINOR_TICKS_COUNT_LIMIT = 200, DEFAULT_MINOR_NUMBER_MULTIPLIERS = [2, 4, 5, 8, 10]; exports.continuous = { _hasUnitBeginningTickCorrection: _noop, _correctMax: function(tickInterval) { this._max = this._adjustNumericTickValue(_ceil(this._max / tickInterval) * tickInterval, tickInterval, this._min) }, _correctMin: function(tickInterval) { this._min = this._adjustNumericTickValue(_floor(this._min / tickInterval) * tickInterval, tickInterval, this._min) }, _findBusinessDelta: function(min, max) { return _adjustValue(_abs(min - max)) }, _findTickIntervalForCustomTicks: function() { return _abs(this._customTicks[1] - this._customTicks[0]) }, _getBoundInterval: function() { var that = this, boundCoef = that._options.boundCoef; return _isDefined(boundCoef) && isFinite(boundCoef) ? that._tickInterval * _abs(boundCoef) : that._tickInterval / 2 }, _getInterval: function(deltaCoef, numberMultipliers) { var factor, newResult, i, interval = deltaCoef || this._getDeltaCoef(this._screenDelta, this._businessDelta, this._options.gridSpacingFactor), multipliers = numberMultipliers || this._options.numberMultipliers, result = 0, hasResult = false; if (interval > 1) { for (factor = 1; !hasResult; factor *= 10) { for (i = 0; i < multipliers.length; i++) { result = multipliers[i] * factor; if (interval <= result) { hasResult = true; break } } } } else { if (interval > 0) { result = 1; for (factor = .1; !hasResult; factor /= 10) { for (i = multipliers.length - 1; i >= 0; i--) { newResult = multipliers[i] * factor; if (interval > newResult) { hasResult = true; break } result = newResult } } } } return _adjustValue(result) }, _getDefaultMinorInterval: function(screenDelta, businessDelta) { var result, deltaCoef = this._getDeltaCoef(screenDelta, businessDelta, this._options.minorGridSpacingFactor), multipliers = DEFAULT_MINOR_NUMBER_MULTIPLIERS, i = multipliers.length - 1; for (i; i >= 0; i--) { result = businessDelta / multipliers[i]; if (deltaCoef <= result) { return _adjustValue(result) } } return 0 }, _getMinorInterval: function(screenDelta, businessDelta) { var interval, intervalsCount, count, that = this, options = that._options, minorTickInterval = options.minorTickInterval, minorTickCount = options.minorTickCount; if (isFinite(minorTickInterval) && that._isTickIntervalCorrect(minorTickInterval, MINOR_TICKS_COUNT_LIMIT, businessDelta)) { interval = minorTickInterval; count = interval < businessDelta ? _ceil(businessDelta / interval) - 1 : 0 } else { if (_isDefined(minorTickCount)) { intervalsCount = _isDefined(minorTickCount) ? minorTickCount + 1 : _floor(screenDelta / options.minorGridSpacingFactor); count = intervalsCount - 1; interval = count > 0 ? businessDelta / intervalsCount : 0 } else { interval = that._getDefaultMinorInterval(screenDelta, businessDelta); count = interval < businessDelta ? _floor(businessDelta / interval) - 1 : 0 } } that._minorTickInterval = interval; that._minorTickCount = count }, _getNextTickValue: function(value, tickInterval, isTickIntervalNegative) { tickInterval = _isDefined(isTickIntervalNegative) && isTickIntervalNegative ? -tickInterval : tickInterval; value += tickInterval; return this._adjustNumericTickValue(value, tickInterval, this._min) }, _isTickIntervalValid: function(tickInterval) { return _isDefined(tickInterval) && isFinite(tickInterval) && 0 !== tickInterval } } }, /*!**********************************************!*\ !*** ./js/viz/axes/datetime_tick_manager.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, tickManagerContinuous = __webpack_require__( /*! ./numeric_tick_manager */ 568).continuous, _isDefined = commonUtils.isDefined, _convertDateUnitToMilliseconds = dateUtils.convertDateUnitToMilliseconds, _correctDateWithUnitBeginning = dateUtils.correctDateWithUnitBeginning, _dateToMilliseconds = dateUtils.dateToMilliseconds, _convertMillisecondsToDateUnits = dateUtils.convertMillisecondsToDateUnits, _math = Math, _abs = _math.abs, _ceil = _math.ceil, _floor = _math.floor, MINOR_TICKS_COUNT_LIMIT = 50, DEFAULT_DATETIME_MULTIPLIERS = { millisecond: [1, 2, 5, 10, 25, 100, 250, 300, 500], second: [1, 2, 3, 5, 10, 15, 20, 30], minute: [1, 2, 3, 5, 10, 15, 20, 30], hour: [1, 2, 3, 4, 6, 8, 12], day: [1, 2, 3, 5, 7, 10, 14], month: [1, 2, 3, 6] }; function correctDate(date, tickInterval, correctionMethod) { var interval = _dateToMilliseconds(tickInterval), timezoneOffset = 60 * date.getTimezoneOffset() * 1e3; return new Date(Math[correctionMethod]((date - 0 - timezoneOffset) / interval) * interval + timezoneOffset) } exports.datetime = extend({}, tickManagerContinuous, { _correctMax: function(tickInterval) { this._max = correctDate(this._max, tickInterval, "ceil") }, _correctMin: function(tickInterval) { this._min = correctDate(this._min, tickInterval, "floor"); if (this._options.setTicksAtUnitBeginning) { this._min = _correctDateWithUnitBeginning(this._min, tickInterval) } }, _findTickIntervalForCustomTicks: function() { return _convertMillisecondsToDateUnits(_abs(this._customTicks[1] - this._customTicks[0])) }, _getBoundInterval: function() { var that = this, interval = that._tickInterval, intervalInMs = _dateToMilliseconds(interval), boundCoef = that._options.boundCoef, boundIntervalInMs = _isDefined(boundCoef) && isFinite(boundCoef) ? intervalInMs * _abs(boundCoef) : intervalInMs / 2; return _convertMillisecondsToDateUnits(boundIntervalInMs) }, _getInterval: function(deltaCoef) { var factor, i, key, specificMultipliers, yearsCount, interval = deltaCoef || this._getDeltaCoef(this._screenDelta, this._businessDelta, this._options.gridSpacingFactor), multipliers = this._options.numberMultipliers, result = {}; if (interval > 0 && interval < 1) { return { milliseconds: 1 } } if (0 === interval) { return 0 } for (key in DEFAULT_DATETIME_MULTIPLIERS) { if (DEFAULT_DATETIME_MULTIPLIERS.hasOwnProperty(key)) { specificMultipliers = DEFAULT_DATETIME_MULTIPLIERS[key]; for (i = 0; i < specificMultipliers.length; i++) { if (interval <= _convertDateUnitToMilliseconds(key, specificMultipliers[i])) { result[key + "s"] = specificMultipliers[i]; return result } } } } for (factor = 1;; factor *= 10) { for (i = 0; i < multipliers.length; i++) { yearsCount = factor * multipliers[i]; if (interval <= _convertDateUnitToMilliseconds("year", yearsCount)) { return { years: yearsCount } } } } }, _getMinorInterval: function(screenDelta, businessDelta) { var interval, intervalInMs, intervalsCount, count, that = this, options = that._options; if (_isDefined(options.minorTickInterval) && that._isTickIntervalCorrect(options.minorTickInterval, MINOR_TICKS_COUNT_LIMIT, businessDelta)) { interval = options.minorTickInterval; intervalInMs = _dateToMilliseconds(interval); count = intervalInMs < businessDelta ? _ceil(businessDelta / intervalInMs) - 1 : 0 } else { intervalsCount = _isDefined(options.minorTickCount) ? options.minorTickCount + 1 : _floor(screenDelta / options.minorGridSpacingFactor); count = intervalsCount - 1; interval = count > 0 ? _convertMillisecondsToDateUnits(businessDelta / intervalsCount) : 0 } that._minorTickInterval = interval; that._minorTickCount = count }, _getNextTickValue: function(value, tickInterval, isTickIntervalNegative, isTickIntervalWithPow, withCorrection) { var newValue = dateUtils.addInterval(value, tickInterval, isTickIntervalNegative); if (this._options.setTicksAtUnitBeginning && false !== withCorrection) { newValue = _correctDateWithUnitBeginning(newValue, tickInterval, true); this._correctDateWithUnitBeginningCalled = true } return newValue }, _getUnitBeginningMinorTicks: function(minorTicks) { var that = this, ticks = that._ticks, tickInterval = that._findMinorTickInterval(ticks[1], ticks[2]), isTickIntervalNegative = true, isTickIntervalWithPow = false, needCorrectTick = false, startTick = that._getNextTickValue(ticks[1], tickInterval, isTickIntervalNegative, isTickIntervalWithPow, needCorrectTick); if (that._isTickIntervalValid(tickInterval)) { minorTicks = that._createTicks(minorTicks, tickInterval, startTick, ticks[0], isTickIntervalNegative, isTickIntervalWithPow, needCorrectTick) } return minorTicks }, _hasUnitBeginningTickCorrection: function() { var ticks = this._ticks; if (ticks.length < 3) { return false } return ticks[1] - ticks[0] !== ticks[2] - ticks[1] && this._options.setTicksAtUnitBeginning && this._options.minorTickCount }, _isTickIntervalValid: function(tickInterval) { return _isDefined(tickInterval) && 0 !== _dateToMilliseconds(tickInterval) } }) }, /*!*************************************************!*\ !*** ./js/viz/axes/logarithmic_tick_manager.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var vizUtils = __webpack_require__( /*! ../core/utils */ 509), dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), _isDefined = commonUtils.isDefined, _addInterval = dateUtils.addInterval, _adjustValue = vizUtils.adjustValue, tickManagerContinuous = __webpack_require__( /*! ./numeric_tick_manager */ 568).continuous, _getLog = vizUtils.getLog, _raiseTo = vizUtils.raiseTo, _math = Math, _abs = _math.abs, _ceil = _math.ceil, _floor = _math.floor, _round = _math.round; exports.logarithmic = extend({}, tickManagerContinuous, { _correctMax: function() { var base = this._options.base; this._max = _adjustValue(_raiseTo(_ceil(_adjustValue(_getLog(this._max, base))), base)) }, _correctMin: function() { var base = this._options.base; this._min = _adjustValue(_raiseTo(_floor(_adjustValue(_getLog(this._min, base))), base)) }, _findBusinessDelta: function(min, max, isTickIntervalWithPow) { var delta; if (min <= 0 || max <= 0) { return 0 } if (false === isTickIntervalWithPow) { delta = tickManagerContinuous._findBusinessDelta(min, max) } else { delta = _round(_abs(_getLog(min, this._options.base) - _getLog(max, this._options.base))) } return delta }, _findTickIntervalForCustomTicks: function() { return _adjustValue(_getLog(this._customTicks[1] / this._customTicks[0], this._options.base)) }, _getInterval: function(deltaCoef) { var factor, i, interval = deltaCoef || this._getDeltaCoef(this._screenDelta, this._businessDelta, this._options.gridSpacingFactor), multipliers = this._options.numberMultipliers, result = 0, hasResult = false; if (0 !== interval) { for (factor = 1; !hasResult; factor *= 10) { for (i = 0; i < multipliers.length; i++) { result = multipliers[i] * factor; if (interval <= result) { hasResult = true; break } } } } return _adjustValue(result) }, _getMinorInterval: function(screenDelta, businessDelta) { var that = this, options = that._options, minorTickCount = options.minorTickCount, intervalsCount = _isDefined(minorTickCount) ? minorTickCount + 1 : _floor(screenDelta / options.minorGridSpacingFactor), count = intervalsCount - 1, interval = count > 0 ? businessDelta / intervalsCount : 0; that._minorTickInterval = interval; that._minorTickCount = count }, _getNextTickValue: function(value, tickInterval, isTickIntervalNegative, isTickIntervalWithPow) { var pow, nextTickValue, that = this; tickInterval = _isDefined(isTickIntervalNegative) && isTickIntervalNegative ? -tickInterval : tickInterval; if (false === isTickIntervalWithPow) { nextTickValue = value + tickInterval } else { pow = _addInterval(_getLog(value, that._options.base), tickInterval, that._min > that._max); nextTickValue = _adjustValue(_raiseTo(pow, that._options.base)) } return nextTickValue } }) }, /*!********************************************!*\ !*** ./js/viz/translators/translator2d.js ***! \********************************************/ function(module, exports, __webpack_require__) { var _Translator2d, $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, numericTranslator = __webpack_require__( /*! ./numeric_translator */ 572), categoryTranslator = __webpack_require__( /*! ./category_translator */ 573), intervalTranslator = __webpack_require__( /*! ./interval_translator */ 574), datetimeTranslator = __webpack_require__( /*! ./datetime_translator */ 575), logarithmicTranslator = __webpack_require__( /*! ./logarithmic_translator */ 576), vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), getLog = vizUtils.getLog, getPower = vizUtils.getPower, isDefined = commonUtils.isDefined, _abs = Math.abs, CANVAS_PROP = ["width", "height", "left", "top", "bottom", "right"], NUMBER_EQUALITY_CORRECTION = 1, DATETIME_EQUALITY_CORRECTION = 6e4, _noop = commonUtils.noop, addInterval = __webpack_require__( /*! ../../core/utils/date */ 63).addInterval; var validateCanvas = function(canvas) { $.each(CANVAS_PROP, function(_, prop) { canvas[prop] = parseInt(canvas[prop]) || 0 }); return canvas }; var makeCategoriesToPoints = function(categories) { var categoriesToPoints = {}; categories.forEach(function(item, i) { categoriesToPoints[item.valueOf()] = i }); return categoriesToPoints }; var validateBusinessRange = function(businessRange) { function validate(valueSelector, baseValueSelector) { if (!isDefined(businessRange[valueSelector]) && isDefined(businessRange[baseValueSelector])) { businessRange[valueSelector] = businessRange[baseValueSelector] } } validate("minVisible", "min"); validate("maxVisible", "max"); return businessRange }; function valuesIsDefinedAndEqual(val1, val2) { return isDefined(val1) && isDefined(val2) && val1.valueOf() === val2.valueOf() } function getCanvasBounds(range) { var newMin, newMax, min = range.min, max = range.max, minVisible = range.minVisible, maxVisible = range.maxVisible, base = range.base, isDateTime = commonUtils.isDate(max) || commonUtils.isDate(min), correction = isDateTime ? DATETIME_EQUALITY_CORRECTION : NUMBER_EQUALITY_CORRECTION, isLogarithmic = "logarithmic" === range.axisType; if (isLogarithmic) { maxVisible = getLog(maxVisible, base); minVisible = getLog(minVisible, base); min = getLog(min, base); max = getLog(max, base) } if (valuesIsDefinedAndEqual(min, max)) { newMin = min.valueOf() - correction; newMax = max.valueOf() + correction; if (isDateTime) { min = new Date(newMin); max = new Date(newMax) } else { min = 0 !== min || isLogarithmic ? newMin : 0; max = newMax } } if (valuesIsDefinedAndEqual(minVisible, maxVisible)) { newMin = minVisible.valueOf() - correction; newMax = maxVisible.valueOf() + correction; if (isDateTime) { minVisible = newMin < min.valueOf() ? min : new Date(newMin); maxVisible = newMax > max.valueOf() ? max : new Date(newMax) } else { if (0 !== minVisible || isLogarithmic) { minVisible = newMin < min ? min : newMin } maxVisible = newMax > max ? max : newMax } } return { base: base, rangeMin: min, rangeMax: max, rangeMinVisible: minVisible, rangeMaxVisible: maxVisible } } exports.Translator2D = _Translator2d = function(businessRange, canvas, options) { this.update(businessRange, canvas, options) }; _Translator2d.prototype = { constructor: _Translator2d, reinit: function() { var that = this, range = that._businessRange, categories = range.categories || [], script = {}, canvasOptions = that._prepareCanvasOptions(), visibleCategories = vizUtils.getCategoriesInfo(categories, range.minVisible, range.maxVisible).categories, categoriesLength = (visibleCategories || categories).length; switch (range.axisType) { case "logarithmic": script = logarithmicTranslator; break; case "semidiscrete": script = intervalTranslator; canvasOptions.ratioOfCanvasRange = canvasOptions.canvasLength / (addInterval(canvasOptions.rangeMaxVisible, that._options.interval) - canvasOptions.rangeMinVisible); break; case "discrete": script = categoryTranslator; that._categories = categories; canvasOptions.interval = that._getDiscreteInterval(range.addSpiderCategory ? categoriesLength + 1 : categoriesLength, canvasOptions); that._categoriesToPoints = makeCategoriesToPoints(categories, canvasOptions.invert); if (visibleCategories && categoriesLength) { canvasOptions.startPointIndex = that._categoriesToPoints[visibleCategories[0].valueOf()]; that.visibleCategories = visibleCategories } break; default: if ("datetime" === range.dataType) { script = datetimeTranslator } else { script = numericTranslator } } extend(that, script); that._conversionValue = that._options.conversionValue ? function(value) { return value } : function(value) { return Math.round(value) }; that._calculateSpecialValues() }, _getDiscreteInterval: function(categoriesLength, canvasOptions) { var correctedCategoriesCount = categoriesLength - (this._businessRange.stick ? 1 : 0); return correctedCategoriesCount > 0 ? canvasOptions.canvasLength / correctedCategoriesCount : canvasOptions.canvasLength }, _prepareCanvasOptions: function() { var length, that = this, businessRange = that._businessRange, canvasOptions = that._canvasOptions = getCanvasBounds(businessRange), canvas = that._canvas; if (that._options.isHorizontal) { canvasOptions.startPoint = canvas.left; length = canvas.width; canvasOptions.endPoint = canvas.width - canvas.right; canvasOptions.invert = businessRange.invert } else { canvasOptions.startPoint = canvas.top; length = canvas.height; canvasOptions.endPoint = canvas.height - canvas.bottom; canvasOptions.invert = !businessRange.invert } that.canvasLength = canvasOptions.canvasLength = canvasOptions.endPoint - canvasOptions.startPoint; canvasOptions.rangeDoubleError = Math.pow(10, getPower(canvasOptions.rangeMax - canvasOptions.rangeMin) - getPower(length) - 2); canvasOptions.ratioOfCanvasRange = canvasOptions.canvasLength / (canvasOptions.rangeMaxVisible - canvasOptions.rangeMinVisible); return canvasOptions }, updateCanvas: function(canvas) { this._canvas = validateCanvas(canvas); this.reinit() }, updateBusinessRange: function(businessRange) { this._businessRange = validateBusinessRange(businessRange); this.reinit() }, update: function(businessRange, canvas, options) { var that = this; that._options = extend(that._options || {}, options); that._canvas = validateCanvas(canvas); that.updateBusinessRange(businessRange) }, getBusinessRange: function() { return this._businessRange }, getCanvasVisibleArea: function() { return { min: this._canvasOptions.startPoint, max: this._canvasOptions.endPoint } }, _calculateSpecialValues: function() { var invert, canvas_position_default, canvas_position_center_middle, that = this, canvasOptions = that._canvasOptions, startPoint = canvasOptions.startPoint, endPoint = canvasOptions.endPoint, range = that._businessRange, minVisible = range.minVisible, maxVisible = range.maxVisible; if (minVisible <= 0 && maxVisible >= 0) { that.sc = {}; canvas_position_default = that.translate(0) } else { invert = range.invert ^ (minVisible <= 0 && maxVisible <= 0); if (that._options.isHorizontal) { canvas_position_default = invert ? endPoint : startPoint } else { canvas_position_default = invert ? startPoint : endPoint } } canvas_position_center_middle = startPoint + canvasOptions.canvasLength / 2; that.sc = { canvas_position_default: canvas_position_default, canvas_position_left: startPoint, canvas_position_top: startPoint, canvas_position_center: canvas_position_center_middle, canvas_position_middle: canvas_position_center_middle, canvas_position_right: endPoint, canvas_position_bottom: endPoint, canvas_position_start: canvasOptions.invert ? endPoint : startPoint, canvas_position_end: canvasOptions.invert ? startPoint : endPoint } }, translateSpecialCase: function(value) { return this.sc[value] }, _calculateProjection: function(distance) { var canvasOptions = this._canvasOptions; return canvasOptions.invert ? canvasOptions.endPoint - distance : canvasOptions.startPoint + distance }, _calculateUnProjection: function(distance) { var canvasOptions = this._canvasOptions; return canvasOptions.invert ? canvasOptions.rangeMaxVisible.valueOf() - distance : canvasOptions.rangeMinVisible.valueOf() + distance }, getVisibleCategories: function() { return this.visibleCategories }, getMinBarSize: function(minBarSize) { var visibleArea = this.getCanvasVisibleArea(), minValue = this.untranslate(visibleArea.min + minBarSize); return _abs(this.untranslate(visibleArea.min) - (!isDefined(minValue) ? this.untranslate(visibleArea.max) : minValue)) }, translate: _noop, untranslate: _noop, getInterval: _noop, zoom: _noop, getMinScale: _noop, getRange: function() { return [this.untranslate(this._canvasOptions.startPoint, -1), this.untranslate(this._canvasOptions.endPoint, 1)] }, isEmptyValueRange: function() { return this._businessRange.stubData }, getScreenRange: function() { return [this._canvasOptions.startPoint, this._canvasOptions.endPoint] }, add: function(value, diff, dir) { return this._add(value, diff, (this._businessRange.invert ? -1 : 1) * dir) } } }, /*!**************************************************!*\ !*** ./js/viz/translators/numeric_translator.js ***! \**************************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), isDefined = commonUtils.isDefined, round = Math.round; module.exports = { translate: function(bp) { var that = this, canvasOptions = that._canvasOptions, doubleError = canvasOptions.rangeDoubleError, specialValue = that.translateSpecialCase(bp); if (isDefined(specialValue)) { return specialValue } if (isNaN(bp) || bp.valueOf() + doubleError < canvasOptions.rangeMin || bp.valueOf() - doubleError > canvasOptions.rangeMax) { return null } return that._conversionValue(that._calculateProjection((bp - canvasOptions.rangeMinVisible) * canvasOptions.ratioOfCanvasRange)) }, untranslate: function(pos, _directionOffset, enableOutOfCanvas) { var canvasOptions = this._canvasOptions, startPoint = canvasOptions.startPoint; if (!enableOutOfCanvas && (pos < startPoint || pos > canvasOptions.endPoint) || !isDefined(canvasOptions.rangeMin) || !isDefined(canvasOptions.rangeMax)) { return null } return this._calculateUnProjection((pos - startPoint) / canvasOptions.ratioOfCanvasRange) }, getInterval: function() { return round(this._canvasOptions.ratioOfCanvasRange * (this._businessRange.interval || Math.abs(this._canvasOptions.rangeMax - this._canvasOptions.rangeMin))) }, _getValue: function(val) { return val }, zoom: function(translate, scale) { var that = this, canvasOptions = that._canvasOptions, startPoint = canvasOptions.startPoint, endPoint = canvasOptions.endPoint, newStart = (startPoint + translate) / scale, newEnd = (endPoint + translate) / scale, translatedRangeMinMax = [that.translate(that._getValue(canvasOptions.rangeMin)), that.translate(that._getValue(canvasOptions.rangeMax))], minPoint = Math.min(translatedRangeMinMax[0], translatedRangeMinMax[1]), maxPoint = Math.max(translatedRangeMinMax[0], translatedRangeMinMax[1]); if (minPoint > newStart) { newEnd -= newStart - minPoint; newStart = minPoint } if (maxPoint < newEnd) { newStart -= newEnd - maxPoint; newEnd = maxPoint } if (maxPoint - minPoint < newEnd - newStart) { newStart = minPoint; newEnd = maxPoint } translate = (endPoint - startPoint) * newStart / (newEnd - newStart) - startPoint; scale = (startPoint + translate) / newStart || 1; return { min: that.untranslate(newStart, void 0, true), max: that.untranslate(newEnd, void 0, true), translate: translate, scale: scale } }, getMinScale: function(zoom) { return zoom ? 1.1 : .9 }, getScale: function(val1, val2) { var canvasOptions = this._canvasOptions; val1 = isDefined(val1) ? val1 : canvasOptions.rangeMin; val2 = isDefined(val2) ? val2 : canvasOptions.rangeMax; return (canvasOptions.rangeMax - canvasOptions.rangeMin) / Math.abs(val1 - val2) }, isValid: function(value) { var co = this._canvasOptions; return null !== value && !isNaN(value) && value.valueOf() + co.rangeDoubleError >= co.rangeMin && value.valueOf() - co.rangeDoubleError <= co.rangeMax }, parse: function(value) { return Number(value) }, to: function(value) { return this._conversionValue(this._calculateProjection((value - this._canvasOptions.rangeMinVisible) * this._canvasOptions.ratioOfCanvasRange)) }, from: function(position) { return this._calculateUnProjection((position - this._canvasOptions.startPoint) / this._canvasOptions.ratioOfCanvasRange) }, _add: function(value, diff, coeff) { return value + diff * coeff }, isValueProlonged: false } }, /*!***************************************************!*\ !*** ./js/viz/translators/category_translator.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), isDefined = commonUtils.isDefined, round = Math.round; module.exports = { translate: function(category, directionOffset) { var stickDelta, that = this, canvasOptions = that._canvasOptions, categoryIndex = that._categoriesToPoints[category.valueOf()], specialValue = that.translateSpecialCase(category), startPointIndex = canvasOptions.startPointIndex || 0, stickInterval = that._businessRange.stick ? 0 : .5; if (isDefined(specialValue)) { return specialValue } if (!categoryIndex && 0 !== categoryIndex) { return null } directionOffset = directionOffset || 0; stickDelta = categoryIndex + stickInterval - startPointIndex + .5 * directionOffset; return round(that._calculateProjection(canvasOptions.interval * stickDelta)) }, untranslate: function(pos, directionOffset, enableOutOfCanvas) { var that = this, canvasOptions = that._canvasOptions, startPoint = canvasOptions.startPoint, categories = that.visibleCategories || that._categories, categoriesLength = categories.length, result = 0, stickInterval = that._businessRange.stick ? .5 : 0; if (!enableOutOfCanvas && (pos < startPoint || pos > canvasOptions.endPoint)) { return null } directionOffset = directionOffset || 0; result = round((pos - startPoint) / canvasOptions.interval + stickInterval - .5 - .5 * directionOffset); if (categoriesLength === result) { result-- } if (result === -1) { result = 0 } if (canvasOptions.invert) { result = categoriesLength - result - 1 } return categories[result] }, getInterval: function() { return this._canvasOptions.interval }, zoom: function(translate, scale) { var endCategoryIndex, newVisibleCategories, newInterval, that = this, canvasOptions = that._canvasOptions, stick = that._businessRange.stick, invert = canvasOptions.invert, interval = canvasOptions.interval * scale, translateCategories = translate / interval, startCategoryIndex = parseInt((canvasOptions.startPointIndex || 0) + translateCategories + .5), categoriesLength = parseInt(canvasOptions.canvasLength / interval + (stick ? 1 : 0)) || 1, categories = that._categories; if (invert) { startCategoryIndex = parseInt((canvasOptions.startPointIndex || 0) + (that.visibleCategories || []).length - translateCategories + .5) - categoriesLength } if (startCategoryIndex < 0) { startCategoryIndex = 0 } endCategoryIndex = startCategoryIndex + categoriesLength; if (endCategoryIndex > categories.length) { endCategoryIndex = categories.length; startCategoryIndex = endCategoryIndex - categoriesLength; if (startCategoryIndex < 0) { startCategoryIndex = 0 } } newVisibleCategories = categories.slice(parseInt(startCategoryIndex), parseInt(endCategoryIndex)); newInterval = that._getDiscreteInterval(newVisibleCategories.length, canvasOptions); scale = newInterval / canvasOptions.interval; translate = that.translate(!invert ? newVisibleCategories[0] : newVisibleCategories[newVisibleCategories.length - 1]) * scale - (canvasOptions.startPoint + (stick ? 0 : newInterval / 2)); return { min: newVisibleCategories[0], max: newVisibleCategories[newVisibleCategories.length - 1], translate: translate, scale: scale } }, getMinScale: function(zoom) { var that = this, canvasOptions = that._canvasOptions, categoriesLength = (that.visibleCategories || that._categories).length; categoriesLength += (parseInt(.1 * categoriesLength) || 1) * (zoom ? -2 : 2); return canvasOptions.canvasLength / (Math.max(categoriesLength, 1) * canvasOptions.interval) }, getScale: function(min, max) { var that = this, canvasOptions = that._canvasOptions, visibleArea = that.getCanvasVisibleArea(), stickOffset = !that._businessRange.stick && 1, minPoint = isDefined(min) ? that.translate(min, -stickOffset) : null, maxPoint = isDefined(max) ? that.translate(max, +stickOffset) : null; if (null === minPoint) { minPoint = canvasOptions.invert ? visibleArea.max : visibleArea.min } if (null === maxPoint) { maxPoint = canvasOptions.invert ? visibleArea.min : visibleArea.max } return that.canvasLength / Math.abs(maxPoint - minPoint) }, isValid: function(value) { return isDefined(value) ? this._categoriesToPoints[value.valueOf()] >= 0 : false }, parse: function(value) { return value }, to: function(value, direction) { var canvasOptions = this._canvasOptions, businessRange = this._businessRange, categoryIndex = this._categoriesToPoints[value.valueOf()], startPointIndex = canvasOptions.startPointIndex || 0, stickInterval = businessRange.stick ? 0 : .5, stickDelta = categoryIndex + stickInterval - startPointIndex + (businessRange.invert ? -1 : 1) * direction * .5; return round(this._calculateProjection(canvasOptions.interval * stickDelta)) }, from: function(position, direction) { var canvasOptions = this._canvasOptions, businessRange = this._businessRange, startPoint = canvasOptions.startPoint, categories = this._categories, categoriesLength = categories.length, stickInterval = businessRange.stick ? .5 : 0, result = round((position - startPoint) / canvasOptions.interval + stickInterval - .5 - .5 * direction); if (categoriesLength === result) { result-- } if (result === -1) { result = 0 } if (canvasOptions.invert) { result = categoriesLength - result - 1 } return categories[result] }, _add: function() { return NaN }, isValueProlonged: true } }, /*!***************************************************!*\ !*** ./js/viz/translators/interval_translator.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var adjustValue = __webpack_require__( /*! ../core/utils */ 509).adjustValue, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), isNumber = commonUtils.isNumeric, isDefined = commonUtils.isDefined, dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), addInterval = dateUtils.addInterval, dateToMilliseconds = dateUtils.dateToMilliseconds, floor = Math.floor; module.exports = { _intervalize: function(value, interval) { if (!isDefined(value)) { return } if ("datetime" === this._businessRange.dataType) { if (isNumber(value)) { value = new Date(value) } else { value = new Date(value.getTime()) } value = dateUtils.correctDateWithUnitBeginning(value, interval) } else { value = adjustValue(floor(value / interval) * interval) } return value }, translate: function(bp, direction, interval) { var that = this, specialValue = that.translateSpecialCase(bp); if (isDefined(specialValue)) { return specialValue } interval = interval || that._options.interval; if (!that.isValid(bp, interval)) { return null } return that.to(bp, direction, interval) }, untranslate: function(pos, direction, enableOutOfCanvas) { var canvasOptions = this._canvasOptions, startPoint = canvasOptions.startPoint; if (!enableOutOfCanvas && (pos < startPoint || pos > canvasOptions.endPoint) || !isDefined(canvasOptions.rangeMin) || !isDefined(canvasOptions.rangeMax)) { return null } return this.from(pos, direction) }, getInterval: function() { return Math.round(this._canvasOptions.ratioOfCanvasRange * (this._businessRange.interval || Math.abs(this._canvasOptions.rangeMax - this._canvasOptions.rangeMin))) }, _getValue: function() {}, zoom: function() {}, getMinScale: function() {}, getScale: function() {}, isValid: function(value, interval) { var that = this, co = that._canvasOptions, rangeMin = co.rangeMin, rangeMax = co.rangeMax; interval = interval || that._options.interval; if (null === value || isNaN(value)) { return false } value = "datetime" === that._businessRange.dataType && isNumber(value) ? new Date(value) : value; if (interval !== that._options.interval) { rangeMin = that._intervalize(rangeMin, interval); rangeMax = that._intervalize(rangeMax, interval) } if (value.valueOf() < rangeMin || value.valueOf() >= addInterval(rangeMax, interval)) { return false } return true }, parse: function(value) { return "datetime" === this._businessRange.dataType ? isNumber(value) ? new Date(value) : value : Number(value) }, to: function(bp, direction, interval) { var that = this; interval = interval || that._options.interval; var v1 = that._intervalize(bp, interval), v2 = addInterval(v1, interval), res = that._to(v1), p2 = that._to(v2); if (!direction) { res = floor((res + p2) / 2) } else { if (direction > 0) { res = p2 } } return res }, _to: function(value) { var co = this._canvasOptions, rMin = co.rangeMinVisible, rMax = co.rangeMaxVisible, offset = value - rMin; if (value < rMin) { offset = 0 } else { if (value > rMax) { offset = addInterval(rMax, this._options.interval) - rMin } } return this._conversionValue(this._calculateProjection(offset * this._canvasOptions.ratioOfCanvasRange)) }, from: function(position, direction) { var value, that = this, origInterval = that._options.interval, interval = origInterval, co = that._canvasOptions, rMin = co.rangeMinVisible, rMax = co.rangeMaxVisible; if ("datetime" === that._businessRange.dataType) { interval = dateToMilliseconds(origInterval) } value = that._calculateUnProjection((position - that._canvasOptions.startPoint) / that._canvasOptions.ratioOfCanvasRange); value = that._intervalize(addInterval(value, interval / 2, direction > 0), origInterval); if (value < rMin) { value = rMin } else { if (value > rMax) { value = rMax } } return value }, _add: function() { return NaN }, isValueProlonged: true } }, /*!***************************************************!*\ !*** ./js/viz/translators/datetime_translator.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var numericTranslator = __webpack_require__( /*! ./numeric_translator */ 572); module.exports = { translate: numericTranslator.translate, untranslate: function() { var result = numericTranslator.untranslate.apply(this, arguments); return null === result ? result : new Date(result) }, _getValue: numericTranslator._getValue, getInterval: numericTranslator.getInterval, zoom: numericTranslator.zoom, getMinScale: numericTranslator.getMinScale, getScale: numericTranslator.getScale, isValid: function(value) { return numericTranslator.isValid.call(this, new Date(value)) }, parse: function(value) { return new Date(value) }, to: numericTranslator.to, from: function(position) { return new Date(numericTranslator.from.call(this, position)) }, _add: __webpack_require__( /*! ../../core/utils/date */ 63).addDateInterval, isValueProlonged: numericTranslator.isValueProlonged } }, /*!******************************************************!*\ !*** ./js/viz/translators/logarithmic_translator.js ***! \******************************************************/ function(module, exports, __webpack_require__) { var numericTranslator = __webpack_require__( /*! ./numeric_translator */ 572), vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), raiseTo = vizUtils.raiseTo, getLog = vizUtils.getLog; module.exports = { translate: function(bp) { var that = this, specialValue = that.translateSpecialCase(bp); if (commonUtils.isDefined(specialValue)) { return specialValue } return numericTranslator.translate.call(that, getLog(bp, that._businessRange.base)) }, untranslate: function() { var result = numericTranslator.untranslate.apply(this, arguments); return null === result ? result : raiseTo(result, this._businessRange.base) }, getInterval: numericTranslator.getInterval, _getValue: function(value) { return Math.pow(this._canvasOptions.base, value) }, zoom: numericTranslator.zoom, getMinScale: numericTranslator.getMinScale, getScale: function(val1, val2) { var base = this._businessRange.base; val1 = commonUtils.isDefined(val1) ? getLog(val1, base) : void 0; val2 = commonUtils.isDefined(val2) ? getLog(val2, base) : void 0; return numericTranslator.getScale.call(this, val1, val2) }, isValid: function(value) { return numericTranslator.isValid.call(this, getLog(value, this._businessRange.base)) }, parse: numericTranslator.parse, to: function(value) { return numericTranslator.to.call(this, getLog(value, this._businessRange.base)) }, from: function(position) { return raiseTo(numericTranslator.from.call(this, position), this._businessRange.base) }, _add: function(value, diff, dir) { var b = this._businessRange.base; return raiseTo(numericTranslator._add(getLog(value, b), diff, dir), b) }, isValueProlonged: numericTranslator.isValueProlonged } }, /*!*****************************!*\ !*** ./js/viz/axes/tick.js ***! \*****************************/ function(module, exports, __webpack_require__) { var isDefined = __webpack_require__( /*! ../../core/utils/common */ 14).isDefined, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, constants = __webpack_require__( /*! ./axes_constants */ 566); function getPathStyle(options) { return { stroke: options.color, "stroke-width": options.width, "stroke-opacity": options.opacity } } function createTick(axis, renderer, tickOptions, gridOptions, skippedCategory, skipLabels, offset) { var tickOffset = offset || axis._tickOffset, lineGroup = axis._axisLineGroup, elementsGroup = axis._axisElementsGroup, tickStyle = getPathStyle(tickOptions), gridStyle = getPathStyle(gridOptions), emptyStrRegExp = /^\s+$/, axisOptions = axis.getOptions(), labelOptions = axisOptions.label, labelStyle = axis._textOptions; function getLabelFontStyle(tick) { var fontStyle = axis._textFontStyles, customizeColor = labelOptions.customizeColor; if (customizeColor && customizeColor.call) { fontStyle = extend({}, axis._textFontStyles, { fill: customizeColor.call(tick, tick) }) } return fontStyle } return function(value) { var tick = { value: value, initCoords: function() { this.coords = axis._getTranslatedValue(value, tickOffset) }, drawMark: function() { if (!tickOptions.visible || skippedCategory === value) { return } if (this.withoutPath) { return } this.mark = axis._createPathElement([], tickStyle).append(lineGroup); this.updateTickPosition() }, updateTickPosition: function() { if (!this.mark) { return } this.mark.attr({ points: axis._getTickMarkPoints(tick, tickOptions.length) }); this.coords.angle && axis._rotateTick(this.mark, this.coords) }, drawLabel: function() { if (!labelOptions.visible || skipLabels) { return } if (this.withoutLabel) { return } var labelHint, axisBounds = { min: axis._minBound, max: axis._maxBound }, text = constants.formatLabel(value, labelOptions, axisBounds); if (isDefined(text) && "" !== text && !emptyStrRegExp.test(text)) { this.label = renderer.text(text).css(getLabelFontStyle(this)).attr(labelStyle).data("chart-data-argument", this.value).append(elementsGroup); this.updateLabelPosition(); labelHint = constants.formatHint(this.value, labelOptions, axisBounds); if (isDefined(labelHint) && "" !== labelHint) { this.label.setTitle(labelHint) } } }, updateLabelPosition: function() { if (!this.label) { return } var coords = axis._getTranslatedValue(value); this.labelCoords = coords; this.label.attr({ x: coords.x, y: coords.y }) }, drawGrid: function(drawLine) { if (gridOptions.visible && skippedCategory !== this.value) { this.grid = drawLine(this, gridStyle); this.grid && this.grid.append(axis._axisGridGroup) } }, updateGridPosition: function(updateLine) { this.grid && this.grid.attr(axis._getGridPoints(tick.coords)) } }; return tick } } exports.tick = createTick }, /*!********************************!*\ !*** ./js/viz/axes/xy_axes.js ***! \********************************/ function(module, exports, __webpack_require__) { var formatHelper = __webpack_require__( /*! ../../format_helper */ 66), dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, getNextDateUnit = dateUtils.getNextDateUnit, correctDateWithUnitBeginning = dateUtils.correctDateWithUnitBeginning, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), vizUtils = __webpack_require__( /*! ../core/utils */ 509), _isDefined = commonUtils.isDefined, constants = __webpack_require__( /*! ./axes_constants */ 566), _extend = extend, _math = Math, _max = _math.max, TOP = constants.top, BOTTOM = constants.bottom, LEFT = constants.left, RIGHT = constants.right, CENTER = constants.center; function prepareDatesDifferences(datesDifferences, tickInterval) { var dateUnitInterval, i; if ("week" === tickInterval) { tickInterval = "day" } if ("quarter" === tickInterval) { tickInterval = "month" } if (datesDifferences[tickInterval]) { for (i = 0; i < dateUtils.dateUnitIntervals.length; i++) { dateUnitInterval = dateUtils.dateUnitIntervals[i]; if (datesDifferences[dateUnitInterval]) { datesDifferences[dateUnitInterval] = false; datesDifferences.count-- } if (dateUnitInterval === tickInterval) { break } } } } function getMarkerDates(min, max, markerInterval) { var dates, origMin = min; min = correctDateWithUnitBeginning(min, markerInterval); max = correctDateWithUnitBeginning(max, markerInterval); dates = dateUtils.getSequenceByInterval(min, max, markerInterval); if (dates.length && origMin > dates[0]) { dates = dates.slice(1) } return dates } function getStripHorizontalAlignmentPosition(alignment) { var position = "start"; if ("center" === alignment) { position = "center" } if ("right" === alignment) { position = "end" } return position } function getStripVerticalAlignmentPosition(alignment) { var position = "start"; if ("center" === alignment) { position = "center" } if ("bottom" === alignment) { position = "end" } return position } function getMarkerInterval(tickInterval) { var markerInterval = getNextDateUnit(tickInterval); if ("quarter" === markerInterval) { markerInterval = getNextDateUnit(markerInterval) } return markerInterval } function getMarkerFormat(curDate, prevDate, tickInterval, markerInterval) { var format = markerInterval, datesDifferences = prevDate && dateUtils.getDatesDifferences(prevDate, curDate); if (prevDate && "year" !== tickInterval) { prepareDatesDifferences(datesDifferences, tickInterval); format = formatHelper.getDateFormatByDifferences(datesDifferences) } return format } function getMaxSide(act, boxes) { return boxes.reduce(function(prevValue, box) { return _max(prevValue, act(box)) }, 0) } function getDistanceByAngle(bBox, rotationAngle) { rotationAngle = _math.abs(rotationAngle); rotationAngle = rotationAngle % 180 >= 90 ? 90 - rotationAngle % 90 : rotationAngle % 90; var a = rotationAngle * (_math.PI / 180); if (a >= _math.atan(bBox.height / bBox.width)) { return bBox.height / _math.abs(_math.sin(a)) } else { return bBox.width } } function getMaxConstantLinePadding(constantLines) { return constantLines.reduce(function(padding, options) { return _max(padding, options.paddingTopBottom) }, 0) } function getConstantLineLabelMarginForVerticalAlignment(constantLines, alignment, labelHeight) { return constantLines.some(function(options) { return options.label.verticalAlignment === alignment }) && labelHeight || 0 } function getLeftMargin(bBox) { return _math.abs(bBox.x) || 0 } function getRightMargin(bBox) { return _math.abs(bBox.width - _math.abs(bBox.x)) || 0 } module.exports = { linear: { _getStep: function(boxes, rotationAngle) { var spacing = this._options.label.minSpacing, func = this._isHorizontal ? function(box) { return box.width + spacing } : function(box) { return box.height }, maxLabelLength = getMaxSide(func, boxes); if (rotationAngle) { maxLabelLength = getDistanceByAngle({ width: maxLabelLength, height: this._getMaxLabelHeight(false, boxes, 0) }, rotationAngle) } return constants.getTicksCountInRange(this._majorTicks, this._isHorizontal ? "x" : "y", maxLabelLength) }, _getMaxLabelHeight: function(isNegative, boxes, spacing) { return (isNegative ? -1 : 1) * (getMaxSide(function(box) { return box.height }, boxes) + spacing) }, _validateOverlappingMode: function(mode, displayMode) { if (this._isHorizontal && ("rotate" === displayMode || "stagger" === displayMode) || !this._isHorizontal) { return constants.validateOverlappingMode(mode) } return mode }, _validateDisplayMode: function(mode) { return this._isHorizontal ? mode : "standard" }, getMarkerTrackers: function() { return this._markerTrackers }, _getSharpParam: function(opposite) { return this._isHorizontal ^ opposite ? "h" : "v" }, _createAxisElement: function() { return this._renderer.path([], "line") }, _updateAxisElementPosition: function() { if (!this._axisElement) { return } var axisCoord = this._axisPosition, canvas = this._getCanvasStartEnd(); this._axisElement.attr({ points: this._isHorizontal ? [canvas.start, axisCoord, canvas.end, axisCoord] : [axisCoord, canvas.start, axisCoord, canvas.end] }) }, _getTranslatedCoord: function(value, offset) { return this._translator.translate(value, offset) }, _getCanvasStartEnd: function() { var isHorizontal = this._isHorizontal, canvas = this._canvas, invert = this._translator.getBusinessRange().invert, coords = isHorizontal ? [canvas.left, canvas.width - canvas.right] : [canvas.height - canvas.bottom, canvas.top]; invert && coords.reverse(); return { start: coords[0], end: coords[1] } }, _getScreenDelta: function() { var canvas = this._getCanvasStartEnd(); return _math.abs(canvas.start - canvas.end) }, _initAxisPositions: function() { var that = this, position = that._options.position; that._axisPosition = that._orthogonalPositions["top" === position || "left" === position ? "start" : "end"] }, _getTickMarkPoints: function(tick, length) { var coords = tick.coords, isHorizontal = this._isHorizontal, tickCorrection = { left: -1, top: -1, right: 0, bottom: 0, center: -.5 }[this._options.tickOrientation || "center"]; return [coords.x + (isHorizontal ? 0 : tickCorrection * length), coords.y + (isHorizontal ? tickCorrection * length : 0), coords.x + (isHorizontal ? 0 : tickCorrection * length + length), coords.y + (isHorizontal ? tickCorrection * length + length : 0)] }, _getTitleCoords: function() { var that = this, x = that._axisPosition, y = that._axisPosition, canvas = that._getCanvasStartEnd(), center = canvas.start + (canvas.end - canvas.start) / 2; if (that._isHorizontal) { x = center } else { y = center } return { x: x, y: y } }, _drawTitleText: function(group, coords) { var options = this._options, titleOptions = options.title, attrs = { opacity: titleOptions.opacity, align: "center" }; if (!titleOptions.text || !group) { return } coords = coords || this._getTitleCoords(); if (!this._isHorizontal) { attrs.rotate = options.position === LEFT ? 270 : 90 } var text = this._renderer.text(titleOptions.text, coords.x, coords.y).css(vizUtils.patchFontOptions(titleOptions.font)).attr(attrs).append(group); return text }, _updateTitleCoords: function() { this._title && this._title.element.attr(this._getTitleCoords()) }, _drawTitle: function() { var title = this._drawTitleText(this._axisTitleGroup); if (title) { this._title = { element: title } } }, _measureTitle: function() { if (this._title) { this._title.bBox = this._title.element.getBBox() } }, _drawDateMarker: function(date, options) { var text, pathElement, that = this, markerOptions = that._options.marker, invert = that._translator.getBusinessRange().invert, textIndent = markerOptions.width + markerOptions.textLeftIndent; if (null === options.x) { return } if (!options.withoutStick) { pathElement = that._renderer.path([options.x, options.y, options.x, options.y + markerOptions.separatorHeight], "line").attr({ "stroke-width": markerOptions.width, stroke: markerOptions.color, "stroke-opacity": markerOptions.opacity, sharp: "h" }).append(that._axisElementsGroup) } text = String(constants.formatLabel(date, options.labelFormat)); return { date: date, x: options.x, y: options.y, cropped: options.withoutStick, label: that._renderer.text(text, options.x, options.y).css(vizUtils.patchFontOptions(markerOptions.label.font)).append(that._axisElementsGroup), line: pathElement, getEnd: function() { return this.x + (invert ? -1 : 1) * (textIndent + this.labelBBox.width) }, setTitle: function() { this.title = text }, hideLabel: function() { this.label.dispose(); this.label = null; this.title = text }, hide: function() { if (pathElement) { pathElement.dispose(); pathElement = null } this.label.dispose(); this.label = null; this.hidden = true } } }, _drawDateMarkers: function() { var tickInterval, markerInterval, markerDates, markersAreaTop, dateMarker, that = this, options = that._options, translator = that._translator, minBound = that._minBound, dateMarkers = []; function draw(markerDate, format, withoutStick) { return that._drawDateMarker(markerDate, { x: translator.translate(markerDate), y: markersAreaTop, labelFormat: that._getLabelFormatOptions(format), withoutStick: withoutStick }) } if (!options.marker.visible || "datetime" !== options.argumentType || "discrete" === options.type || that._majorTicks.length <= 1) { return [] } markersAreaTop = that._axisPosition + options.marker.topIndent; tickInterval = dateUtils.getDateUnitInterval(this._tickManager.getTickInterval()); markerInterval = getMarkerInterval(tickInterval); markerDates = getMarkerDates(minBound, that._maxBound, markerInterval); if (markerDates.length > 1 || 1 === markerDates.length && minBound < markerDates[0]) { dateMarkers = markerDates.reduce(function(markers, curDate, i, dates) { var marker = draw(curDate, getMarkerFormat(curDate, dates[i - 1] || minBound < curDate && minBound, tickInterval, markerInterval)); marker && markers.push(marker); return markers }, []); if (minBound < markerDates[0]) { dateMarker = draw(minBound, getMarkerFormat(minBound, markerDates[0], tickInterval, markerInterval), true); dateMarker && dateMarkers.unshift(dateMarker) } } return dateMarkers }, _adjustDateMarkers: function(offset) { offset = offset || 0; var that = this, markerOptions = this._options.marker, textIndent = markerOptions.width + markerOptions.textLeftIndent, invert = this._translator.getBusinessRange().invert, canvas = that._getCanvasStartEnd(), dateMarkers = this._dateMarkers; if (!dateMarkers.length) { return offset } if (dateMarkers[0].cropped) { if (!this._checkMarkersPosition(invert, dateMarkers[1], dateMarkers[0])) { dateMarkers[0].hideLabel() } } var prevDateMarker; dateMarkers.forEach(function(marker, i, markers) { if (marker.cropped) { return } if (invert ? marker.getEnd() < canvas.end : marker.getEnd() > canvas.end) { marker.hideLabel() } else { if (that._checkMarkersPosition(invert, marker, prevDateMarker)) { prevDateMarker = marker } else { marker.hide() } } }); this._dateMarkers.forEach(function(marker) { if (marker.label) { var labelBBox = marker.labelBBox, dy = marker.y + markerOptions.textTopIndent - labelBBox.y; marker.label.attr({ translateX: invert ? marker.x - textIndent - labelBBox.x - labelBBox.width : marker.x + textIndent - labelBBox.x, translateY: dy + offset }) } if (marker.line) { marker.line.attr({ translateY: offset }) } }); that._initializeMarkersTrackers(offset); return offset + markerOptions.topIndent + markerOptions.separatorHeight }, _checkMarkersPosition: function(invert, dateMarker, prevDateMarker) { if (void 0 === prevDateMarker) { return true } return invert ? dateMarker.x < prevDateMarker.getEnd() : dateMarker.x > prevDateMarker.getEnd() }, _initializeMarkersTrackers: function(offset) { var that = this, separatorHeight = that._options.marker.separatorHeight, renderer = that._renderer, businessRange = this._translator.getBusinessRange(), canvas = that._getCanvasStartEnd(), group = that._axisElementsGroup; that._markerTrackers = this._dateMarkers.filter(function(marker) { return !marker.hidden }).map(function(marker, i, markers) { var nextMarker = markers[i + 1] || { x: canvas.end, date: businessRange.max }, x = marker.x, y = marker.y + offset, markerTracker = renderer.path([x, y, x, y + separatorHeight, nextMarker.x, y + separatorHeight, nextMarker.x, y, x, y], "area").attr({ "stroke-width": 1, stroke: "grey", fill: "grey", opacity: 1e-4 }).append(group); markerTracker.data("range", { startValue: marker.date, endValue: nextMarker.date }); if (marker.title) { markerTracker.setTitle(marker.title) } return markerTracker }) }, _getLabelFormatOptions: function(formatString) { var that = this, markerLabelOptions = that._markerLabelOptions; if (!markerLabelOptions) { that._markerLabelOptions = markerLabelOptions = _extend(true, {}, that._options.marker.label) } if (!_isDefined(that._options.marker.label.format)) { markerLabelOptions.format = formatString } return markerLabelOptions }, _adjustConstantLineLabels: function(constantLines) { var that = this, axisPosition = that._options.position, canvas = that.getCanvas(), canvasLeft = canvas.left, canvasRight = canvas.width - canvas.right, canvasTop = canvas.top, canvasBottom = canvas.height - canvas.bottom, verticalCenter = canvasTop + (canvasBottom - canvasTop) / 2, horizontalCenter = canvasLeft + (canvasRight - canvasLeft) / 2, maxLabel = 0; constantLines.forEach(function(item) { var translateX, translateY, isHorizontal = that._isHorizontal, linesOptions = item.options, paddingTopBottom = linesOptions.paddingTopBottom, paddingLeftRight = linesOptions.paddingLeftRight, labelOptions = linesOptions.label, labelVerticalAlignment = labelOptions.verticalAlignment, labelHorizontalAlignment = labelOptions.horizontalAlignment, labelIsInside = "inside" === labelOptions.position, label = item.label, box = item.labelBBox; if (null === label) { return } if (isHorizontal) { if (labelIsInside) { if (labelHorizontalAlignment === LEFT) { translateX = item.coord - paddingLeftRight - box.x - box.width } else { translateX = item.coord + paddingLeftRight - box.x } switch (labelVerticalAlignment) { case CENTER: translateY = verticalCenter - box.y - box.height / 2; break; case BOTTOM: translateY = canvasBottom - paddingTopBottom - box.y - box.height; break; default: translateY = canvasTop + paddingTopBottom - box.y } } else { if (axisPosition === labelVerticalAlignment) { maxLabel = _max(maxLabel, box.height + paddingTopBottom) } translateX = item.coord - box.x - box.width / 2; if (labelVerticalAlignment === BOTTOM) { translateY = canvasBottom + paddingTopBottom - box.y } else { translateY = canvasTop - paddingTopBottom - box.y - box.height } } } else { if (labelIsInside) { if (labelVerticalAlignment === BOTTOM) { translateY = item.coord + paddingTopBottom - box.y } else { translateY = item.coord - paddingTopBottom - box.y - box.height } switch (labelHorizontalAlignment) { case CENTER: translateX = horizontalCenter - box.x - box.width / 2; break; case RIGHT: translateX = canvasRight - paddingLeftRight - box.x - box.width; break; default: translateX = canvasLeft + paddingLeftRight - box.x } } else { if (axisPosition === labelHorizontalAlignment) { maxLabel = _max(maxLabel, box.width + paddingLeftRight) } translateY = item.coord - box.y - box.height / 2; if (labelHorizontalAlignment === RIGHT) { translateX = canvasRight + paddingLeftRight - box.x } else { translateX = canvasLeft - paddingLeftRight - box.x - box.width } } } label.attr({ translateX: translateX, translateY: translateY }) }); return maxLabel }, _drawConstantLinesForEstimating: function(constantLines) { var that = this, renderer = this._renderer, group = renderer.g(); constantLines.forEach(function(options) { that._drawConstantLineLabelText(options.label.text, 0, 0, options.label, group).attr({ align: "center" }) }); return group.append(renderer.root) }, _estimateLabelHeight: function(bBox, labelOptions) { var height = bBox.height, drawingType = labelOptions.drawingType; if ("stagger" === this._validateDisplayMode(drawingType) || "stagger" === this._validateOverlappingMode(labelOptions.overlappingBehavior, drawingType)) { height = 2 * height + labelOptions.staggeringSpacing } if ("rotate" === this._validateDisplayMode(drawingType) || "rotate" === this._validateOverlappingMode(labelOptions.overlappingBehavior, drawingType)) { var sinCos = vizUtils.getCosAndSin(labelOptions.rotationAngle); height = height * sinCos.cos + bBox.width * sinCos.sin } return height && (height + labelOptions.indentFromAxis || 0) || 0 }, _estimateLabelFormat: function(canvas) { this.updateCanvas(canvas); this._updateTickManager(); this._tickManager.getTicks(); this._correctLabelFormat() }, estimateMargins: function(canvas) { this._estimateLabelFormat(canvas); var that = this, options = this._options, constantLineOptions = (options.constantLines || []).filter(function(options) { that._checkAlignmentConstantLineLabels(options.label); return "outside" === options.label.position && options.label.visible }), rootElement = that._renderer.root, businessRange = that._translator.getBusinessRange(), labelIsVisible = options.label.visible && !that._translator.getBusinessRange().stubData, labelValue = labelIsVisible && constants.formatLabel("discrete" === businessRange.axisType ? businessRange.categories[0] : businessRange.max, options.label), labelElement = labelIsVisible && that._renderer.text(labelValue, 0, 0).css(that._textFontStyles).attr(that._textOptions).append(rootElement), titleElement = that._drawTitleText(rootElement, { x: 0, y: 0 }), constantLinesLabelsElement = that._drawConstantLinesForEstimating(constantLineOptions), labelBox = labelElement && labelElement.getBBox() || { x: 0, y: 0, width: 0, height: 0 }, titleBox = titleElement && titleElement.getBBox() || { x: 0, y: 0, width: 0, height: 0 }, constantLinesBox = constantLinesLabelsElement.getBBox(), titleHeight = titleBox.height ? titleBox.height + options.title.margin : 0, labelHeight = that._estimateLabelHeight(labelBox, options.label), constantLinesHeight = constantLinesBox.height ? constantLinesBox.height + getMaxConstantLinePadding(constantLineOptions) : 0, height = labelHeight + titleHeight, margins = { left: _max(getLeftMargin(labelBox), getLeftMargin(constantLinesBox)), right: _max(getRightMargin(labelBox), getRightMargin(constantLinesBox)), top: ("top" === options.position ? height : 0) + getConstantLineLabelMarginForVerticalAlignment(constantLineOptions, "top", constantLinesHeight), bottom: ("top" !== options.position ? height : 0) + getConstantLineLabelMarginForVerticalAlignment(constantLineOptions, "bottom", constantLinesHeight) }; labelElement && labelElement.remove(); titleElement && titleElement.remove(); constantLinesLabelsElement && constantLinesLabelsElement.remove(); return margins }, _checkAlignmentConstantLineLabels: function(labelOptions) { var position = labelOptions.position, verticalAlignment = (labelOptions.verticalAlignment || "").toLowerCase(), horizontalAlignment = (labelOptions.horizontalAlignment || "").toLowerCase(); if (this._isHorizontal) { if ("outside" === position) { verticalAlignment = verticalAlignment === BOTTOM ? BOTTOM : TOP; horizontalAlignment = CENTER } else { verticalAlignment = verticalAlignment === CENTER ? CENTER : verticalAlignment === BOTTOM ? BOTTOM : TOP; horizontalAlignment = horizontalAlignment === LEFT ? LEFT : RIGHT } } else { if ("outside" === position) { verticalAlignment = CENTER; horizontalAlignment = horizontalAlignment === LEFT ? LEFT : RIGHT } else { verticalAlignment = verticalAlignment === BOTTOM ? BOTTOM : TOP; horizontalAlignment = horizontalAlignment === RIGHT ? RIGHT : horizontalAlignment === CENTER ? CENTER : LEFT } } labelOptions.verticalAlignment = verticalAlignment; labelOptions.horizontalAlignment = horizontalAlignment }, _getConstantLineLabelsCoords: function(value, lineLabelOptions) { var that = this, x = value, y = value; if (that._isHorizontal) { y = that._orthogonalPositions["top" === lineLabelOptions.verticalAlignment ? "start" : "end"] } else { x = that._orthogonalPositions["right" === lineLabelOptions.horizontalAlignment ? "end" : "start"] } return { x: x, y: y } }, _getAdjustedStripLabelCoords: function(strip) { var stripOptions = strip.options, paddingTopBottom = stripOptions.paddingTopBottom, paddingLeftRight = stripOptions.paddingLeftRight, horizontalAlignment = stripOptions.label.horizontalAlignment, verticalAlignment = stripOptions.label.verticalAlignment, box = strip.labelBBox, labelHeight = box.height, labelWidth = box.width, labelCoords = strip.labelCoords, y = labelCoords.y - box.y, x = labelCoords.x - box.x; if (verticalAlignment === TOP) { y += paddingTopBottom } else { if (verticalAlignment === CENTER) { y -= labelHeight / 2 } else { if (verticalAlignment === BOTTOM) { y -= paddingTopBottom + labelHeight } } } if (horizontalAlignment === LEFT) { x += paddingLeftRight } else { if (horizontalAlignment === CENTER) { x -= labelWidth / 2 } else { if (horizontalAlignment === RIGHT) { x -= paddingLeftRight + labelWidth } } } return { translateX: x, translateY: y } }, _adjustTitle: function(offset) { offset = offset || 0; if (!this._title) { return } var that = this, options = that._options, position = options.position, margin = options.title.margin, title = that._title, boxTitle = title.bBox, x = boxTitle.x, y = boxTitle.y, width = boxTitle.width, height = boxTitle.height, axisPosition = that._axisPosition, loCoord = axisPosition - margin - offset, hiCoord = axisPosition + margin + offset, params = {}; if (that._isHorizontal) { if (position === TOP) { params.translateY = loCoord - (y + height) } else { params.translateY = hiCoord - y } } else { if (position === LEFT) { params.translateX = loCoord - (x + width) } else { params.translateX = hiCoord - x } } title.element.attr(params) }, _checkTitleOverflow: function() { if (!this._title) { return } var canvasLength = this._getScreenDelta(), title = this._title, boxTitle = title.bBox; if ((this._isHorizontal ? boxTitle.width : boxTitle.height) > canvasLength) { title.element.applyEllipsis(canvasLength) && title.element.setTitle(this._options.title.text) } }, coordsIn: function(x, y) { var canvas = this.getCanvas(), isHorizontal = this._options.isHorizontal, position = this._options.position, coord = isHorizontal ? y : x; if (isHorizontal && position === constants.top || !isHorizontal && position === constants.left) { return coord < canvas[position] } return coord > canvas[isHorizontal ? "height" : "width"] - canvas[position] }, _boundaryTicksVisibility: { min: true, max: true }, _getMinMax: function() { return { min: this._options.min, max: this._options.max } }, _getStick: function() { return !this._options.valueMarginsEnabled }, _getStripLabelCoords: function(from, to, stripLabelOptions) { var x, y, that = this, orthogonalPositions = that._orthogonalPositions, isHorizontal = that._isHorizontal, horizontalAlignment = stripLabelOptions.horizontalAlignment, verticalAlignment = stripLabelOptions.verticalAlignment; if (isHorizontal) { if (horizontalAlignment === CENTER) { x = from + (to - from) / 2 } else { if (horizontalAlignment === LEFT) { x = from } else { if (horizontalAlignment === RIGHT) { x = to } } } y = orthogonalPositions[getStripVerticalAlignmentPosition(verticalAlignment)] } else { x = orthogonalPositions[getStripHorizontalAlignmentPosition(horizontalAlignment)]; if (verticalAlignment === TOP) { y = from } else { if (verticalAlignment === CENTER) { y = to + (from - to) / 2 } else { if (verticalAlignment === BOTTOM) { y = to } } } } return { x: x, y: y } }, _getTranslatedValue: function(value, offset) { var pos1 = this._translator.translate(value, offset, "semidiscrete" === this._options.type && this._options.tickInterval), pos2 = this._axisPosition, isHorizontal = this._isHorizontal; return { x: isHorizontal ? pos1 : pos2, y: isHorizontal ? pos2 : pos1 } }, _getSkippedCategory: function() { var skippedCategory, categories = this._translator.getVisibleCategories() || this._translator.getBusinessRange().categories; if (categories && categories.length && !!this._tickOffset) { skippedCategory = categories[categories.length - 1] } return skippedCategory }, _getSpiderCategoryOption: commonUtils.noop, shift: function(margins) { var that = this, options = that._options, isHorizontal = options.isHorizontal, axesSpacing = that.getMultipleAxesSpacing(), constantLinesGroups = that._axisConstantLineGroups; function shiftGroup(side, group) { var attr = {}, shift = margins[side] + axesSpacing; attr[isHorizontal ? "translateY" : "translateX"] = ("left" === side || "top" === side ? -1 : 1) * shift; if (margins[side]) { (group[side] || group).attr(attr); return shift } } that._axisShift = shiftGroup(options.position, that._axisGroup); if (isHorizontal) { shiftGroup("top", constantLinesGroups); shiftGroup("bottom", constantLinesGroups) } else { shiftGroup("left", constantLinesGroups); shiftGroup("right", constantLinesGroups) } } } } }, /*!***********************************!*\ !*** ./js/viz/axes/polar_axes.js ***! \***********************************/ function(module, exports, __webpack_require__) { var circularAxes, polarAxes, vizUtils = __webpack_require__( /*! ../core/utils */ 509), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, constants = __webpack_require__( /*! ./axes_constants */ 566), xyAxesLinear = __webpack_require__( /*! ./xy_axes */ 578).linear, tick = __webpack_require__( /*! ./tick */ 577).tick, _map = vizUtils.map, _math = Math, _abs = _math.abs, _round = _math.round, convertPolarToXY = vizUtils.convertPolarToXY, _extend = extend, _noop = commonUtils.noop, HALF_PI_ANGLE = 90; function getPolarQuarter(angle) { var quarter; angle = vizUtils.normalizeAngle(angle); if (angle >= 315 && angle <= 360 || angle < 45 && angle >= 0) { quarter = 1 } else { if (angle >= 45 && angle < 135) { quarter = 2 } else { if (angle >= 135 && angle < 225) { quarter = 3 } else { if (angle >= 225 && angle < 315) { quarter = 4 } } } } return quarter } polarAxes = exports; circularAxes = polarAxes.circular = { _updateTranslator: function() { this._translator.update({}, {}, { isHorizontal: true, conversionValue: true }) }, getCenter: function() { return this._center }, getRadius: function() { return this._radius }, getAngles: function() { var options = this._options; return [options.startAngle, options.endAngle] }, _updateRadius: function(canvas) { var rad = Math.min(canvas.width - canvas.left - canvas.right, canvas.height - canvas.top - canvas.bottom) / 2; this._radius = rad < 0 ? 0 : rad }, _updateCenter: function(canvas) { this._center = { x: canvas.left + (canvas.width - canvas.right - canvas.left) / 2, y: canvas.top + (canvas.height - canvas.top - canvas.bottom) / 2 } }, _processCanvas: function(canvas) { var options = this._options; this._updateRadius(canvas); this._updateCenter(canvas); return { left: 0, right: 0, width: _math.abs(options.endAngle - options.startAngle) } }, _createAxisElement: function() { return this._renderer.circle() }, _updateAxisElementPosition: function() { var center = this.getCenter(); this._axisElement.attr({ cx: center.x, cy: center.y, r: this.getRadius() }) }, _boundaryTicksVisibility: { min: true }, _getSpiderCategoryOption: function() { return this._options.firstPointOnStartAngle }, _getMinMax: function() { var max, options = this._options, min = commonUtils.isNumeric(options.originValue) ? options.originValue : void 0; if (options.period > 0 && options.argumentType === constants.numeric) { min = min || 0; max = min + options.period } return { min: min, max: max } }, _getStick: function() { return this._options.firstPointOnStartAngle || this._options.type !== constants.discrete }, _getTranslatedCoord: function(value, offset) { return this._translator.translate(value, offset) - HALF_PI_ANGLE }, _getCanvasStartEnd: function() { return { start: 0 - HALF_PI_ANGLE, end: 360 - HALF_PI_ANGLE } }, _getStripGraphicAttributes: function(fromAngle, toAngle) { var center = this.getCenter(), angle = this.getAngles()[0], r = this.getRadius(); return { x: center.x, y: center.y, innerRadius: 0, outerRadius: r, startAngle: -toAngle - angle, endAngle: -fromAngle - angle } }, _createStrip: function(fromAngle, toAngle, attr) { var coords = this._getStripGraphicAttributes(fromAngle, toAngle); return this._renderer.arc(coords.x, coords.y, coords.innerRadius, coords.outerRadius, coords.startAngle, coords.endAngle).attr(attr) }, _getStripLabelCoords: function(from, to) { var that = this, coords = that._getStripGraphicAttributes(from, to), angle = coords.startAngle + (coords.endAngle - coords.startAngle) / 2, cosSin = vizUtils.getCosAndSin(angle), halfRad = that.getRadius() / 2, center = that.getCenter(), x = _round(center.x + halfRad * cosSin.cos), y = _round(center.y - halfRad * cosSin.sin); return { x: x, y: y, align: constants.center } }, _getConstantLineGraphicAttributes: function(value) { var center = this.getCenter(), r = this.getRadius(); return { points: [center.x, center.y, center.x + r, center.y] } }, _createConstantLine: function(value, attr) { var center = this.getCenter(); return this._createPathElement(this._getConstantLineGraphicAttributes(value).points, attr).rotate(value + this.getAngles()[0], center.x, center.y) }, _getConstantLineLabelsCoords: function(value) { var that = this, cosSin = vizUtils.getCosAndSin(-value - that.getAngles()[0]), halfRad = that.getRadius() / 2, center = that.getCenter(), x = _round(center.x + halfRad * cosSin.cos), y = _round(center.y - halfRad * cosSin.sin); return { x: x, y: y } }, _checkAlignmentConstantLineLabels: _noop, _getScreenDelta: function() { var angles = this.getAngles(); return _abs(angles[0] - angles[1]) * this.getRadius() * Math.PI / 180 }, _getTickMarkPoints: function(tick, length) { var center = this.getCenter(), corrections = { inside: -1, center: -.5, outside: 0 }, radiusWithTicks = this.getRadius() + length * corrections[this._options.tickOrientation || "center"]; return [center.x + radiusWithTicks, center.y, center.x + radiusWithTicks + length, center.y] }, _getLabelAdjustedCoord: function(tick) { var that = this, labelCoords = tick.labelCoords, labelY = labelCoords.y, labelAngle = labelCoords.angle, cosSin = vizUtils.getCosAndSin(labelAngle), cos = cosSin.cos, sin = cosSin.sin, box = tick.labelBBox, halfWidth = box.width / 2, halfHeight = box.height / 2, indentFromAxis = that._options.label.indentFromAxis || 0, x = labelCoords.x + indentFromAxis * cos, y = labelY + (labelY - box.y - halfHeight) + indentFromAxis * sin; switch (getPolarQuarter(labelAngle)) { case 1: x += halfWidth; y += halfHeight * sin; break; case 2: x += halfWidth * cos; y += halfHeight; break; case 3: x += -halfWidth; y += halfHeight * sin; break; case 4: x += halfWidth * cos; y += -halfHeight } return { x: x, y: y } }, _getGridLineDrawer: function() { var that = this; return function(tick, gridStyle) { var center = that.getCenter(); return that._createPathElement(that._getGridPoints().points, gridStyle).rotate(tick.coords.angle, center.x, center.y) } }, _getGridPoints: function() { var r = this.getRadius(), center = this.getCenter(); return { points: [center.x, center.y, center.x + r, center.y] } }, _getTranslatedValue: function(value, offset) { var startAngle = this.getAngles()[0], angle = this._translator.translate(value, -offset), coords = convertPolarToXY(this.getCenter(), startAngle, angle, this.getRadius()); return { x: coords.x, y: coords.y, angle: angle + startAngle - HALF_PI_ANGLE } }, _getAdjustedStripLabelCoords: function(strip) { var box = strip.labelBBox; return { translateY: strip.label.attr("y") - box.y - box.height / 2 } }, coordsIn: function(x, y) { return vizUtils.convertXYToPolar(this.getCenter(), x, y).r > this.getRadius() }, _rotateTick: function(element, coords) { var center = this.getCenter(); element.rotate(coords.angle, center.x, center.y) }, _validateOverlappingMode: function(mode) { return constants.validateOverlappingMode(mode) }, _validateDisplayMode: function() { return "standard" }, _getStep: function(boxes) { var that = this, radius = that.getRadius() + (that._options.label.indentFromAxis || 0), maxLabelBox = boxes.reduce(function(prevValue, box) { var curValue = prevValue; if (prevValue.width < box.width) { curValue.width = box.width } if (prevValue.height < box.height) { curValue.height = box.height } return curValue }, { width: 0, height: 0 }), angle1 = _abs(2 * _math.atan(maxLabelBox.height / (2 * radius - maxLabelBox.width)) * 180 / _math.PI), angle2 = _abs(2 * _math.atan(maxLabelBox.width / (2 * radius - maxLabelBox.height)) * 180 / _math.PI); return constants.getTicksCountInRange(that._majorTicks, "angle", _math.max(angle1, angle2)) }, _checkBoundedLabelsOverlapping: function(step, majorTicks, boxes) { var lastVisibleLabelIndex = _math.floor((boxes.length - 1) / step) * step, labelOpt = this._options.label; if (!lastVisibleLabelIndex) { return } if (constants.areLabelsOverlap(boxes[0], boxes[lastVisibleLabelIndex], labelOpt.minSpacing, constants.center)) { "first" === labelOpt.overlappingBehavior.hideFirstOrLast ? majorTicks[0].label.remove() : majorTicks[lastVisibleLabelIndex].label.remove() } }, shift: function(margins) { this._axisGroup.attr({ translateX: margins.right, translateY: margins.bottom }) } }; exports.circularSpider = _extend({}, circularAxes, { _createAxisElement: function() { return this._renderer.path([], "area") }, _updateAxisElementPosition: function() { this._axisElement.attr({ points: _map(this.getSpiderTicks(), function(tick) { return { x: tick.coords.x, y: tick.coords.y } }) }) }, _getStick: function() { return true }, _getSpiderCategoryOption: function() { return true }, getSpiderTicks: function() { var that = this; that._spiderTicks = that._tickManager.getFullTicks().map(tick(that, that.renderer, {}, {}, that._getSkippedCategory(), true)); that._spiderTicks.forEach(function(tick) { tick.initCoords() }); return that._spiderTicks }, _getStripGraphicAttributes: function(fromAngle, toAngle) { var firstTick, lastTick, nextTick, tick, center = this.getCenter(), spiderTicks = this.getSpiderTicks(), points = [], i = 0, len = spiderTicks.length; while (i < len) { tick = spiderTicks[i].coords; if (tick.angle >= fromAngle && tick.angle <= toAngle) { if (!firstTick) { firstTick = (spiderTicks[i - 1] || spiderTicks[spiderTicks.length - 1]).coords; points.push((tick.x + firstTick.x) / 2, (tick.y + firstTick.y) / 2) } points.push(tick.x, tick.y); nextTick = (spiderTicks[i + 1] || spiderTicks[0]).coords; lastTick = { x: (tick.x + nextTick.x) / 2, y: (tick.y + nextTick.y) / 2 } } i++ } points.push(lastTick.x, lastTick.y); points.push(center.x, center.y); return { points: points } }, _createStrip: function(fromAngle, toAngle, attr) { var points = this._getStripGraphicAttributes(fromAngle, toAngle).points; return this._renderer.path(points, "area").attr(attr) }, _getTranslatedCoord: function(value, offset) { return this._translator.translate(value, offset) - HALF_PI_ANGLE }, _setTickOffset: function() { this._tickOffset = false } }); polarAxes.linear = { _getMinMax: circularAxes._getMinMax, _getStick: xyAxesLinear._getStick, _getSpiderCategoryOption: commonUtils.noop, _updateTranslator: function() { this._translator.update({}, {}, { isHorizontal: true }) }, _updateRadius: circularAxes._updateRadius, getRadius: circularAxes.getRadius, getCenter: circularAxes.getCenter, getAngles: circularAxes.getAngles, _updateCenter: circularAxes._updateCenter, _processCanvas: function(canvas) { this._updateRadius(canvas); this._updateCenter(canvas); return { left: 0, right: 0, width: this.getRadius() } }, _createAxisElement: xyAxesLinear._createAxisElement, _updateAxisElementPosition: function() { var centerCoord = this.getCenter(); this._axisElement.attr({ points: [centerCoord.x, centerCoord.y, centerCoord.x + this.getRadius(), centerCoord.y] }).rotate(this.getAngles()[0] - HALF_PI_ANGLE, centerCoord.x, centerCoord.y) }, _getScreenDelta: function() { return this.getRadius() }, _getTickMarkPoints: function(tick, length) { var coords = tick.coords; return [coords.x - length / 2, coords.y, coords.x + length / 2, coords.y] }, _getLabelAdjustedCoord: function(tick) { var x, y, that = this, labelCoords = tick.labelCoords, labelY = labelCoords.y, cosSin = vizUtils.getCosAndSin(labelCoords.angle), indentFromAxis = that._options.label.indentFromAxis || 0, box = tick.labelBBox; x = labelCoords.x - _abs(indentFromAxis * cosSin.sin) + _abs(box.width / 2 * cosSin.cos) - box.width / 2; y = labelY + (labelY - box.y) - _abs(box.height / 2 * cosSin.sin) + _abs(indentFromAxis * cosSin.cos); return { x: x, y: y } }, _getGridLineDrawer: function() { var that = this; return function(tick, gridStyle) { var grid = that._getGridPoints(tick.coords); return that._renderer.circle(grid.x, grid.y, grid.r).attr(gridStyle).sharp() } }, _getGridPoints: function(coords) { var pos = this.getCenter(); return { x: pos.x, y: pos.y, r: vizUtils.getDistance(pos.x, pos.y, coords.x, coords.y) } }, _getTranslatedValue: function(value, offset) { var startAngle = this.getAngles()[0], xy = convertPolarToXY(this.getCenter(), startAngle, 0, this._translator.translate(value, offset)); return { x: xy.x, y: xy.y, angle: startAngle - HALF_PI_ANGLE } }, _getTranslatedCoord: function(value, offset) { return this._translator.translate(value, offset) }, _getCanvasStartEnd: function() { return { start: 0, end: this.getRadius() } }, _getStripGraphicAttributes: function(fromPoint, toPoint) { var center = this.getCenter(); return { x: center.x, y: center.y, innerRadius: fromPoint, outerRadius: toPoint } }, _createStrip: function(fromPoint, toPoint, attr) { var attrs = this._getStripGraphicAttributes(fromPoint, toPoint); return this._renderer.arc(attrs.x, attrs.y, attrs.innerRadius, attrs.outerRadius, 0, 360).attr(attr) }, _getAdjustedStripLabelCoords: circularAxes._getAdjustedStripLabelCoords, _getStripLabelCoords: function(from, to) { var that = this, labelPos = from + (to - from) / 2, center = that.getCenter(), y = _round(center.y - labelPos); return { x: center.x, y: y, align: constants.center } }, _getConstantLineGraphicAttributes: function(value) { var center = this.getCenter(); return { cx: center.x, cy: center.y, r: value } }, _createConstantLine: function(value, attr) { var attrs = this._getConstantLineGraphicAttributes(value); return this._renderer.circle(attrs.cx, attrs.cy, attrs.r).attr(attr).sharp() }, _getConstantLineLabelsCoords: function(value) { var that = this, center = that.getCenter(), y = _round(center.y - value); return { x: center.x, y: y } }, _checkAlignmentConstantLineLabels: _noop, _rotateTick: function(element, coords) { element.rotate(coords.angle + HALF_PI_ANGLE, coords.x, coords.y) }, _validateOverlappingMode: circularAxes._validateOverlappingMode, _validateDisplayMode: circularAxes._validateDisplayMode, _getStep: function(boxes) { var quarter = getPolarQuarter(this.getAngles()[0]), spacing = this._options.label.minSpacing, func = 2 === quarter || 4 === quarter ? function(box) { return box.width + spacing } : function(box) { return box.height }, maxLabelLength = boxes.reduce(function(prevValue, box) { return _math.max(prevValue, func(box)) }, 0); return constants.getTicksCountInRange(this._majorTicks, 2 === quarter || 4 === quarter ? "x" : "y", maxLabelLength) } }; polarAxes.linearSpider = _extend({}, polarAxes.linear, { _createPathElement: function(points, attr) { return this._renderer.path(points, "area").attr(attr).sharp() }, setSpiderTicks: function(ticks) { this._spiderTicks = ticks }, _getGridLineDrawer: function() { var that = this; return function(tick, gridStyle, element) { return that._createPathElement(that._getGridPoints(tick.coords).points, gridStyle) } }, _getGridPoints: function(coords) { var pos = this.getCenter(), radius = vizUtils.getDistance(pos.x, pos.y, coords.x, coords.y); return this._getGridPointsByRadius(radius) }, _getGridPointsByRadius: function(radius) { var pos = this.getCenter(); return { points: _map(this._spiderTicks, function(tick) { var cosSin = vizUtils.getCosAndSin(tick.coords.angle); return { x: _round(pos.x + radius * cosSin.cos), y: _round(pos.y + radius * cosSin.sin) } }) } }, _getStripGraphicAttributes: function(fromPoint, toPoint) { var innerPoints = this._getGridPointsByRadius(toPoint).points, outerPoints = this._getGridPointsByRadius(fromPoint).points; return { points: [outerPoints, innerPoints.reverse()] } }, _createStrip: function(fromPoint, toPoint, attr) { var points = this._getStripGraphicAttributes(fromPoint, toPoint).points; return this._renderer.path(points, "area").attr(attr) }, _getConstantLineGraphicAttributes: function(value) { return this._getGridPointsByRadius(value) }, _createConstantLine: function(value, attr) { return this._createPathElement(this._getConstantLineGraphicAttributes(value).points, attr) } }) }, /*!**************************************!*\ !*** ./js/viz/core/series_family.js ***! \**************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, _math = Math, _round = _math.round, _abs = _math.abs, _pow = _math.pow, _each = $.each, _noop = commonUtils.noop, vizUtils = __webpack_require__( /*! ./utils */ 509), _normalizeEnum = vizUtils.normalizeEnum; function getStacksWithArgument(stackKeepers, argument) { var stacksWithArgument = []; _each(stackKeepers, function(stackName, seriesInStack) { _each(seriesInStack, function(_, singleSeries) { var i, points = singleSeries.getPointsByArg(argument), pointsLength = points.length; for (i = 0; i < pointsLength; ++i) { if (points[i].hasValue()) { stacksWithArgument.push(stackName); return false } } }) }); return stacksWithArgument } function correctPointCoordinatesForStacks(stackKeepers, stacksWithArgument, argument, parameters) { _each(stackKeepers, function(stackName, seriesInStack) { var offset, stackIndex = inArray(stackName, stacksWithArgument); if (stackIndex === -1) { return } offset = getOffset(stackIndex, parameters); _each(seriesInStack, function(_, singleSeries) { correctPointCoordinates(singleSeries.getPointsByArg(argument) || [], parameters.width, offset) }) }) } function adjustBarSeriesDimensionsCore(series, stackCount, options, seriesStackIndexCallback) { var percentWidth, stackIndex, i, points, stackName, stacksWithArgument, parameters, argumentsKeeper = {}, stackKeepers = {}, barsArea = series[0] && .7 * series[0].getArgumentAxis().getTranslator().getInterval(), barWidth = options.barWidth; if (options.equalBarWidth) { percentWidth = barWidth && (barWidth < 0 || barWidth > 1) ? 0 : barWidth; parameters = calculateParams(barsArea, stackCount, percentWidth); for (i = 0; i < series.length; i++) { stackIndex = seriesStackIndexCallback(i, stackCount); points = series[i].getPoints(); correctPointCoordinates(points, parameters.width, getOffset(stackIndex, parameters)) } } else { _each(series, function(i, singleSeries) { stackName = singleSeries.getStackName && singleSeries.getStackName(); stackName = stackName || i.toString(); if (!stackKeepers[stackName]) { stackKeepers[stackName] = [] } stackKeepers[stackName].push(singleSeries); _each(singleSeries.getPoints(), function(_, point) { var argument = point.argument; if (!argumentsKeeper.hasOwnProperty(argument)) { argumentsKeeper[argument.valueOf()] = 1 } }) }); for (var argument in argumentsKeeper) { stacksWithArgument = getStacksWithArgument(stackKeepers, argument); parameters = calculateParams(barsArea, stacksWithArgument.length); correctPointCoordinatesForStacks(stackKeepers, stacksWithArgument, argument, parameters) } } } function calculateParams(barsArea, count, percentWidth) { var spacing, width, middleIndex = count / 2; if (!percentWidth) { spacing = _round(barsArea / count * .2); width = _round((barsArea - spacing * (count - 1)) / count) } else { width = _round(barsArea * percentWidth / count); spacing = _round(count > 1 ? (barsArea - barsArea * percentWidth) / (count - 1) : 0) } return { width: width > 1 ? width : 1, spacing: spacing, middleIndex: middleIndex } } function getOffset(stackIndex, parameters) { return (stackIndex - parameters.middleIndex + .5) * parameters.width - (parameters.middleIndex - stackIndex - .5) * parameters.spacing } function correctPointCoordinates(points, width, offset) { _each(points, function(_, point) { point.correctCoordinates({ width: width, offset: offset }) }) } function checkMinBarSize(value, minShownValue) { return _abs(value) < minShownValue ? value >= 0 ? minShownValue : -minShownValue : value } function getValueType(value) { return value >= 0 ? "positive" : "negative" } function getVisibleSeries(that) { return that.series.filter(function(s) { return s.isVisible() }) } function getAbsStackSumByArg(stackKeepers, stackName, argument) { var positiveStackValue = (stackKeepers.positive[stackName] || {})[argument] || 0, negativeStackValue = -(stackKeepers.negative[stackName] || {})[argument] || 0; return positiveStackValue + negativeStackValue } function getSeriesStackIndexCallback(rotated, series, stackIndexes) { if (!rotated) { return function(seriesIndex) { return stackIndexes ? stackIndexes[series[seriesIndex].getStackName()] : seriesIndex } } else { return function(seriesIndex, stackCount) { return stackCount - (stackIndexes ? stackIndexes[series[seriesIndex].getStackName()] : seriesIndex) - 1 } } } function adjustBarSeriesDimensions() { var that = this, series = getVisibleSeries(that); adjustBarSeriesDimensionsCore(series, series.length, that._options, getSeriesStackIndexCallback(that.rotated, series)) } function adjustStackedBarSeriesDimensions() { var that = this, series = getVisibleSeries(that), stackIndexes = {}, stackCount = 0; _each(series, function() { var stackName = this.getStackName(); if (!stackIndexes.hasOwnProperty(stackName)) { stackIndexes[stackName] = stackCount++ } }); adjustBarSeriesDimensionsCore(series, stackCount, that._options, getSeriesStackIndexCallback(that.rotated, series, stackIndexes)) } function adjustStackedSeriesValues() { var that = this, negativesAsZeroes = that._options.negativesAsZeroes, series = getVisibleSeries(that), stackKeepers = { positive: {}, negative: {} }, holesStack = { left: {}, right: {} }; _each(series, function(seriesIndex, singleSeries) { var points = singleSeries.getPoints(), hole = false; singleSeries._prevSeries = series[seriesIndex - 1]; singleSeries.holes = extend(true, {}, holesStack); _each(points, function(index, point) { var currentStack, value = point.initialValue, argument = point.argument.valueOf(), stackName = singleSeries.getStackName(), stacks = value >= 0 ? stackKeepers.positive : stackKeepers.negative; if (negativesAsZeroes && value < 0) { stacks = stackKeepers.positive; value = 0; point.resetValue() } stacks[stackName] = stacks[stackName] || {}; currentStack = stacks[stackName]; if (currentStack[argument]) { point.correctValue(currentStack[argument]); currentStack[argument] += value } else { currentStack[argument] = value; point.resetCorrection() } if (!point.hasValue()) { var prevPoint = points[index - 1]; if (!hole && prevPoint && prevPoint.hasValue()) { argument = prevPoint.argument.valueOf(); prevPoint._skipSetRightHole = true; holesStack.right[argument] = (holesStack.right[argument] || 0) + (prevPoint.value - (isFinite(prevPoint.minValue) ? prevPoint.minValue : 0)) } hole = true } else { if (hole) { hole = false; holesStack.left[argument] = (holesStack.left[argument] || 0) + (point.value - (isFinite(point.minValue) ? point.minValue : 0)); point._skipSetLeftHole = true } } }) }); _each(series, function(seriesIndex, singleSeries) { var points = singleSeries.getPoints(), holes = singleSeries.holes; _each(points, function(index, point) { var argument = point.argument.valueOf(); point.resetHoles(); !point._skipSetLeftHole && point.setHole(holes.left[argument] || holesStack.left[argument] && 0, "left"); !point._skipSetRightHole && point.setHole(holes.right[argument] || holesStack.right[argument] && 0, "right"); point._skipSetLeftHole = null; point._skipSetRightHole = null }) }); that._stackKeepers = stackKeepers; _each(series, function(_, singleSeries) { _each(singleSeries.getPoints(), function(_, point) { var argument = point.argument.valueOf(); point.setPercentValue(getAbsStackSumByArg(stackKeepers, singleSeries.getStackName(), argument), that.fullStacked, holesStack.left[argument], holesStack.right[argument]) }) }) } function updateStackedSeriesValues() { var that = this, series = getVisibleSeries(that), stack = that._stackKeepers, stackKeepers = { positive: {}, negative: {} }; _each(series, function(_, singleSeries) { var minBarSize = singleSeries.getOptions().minBarSize, minShownBusinessValue = minBarSize && singleSeries.getValueAxis().getTranslator().getMinBarSize(minBarSize), stackName = singleSeries.getStackName(); _each(singleSeries.getPoints(), function(index, point) { if (!point.hasValue()) { return } var updateValue, valueType, currentStack, value = point.initialValue, argument = point.argument.valueOf(); if (that.fullStacked) { value = value / getAbsStackSumByArg(stack, stackName, argument) || 0 } updateValue = checkMinBarSize(value, minShownBusinessValue); valueType = getValueType(updateValue); currentStack = stackKeepers[valueType][stackName] = stackKeepers[valueType][stackName] || {}; if (currentStack[argument]) { point.minValue = currentStack[argument]; currentStack[argument] += updateValue } else { currentStack[argument] = updateValue } point.value = currentStack[argument] }) }); if (that.fullStacked) { updateFullStackedSeriesValues(series, stackKeepers) } } function updateFullStackedSeriesValues(series, stackKeepers) { _each(series, function(_, singleSeries) { var stackName = singleSeries.getStackName ? singleSeries.getStackName() : "default"; _each(singleSeries.getPoints(), function(index, point) { var stackSum = getAbsStackSumByArg(stackKeepers, stackName, point.argument.valueOf()); point.value = point.value / stackSum; if (commonUtils.isNumeric(point.minValue)) { point.minValue = point.minValue / stackSum } }) }) } function updateBarSeriesValues() { _each(this.series, function(_, singleSeries) { var minBarSize = singleSeries.getOptions().minBarSize, minShownBusinessValue = minBarSize && singleSeries.getValueAxis().getTranslator().getMinBarSize(minBarSize); if (minShownBusinessValue) { _each(singleSeries.getPoints(), function(index, point) { if (point.hasValue()) { point.value = checkMinBarSize(point.initialValue, minShownBusinessValue) } }) } }) } function adjustCandlestickSeriesDimensions() { var series = getVisibleSeries(this); adjustBarSeriesDimensionsCore(series, series.length, { barWidth: null, equalBarWidth: true }, getSeriesStackIndexCallback(this.rotated, series)) } function adjustBubbleSeriesDimensions() { var series = getVisibleSeries(this); if (!series.length) { return } var pointSize, bubbleArea, sizeProportion, sizeDispersion, areaDispersion, options = this._options, argTranslator = series[0].getArgumentAxis().getTranslator(), valTranslator = series[0].getValueAxis().getTranslator(), visibleAreaX = argTranslator.getCanvasVisibleArea(), visibleAreaY = valTranslator.getCanvasVisibleArea(), min = _math.min(visibleAreaX.max - visibleAreaX.min, visibleAreaY.max - visibleAreaY.min), minBubbleArea = _pow(options.minBubbleSize, 2), maxBubbleArea = _pow(min * options.maxBubbleSize, 2), equalBubbleSize = (min * options.maxBubbleSize + options.minBubbleSize) / 2, minPointSize = 1 / 0, maxPointSize = 0; _each(series, function(_, seriesItem) { _each(seriesItem.getPoints(), function(_, point) { maxPointSize = maxPointSize > point.size ? maxPointSize : point.size; minPointSize = minPointSize < point.size ? minPointSize : point.size }) }); sizeDispersion = maxPointSize - minPointSize; areaDispersion = _abs(maxBubbleArea - minBubbleArea); minPointSize = minPointSize < 0 ? 0 : minPointSize; _each(series, function(_, seriesItem) { _each(seriesItem.getPoints(), function(_, point) { if (maxPointSize === minPointSize) { pointSize = _round(equalBubbleSize) } else { sizeProportion = _abs(point.size - minPointSize) / sizeDispersion; bubbleArea = areaDispersion * sizeProportion + minBubbleArea; pointSize = _round(_math.sqrt(bubbleArea)) } point.correctCoordinates(pointSize) }) }) } function SeriesFamily(options) { var debug = __webpack_require__( /*! ../../core/utils/console */ 13).debug; debug.assert(options.type, "type was not passed or empty"); var that = this; that.type = _normalizeEnum(options.type); that.pane = options.pane; that.rotated = options.rotated; that.series = []; that.updateOptions(options); switch (that.type) { case "bar": that.adjustSeriesDimensions = adjustBarSeriesDimensions; that.updateSeriesValues = updateBarSeriesValues; break; case "rangebar": that.adjustSeriesDimensions = adjustBarSeriesDimensions; break; case "fullstackedbar": that.fullStacked = true; that.adjustSeriesDimensions = adjustStackedBarSeriesDimensions; that.adjustSeriesValues = adjustStackedSeriesValues; that.updateSeriesValues = updateStackedSeriesValues; break; case "stackedbar": that.adjustSeriesDimensions = adjustStackedBarSeriesDimensions; that.adjustSeriesValues = adjustStackedSeriesValues; that.updateSeriesValues = updateStackedSeriesValues; break; case "fullstackedarea": case "fullstackedline": case "fullstackedspline": case "fullstackedsplinearea": that.fullStacked = true; that.adjustSeriesValues = adjustStackedSeriesValues; break; case "stackedarea": case "stackedsplinearea": case "stackedline": case "stackedspline": that.adjustSeriesValues = adjustStackedSeriesValues; break; case "candlestick": case "stock": that.adjustSeriesDimensions = adjustCandlestickSeriesDimensions; break; case "bubble": that.adjustSeriesDimensions = adjustBubbleSeriesDimensions } } exports.SeriesFamily = SeriesFamily; SeriesFamily.prototype = { constructor: SeriesFamily, adjustSeriesDimensions: _noop, adjustSeriesValues: _noop, updateSeriesValues: _noop, updateOptions: function(options) { this._options = options }, dispose: function() { this.series = null }, add: function(series) { var type = this.type; this.series = vizUtils.map(series, function(singleSeries) { return singleSeries.type === type ? singleSeries : null }) } } }, /*!**********************************************!*\ !*** ./js/viz/chart_components/crosshair.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var math = Math, mathAbs = math.abs, mathMin = math.min, mathMax = math.max, mathFloor = math.floor, vizUtils = __webpack_require__( /*! ../core/utils */ 509), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, HORIZONTAL = "horizontal", VERTICAL = "vertical", LABEL_BACKGROUND_PADDING_X = 8, LABEL_BACKGROUND_PADDING_Y = 4, CENTER = "center", RIGHT = "right", LEFT = "left", TOP = "top", BOTTOM = "bottom"; exports.getMargins = function() { return { x: LABEL_BACKGROUND_PADDING_X, y: LABEL_BACKGROUND_PADDING_Y } }; function getRectangleBBox(bBox) { return { x: bBox.x - LABEL_BACKGROUND_PADDING_X, y: bBox.y - LABEL_BACKGROUND_PADDING_Y, width: bBox.width + 2 * LABEL_BACKGROUND_PADDING_X, height: bBox.height + 2 * LABEL_BACKGROUND_PADDING_Y } } function getLabelCheckerPosition(x, y, isHorizontal, canvas) { var params = isHorizontal ? ["x", "width", "y", "height", y, 0] : ["y", "height", "x", "width", x, 1]; return function(bBox, position, coord) { var labelCoord = { x: coord.x, y: coord.y }, rectangleBBox = getRectangleBBox(bBox), delta = isHorizontal ? coord.y - bBox.y - bBox.height / 2 : coord.y - bBox.y; labelCoord.y = isHorizontal || !isHorizontal && position === BOTTOM ? coord.y + delta : coord.y; if (rectangleBBox[params[0]] < 0) { labelCoord[params[0]] -= rectangleBBox[params[0]] } else { if (rectangleBBox[params[0]] + rectangleBBox[params[1]] + delta * params[5] > canvas[params[1]]) { labelCoord[params[0]] -= rectangleBBox[params[0]] + rectangleBBox[params[1]] + delta * params[5] - canvas[params[1]] } } if (params[4] - rectangleBBox[params[3]] / 2 < 0) { labelCoord[params[2]] -= params[4] - rectangleBBox[params[3]] / 2 } else { if (params[4] + rectangleBBox[params[3]] / 2 > canvas[params[3]]) { labelCoord[params[2]] -= params[4] + rectangleBBox[params[3]] / 2 - canvas[params[3]] } } return labelCoord } } function Crosshair(renderer, options, params, group) { var that = this; that._renderer = renderer; that._crosshairGroup = group; that._options = {}; that.update(options, params) } Crosshair.prototype = { constructor: Crosshair, update: function(options, params) { var that = this, canvas = params.canvas; that._canvas = { top: canvas.top, bottom: canvas.height - canvas.bottom, left: canvas.left, right: canvas.width - canvas.right, width: canvas.width, height: canvas.height }; that._axes = params.axes; that._panes = params.panes; that._prepareOptions(options, HORIZONTAL); that._prepareOptions(options, VERTICAL) }, dispose: function() { var that = this; that._renderer = that._crosshairGroup = that._options = that._axes = that._canvas = that._horizontalGroup = that._verticalGroup = that._horizontal = that._vertical = that._circle = that._panes = null }, _prepareOptions: function(options, direction) { var lineOptions = options[direction + "Line"]; this._options[direction] = { visible: lineOptions.visible, line: { stroke: lineOptions.color || options.color, "stroke-width": lineOptions.width || options.width, dashStyle: lineOptions.dashStyle || options.dashStyle, opacity: lineOptions.opacity || options.opacity, "stroke-linecap": "butt" }, label: extend(true, {}, options.label, lineOptions.label) } }, _createLines: function(options, sharpParam, group) { var lines = [], canvas = this._canvas, points = [canvas.left, canvas.top, canvas.left, canvas.top]; for (var i = 0; i < 2; i++) { lines.push(this._renderer.path(points, "line").attr(options).sharp(sharpParam).append(group)) } return lines }, render: function() { var that = this, renderer = that._renderer, options = that._options, verticalOptions = options.vertical, horizontalOptions = options.horizontal, extraOptions = horizontalOptions.visible ? horizontalOptions.line : verticalOptions.line, circleOptions = { stroke: extraOptions.stroke, "stroke-width": extraOptions["stroke-width"], dashStyle: extraOptions.dashStyle, opacity: extraOptions.opacity }, canvas = that._canvas; that._horizontal = {}; that._vertical = {}; that._circle = renderer.circle(canvas.left, canvas.top, 0).attr(circleOptions).append(that._crosshairGroup); that._horizontalGroup = renderer.g().append(that._crosshairGroup); that._verticalGroup = renderer.g().append(that._crosshairGroup); if (verticalOptions.visible) { that._vertical.lines = that._createLines(verticalOptions.line, "h", that._verticalGroup); that._vertical.labels = that._createLabels(that._axes[0], verticalOptions, false, that._verticalGroup) } if (horizontalOptions.visible) { that._horizontal.lines = that._createLines(horizontalOptions.line, "v", that._horizontalGroup); that._horizontal.labels = that._createLabels(that._axes[1], horizontalOptions, true, that._horizontalGroup) } that.hide() }, _createLabels: function(axes, options, isHorizontal, group) { var x, y, text, background, currentLabelPos, that = this, canvas = that._canvas, renderer = that._renderer, labels = [], labelOptions = options.label; if (labelOptions.visible) { axes.forEach(function(axis) { var align, position = axis.getOptions().position; if (axis.getTranslator().getBusinessRange().stubData) { return } currentLabelPos = axis.getLabelsPosition(); if (isHorizontal) { y = canvas.top; x = currentLabelPos } else { x = canvas.left; y = currentLabelPos } align = position === TOP || position === BOTTOM ? CENTER : position === RIGHT ? LEFT : RIGHT; background = renderer.rect(0, 0, 0, 0).attr({ fill: labelOptions.backgroundColor || options.line.stroke }).append(group); text = renderer.text("0", 0, 0).css(vizUtils.patchFontOptions(options.label.font)).attr({ align: align }).append(group); labels.push({ text: text, background: background, axis: axis, options: labelOptions, pos: { coord: currentLabelPos, side: position }, startXY: { x: x, y: y } }) }) } return labels }, _updateText: function(value, axisName, labels, point, func) { var that = this; labels.forEach(function(label) { var axis = label.axis, coord = label.startXY, textElement = label.text, backgroundElement = label.background, text = ""; if (!axis.name || axis.name === axisName) { text = axis.getFormattedValue(value, label.options, point) } if (text) { textElement.attr({ text: text, x: coord.x, y: coord.y }); textElement.attr(func(textElement.getBBox(), label.pos.side, coord)); that._updateLinesCanvas(label); backgroundElement.attr(getRectangleBBox(textElement.getBBox())) } else { textElement.attr({ text: "" }); backgroundElement.attr({ x: 0, y: 0, width: 0, height: 0 }) } }) }, hide: function() { this._crosshairGroup.attr({ visibility: "hidden" }) }, _updateLinesCanvas: function(label) { var position = label.pos.side, labelCoord = label.pos.coord, coords = this._linesCanvas, canvas = this._canvas; coords[position] = coords[position] !== canvas[position] && mathAbs(coords[position] - canvas[position]) < mathAbs(labelCoord - canvas[position]) ? coords[position] : labelCoord }, _updateLines: function(lines, x, y, r, isHorizontal) { var coords = this._linesCanvas, canvas = this._canvas, points = isHorizontal ? [ [mathMin(x - r, coords.left), canvas.top, x - r, canvas.top], [x + r, canvas.top, mathMax(coords.right, x + r), canvas.top] ] : [ [canvas.left, mathMin(coords.top, y - r), canvas.left, y - r], [canvas.left, y + r, canvas.left, mathMax(coords.bottom, y + r)] ]; for (var i = 0; i < 2; i++) { lines[i].attr({ points: points[i] }) } }, _resetLinesCanvas: function() { var canvas = this._canvas; this._linesCanvas = { left: canvas.left, right: canvas.right, top: canvas.top, bottom: canvas.bottom } }, _getClipRectForPane: function(x, y) { var i, coords, panes = this._panes; for (i = 0; i < panes.length; i++) { coords = panes[i].coords; if (coords.left <= x && coords.right >= x && coords.top <= y && coords.bottom >= y) { return panes[i].clipRect } } return { id: null } }, show: function(data) { var that = this, point = data.point, pointData = point.getCrosshairData(data.x, data.y), r = point.getPointRadius(), horizontal = that._horizontal, vertical = that._vertical, rad = !r ? 0 : r + 3, canvas = that._canvas, x = mathFloor(pointData.x), y = mathFloor(pointData.y); if (x >= canvas.left && x <= canvas.right && y >= canvas.top && y <= canvas.bottom) { that._crosshairGroup.attr({ visibility: "visible" }); that._resetLinesCanvas(); that._circle.attr({ cx: x, cy: y, r: rad, "clip-path": that._getClipRectForPane(x, y).id }); if (horizontal.lines) { that._updateText(pointData.yValue, pointData.axis, horizontal.labels, point, getLabelCheckerPosition(x, y, true, canvas)); that._updateLines(horizontal.lines, x, y, rad, true); that._horizontalGroup.attr({ translateY: y - canvas.top }) } if (vertical.lines) { that._updateText(pointData.xValue, pointData.axis, vertical.labels, point, getLabelCheckerPosition(x, y, false, canvas)); that._updateLines(vertical.lines, x, y, rad, false); that._verticalGroup.attr({ translateX: x - canvas.left }) } } else { that.hide() } } }; exports.Crosshair = Crosshair }, /*!***********************************************!*\ !*** ./js/viz/chart_components/scroll_bar.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, MIN_SCROLL_BAR_SIZE = 2, translator2DModule = __webpack_require__( /*! ../translators/translator2d */ 571), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), pointerEvents = __webpack_require__( /*! ../../events/pointer */ 76), isDefined = commonUtils.isDefined, _min = Math.min, _max = Math.max; var ScrollBar = function(renderer, group) { this._translator = new translator2DModule.Translator2D({}, {}, {}); this._scroll = renderer.rect().append(group); this._addEvents() }; function _getXCoord(canvas, pos, offset, width) { var x = 0; if ("right" === pos) { x = canvas.width - canvas.right + offset } else { if ("left" === pos) { x = canvas.left - offset - width } } return x } function _getYCoord(canvas, pos, offset, width) { var y = 0; if ("top" === pos) { y = canvas.top - offset } else { if ("bottom" === pos) { y = canvas.height - canvas.bottom + width + offset } } return y } ScrollBar.prototype = { _addEvents: function() { var that = this, $scroll = $(that._scroll.element), startPosX = 0, startPosY = 0, scrollChangeHandler = function(e) { var dX = (startPosX - e.pageX) * that._scale, dY = (startPosY - e.pageY) * that._scale; $scroll.trigger(new $.Event("dxc-scroll-move", extend(e, { type: "dxc-scroll-move", pointers: [{ pageX: startPosX + dX, pageY: startPosY + dY }] }))) }; $scroll.on(pointerEvents.down, function(e) { startPosX = e.pageX; startPosY = e.pageY; $scroll.trigger(new $.Event("dxc-scroll-start", { pointers: [{ pageX: startPosX, pageY: startPosY }] })); $(document).on(pointerEvents.move, scrollChangeHandler) }); $(document).on(pointerEvents.up, function() { $(document).off(pointerEvents.move, scrollChangeHandler) }) }, update: function(options) { var that = this, position = options.position, isVertical = options.rotated, defaultPosition = isVertical ? "right" : "top", secondaryPosition = isVertical ? "left" : "bottom"; if (position !== defaultPosition && position !== secondaryPosition) { position = defaultPosition } that._scroll.attr({ rotate: !options.rotated ? -90 : 0, rotateX: 0, rotateY: 0, fill: options.color, width: options.width, opacity: options.opacity }); that._layoutOptions = { width: options.width, offset: options.offset, vertical: isVertical, position: position }; return that }, init: function(range) { var that = this; that._translateWithOffset = "discrete" === range.axisType && !range.stick && 1 || 0; that._translator.update(extend({}, range, { minVisible: null, maxVisible: null, visibleCategories: null }), that._canvas, { isHorizontal: !that._layoutOptions.vertical }); return that }, getOptions: function() { return this._layoutOptions }, setPane: function(panes) { var pane, position = this._layoutOptions.position; if ("left" === position || "top" === position) { pane = panes[0] } else { pane = panes[panes.length - 1] } this.pane = pane.name; return this }, updateSize: function(canvas) { this._canvas = extend({}, canvas); var options = this._layoutOptions, pos = options.position, offset = options.offset, width = options.width; this._scroll.attr({ translateX: _getXCoord(canvas, pos, offset, width), translateY: _getYCoord(canvas, pos, offset, width) }) }, getMultipleAxesSpacing: function() { return 0 }, estimateMargins: function() { return this.getMargins() }, getMargins: function() { var options = this._layoutOptions, margins = { left: 0, top: 0, right: 0, bottom: 0 }; margins[options.position] = options.width + options.offset; return margins }, draw: function() {}, shift: function() {}, hideTitle: function() {}, hideOuterElements: function() {}, setPosition: function(min, max) { var that = this, translator = that._translator, minPoint = isDefined(min) ? translator.translate(min, -that._translateWithOffset) : translator.translate("canvas_position_start"), maxPoint = isDefined(max) ? translator.translate(max, that._translateWithOffset) : translator.translate("canvas_position_end"); that._offset = _min(minPoint, maxPoint); that._scale = translator.getScale(min, max); that._applyPosition(_min(minPoint, maxPoint), _max(minPoint, maxPoint)) }, transform: function(translate, scale) { var translator = this._translator, x = translator.getCanvasVisibleArea().min, dx = x - (x * scale - translate), lx = this._offset + dx / (this._scale * scale); this._applyPosition(lx, lx + translator.canvasLength / (this._scale * scale)) }, dispose: function() { this._scroll.dispose(); this._scroll = this._translator = null }, _applyPosition: function(x1, x2) { var height, that = this, visibleArea = that._translator.getCanvasVisibleArea(); x1 = _max(x1, visibleArea.min); x1 = _min(x1, visibleArea.max); x2 = _min(x2, visibleArea.max); x2 = _max(x2, visibleArea.min); height = Math.abs(x2 - x1); that._scroll.attr({ y: x1, height: height < MIN_SCROLL_BAR_SIZE ? MIN_SCROLL_BAR_SIZE : height }) } }; exports.ScrollBar = ScrollBar }, /*!*************************************************!*\ !*** ./js/viz/chart_components/shutter_zoom.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var dragEvents = __webpack_require__( /*! ../../events/drag */ 110), SHUTTER_EVENTS_NS = ".shutter-zoom", DRAG_START_EVENT_NAME = dragEvents.start + SHUTTER_EVENTS_NS, DRAG_UPDATE_EVENT_NAME = dragEvents.move + SHUTTER_EVENTS_NS, DRAG_END_EVENT_NAME = dragEvents.end + SHUTTER_EVENTS_NS; function getPointerCoord(rootOffset, canvas, rotated, e) { var coord = Math.floor(rotated ? e.pageY - rootOffset.top : e.pageX - rootOffset.left), min = rotated ? canvas.y1 : canvas.x1, max = rotated ? canvas.y2 : canvas.x2; if (coord < min) { coord = min } else { if (coord > max) { coord = max } } return coord } function checkCoords(rootOffset, canvas, e) { var x = e.pageX - rootOffset.left, y = e.pageY - rootOffset.top; return x >= canvas.x1 && x <= canvas.x2 && y >= canvas.y1 && y <= canvas.y2 } function dragStartHandler(ctx) { return function(e) { var offset = ctx.getRootOffset(), canvas = ctx.getCanvas(); if (!checkCoords(offset, canvas, e)) { e.cancel = true; return } ctx.rootOffset = offset; ctx.canvas = canvas; ctx.startCoord = getPointerCoord(offset, canvas, ctx.rotated, e); ctx.triggerStart(); ctx.rect.attr({ x: canvas.x1, y: canvas.y1, width: canvas.width, height: canvas.height }).append(ctx.root) } } function dragHandler(ctx) { return function(e) { var curCoord = getPointerCoord(ctx.rootOffset, ctx.canvas, ctx.rotated, e), attr = {}; ctx.curCoord = curCoord; attr[ctx.rotated ? "y" : "x"] = Math.min(ctx.startCoord, curCoord); attr[ctx.rotated ? "height" : "width"] = Math.abs(ctx.startCoord - curCoord); ctx.rect.attr(attr) } } function dragEndHandler(ctx) { return function(e) { ctx.triggerEnd(); ctx.rect.remove() } } function shutterZoom(options) { var chart = options.chart, renderer = options.renderer, rotated = options.rotated, rect = renderer.rect(0, 0, 0, 0).attr(options.shutterOptions), shutter = { rect: rect, root: renderer.root, rotated: rotated, triggerStart: function() { chart._eventTrigger("zoomStart") }, triggerEnd: function() { var tr = chart._argumentAxes[0].getTranslator(), rangeStart = Math.min(this.startCoord, this.curCoord), rangeEnd = Math.max(this.startCoord, this.curCoord); chart._eventTrigger("zoomEnd", { rangeStart: tr.untranslate(rangeStart), rangeEnd: tr.untranslate(rangeEnd) }) }, dispose: function() { renderer.root.off(SHUTTER_EVENTS_NS); rect.dispose() }, getRootOffset: function() { return renderer.getRootOffset() }, getCanvas: function() { var canvas = chart._canvas, panes = chart.panes, firstPane = panes[0].canvas, lastPane = panes[panes.length - 1].canvas; return { x1: firstPane.left, y1: firstPane.top, x2: canvas.width - lastPane.right, y2: canvas.height - lastPane.bottom, width: canvas.width - firstPane.left - lastPane.right, height: canvas.height - firstPane.top - lastPane.bottom } } }; renderer.root.off(SHUTTER_EVENTS_NS).on(DRAG_START_EVENT_NAME, { direction: rotated ? "vertical" : "horizontal", immediate: true }, dragStartHandler(shutter)).on(DRAG_UPDATE_EVENT_NAME, dragHandler(shutter)).on(DRAG_END_EVENT_NAME, dragEndHandler(shutter)); return shutter } module.exports = { name: "shutter_zoom", init: function() { var options = this.option("shutterZoom") || {}; if (!options.enabled) { return } this._shutterZoom = shutterZoom({ chart: this, renderer: this._renderer, rotated: this.option("rotated"), shutterOptions: options }) }, dispose: function() { this._shutterZoom && this._shutterZoom.dispose() } } }, /*!*****************************!*\ !*** ./js/viz/pie_chart.js ***! \*****************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../core/renderer */ 9), errors = __webpack_require__( /*! ../core/errors */ 7), seriesConsts = __webpack_require__( /*! ./components/consts */ 527), vizUtils = __webpack_require__( /*! ./core/utils */ 509), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, commonUtils = __webpack_require__( /*! ../core/utils/common */ 14), rangeModule = __webpack_require__( /*! ./translators/range */ 564), registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), baseChartModule = __webpack_require__( /*! ./chart_components/base_chart */ 514), BaseChart = baseChartModule.BaseChart, overlapping = baseChartModule.overlapping, seriesSpacing = seriesConsts.pieSeriesSpacing, translator1DModule = __webpack_require__( /*! ./translators/translator1d */ 585), OPTIONS_FOR_REFRESH_SERIES = ["startAngle", "innerRadius", "segmentsDirection", "type"], _extend = extend, _each = $.each, _noop = commonUtils.noop, _getVerticallyShiftedAngularCoords = __webpack_require__( /*! ./core/utils */ 509).getVerticallyShiftedAngularCoords, states = seriesConsts.states, NORMAL_STATE = states.normalMark, LEGEND_ACTIONS = [states.resetItem, states.applyHover, states.applySelected, states.applySelected]; function getLegendItemAction(points) { var state = NORMAL_STATE; points.forEach(function(point) { state |= point.fullState }); return LEGEND_ACTIONS[state] } function correctPercentValue(value) { if (commonUtils.isNumeric(value)) { if (value > 1) { value = 1 } else { if (value < 0) { value = 0 } } } else { value = void 0 } return value } var dxPieChart = BaseChart.inherit({ _setDeprecatedOptions: function() { this.callBase.apply(this, arguments); _extend(this._deprecatedOptions, { "series.innerRadius": { since: "15.2", message: "Use the 'innerRadius' option instead" }, "series.startAngle": { since: "15.2", message: "Use the 'startAngle' option instead" }, "series.segmentsDirection": { since: "15.2", message: "Use the 'segmentsDirection' option instead" }, "series.type": { since: "15.2", message: "Use the 'type' option instead" } }) }, _chartType: "pie", _layoutManagerOptions: function() { return _extend(true, {}, this.callBase(), { piePercentage: correctPercentValue(this._themeManager.getOptions("diameter")), minPiePercentage: correctPercentValue(this._themeManager.getOptions("minDiameter")) }) }, _optionChangesMap: { diameter: "REINIT", minDiameter: "REINIT", sizeGroup: "REINIT" }, _disposeCore: function() { pieSizeEqualizer.remove(this); this.callBase() }, _groupSeries: function() { var series = this.series; this._groupsData = { groups: [{ series: series, valueOptions: { valueType: "numeric" } }], argumentOptions: series[0] && series[0].getOptions() } }, _getArgumentAxis: function() { return null }, _getValueAxis: function() { var translator = (new translator1DModule.Translator1D).setCodomain(360, 0); return { getTranslator: function() { return translator }, setBusinessRange: function(range) { translator.setDomain(range.min, range.max) } } }, _populateBusinessRange: function() { this.businessRanges = this.series.map(function(series) { var range = new rangeModule.Range; range.addRange(series.getRangeData().val); if (!range.isDefined()) { range.setStubData() } series.getValueAxis().setBusinessRange(range); return range }) }, _specialProcessSeries: function() { _each(this.series, function(_, singleSeries) { singleSeries.arrangePoints() }) }, _checkPaneName: function() { return true }, _processSingleSeries: function(singleSeries) { singleSeries.arrangePoints() }, _getLegendTargets: function() { var that = this, itemsByArgument = {}, items = []; that.series.forEach(function(series) { _each(series.pointsByArgument, function(argument, points) { points.forEach(function(point, index) { var key = argument.valueOf().toString() + index; itemsByArgument[key] = itemsByArgument[key] || []; var argumentCount = itemsByArgument[key].push(point); point.index = itemsByArgument[key][argumentCount - 2] ? itemsByArgument[key][argumentCount - 2].index : Object.keys(itemsByArgument).length - 1; point.argumentIndex = index }) }) }); _each(itemsByArgument, function(_, points) { points.forEach(function(point, index) { if (0 === index) { items.push(that._getLegendOptions(point)) } else { if (!items[items.length - 1].visible) { items[items.length - 1].visible = point.isVisible() } } }) }); return items }, _getLayoutTargets: function() { return [{ canvas: this._canvas }] }, _getLayoutSeries: function(series, drawOptions) { var layout, that = this, canvas = that._canvas, drawnLabels = false; layout = that.layoutManager.applyPieChartSeriesLayout(canvas, series, true); series.forEach(function(singleSeries) { singleSeries.correctPosition(layout, canvas); drawnLabels = singleSeries.drawLabelsWOPoints() || drawnLabels }); if (drawnLabels) { layout = that.layoutManager.applyPieChartSeriesLayout(canvas, series, drawOptions.hideLayoutLabels) } series.forEach(function(singleSeries) { singleSeries.hideLabels() }); that._sizeGroupLayout = { x: layout.centerX, y: layout.centerY, radius: layout.radiusOuter, drawOptions: drawOptions }; return layout }, _getLayoutSeriesForEqualPies: function(series, sizeGroupLayout) { var canvas = this._canvas, layout = this.layoutManager.applyEqualPieChartLayout(series, sizeGroupLayout); series.forEach(function(s) { s.correctPosition(layout, canvas) }); return layout }, _updateSeriesDimensions: function(drawOptions) { var innerRad, delta, layout, that = this, visibleSeries = that._getVisibleSeries(), lengthVisibleSeries = visibleSeries.length, sizeGroupLayout = drawOptions.sizeGroupLayout; if (lengthVisibleSeries) { layout = sizeGroupLayout ? that._getLayoutSeriesForEqualPies(visibleSeries, sizeGroupLayout) : that._getLayoutSeries(visibleSeries, drawOptions); delta = (layout.radiusOuter - layout.radiusInner - seriesSpacing * (lengthVisibleSeries - 1)) / lengthVisibleSeries; innerRad = layout.radiusInner; that._setCenter({ x: layout.centerX, y: layout.centerY }); _each(visibleSeries, function(_, singleSeries) { singleSeries.correctRadius({ radiusInner: innerRad, radiusOuter: innerRad + delta }); innerRad += delta + seriesSpacing }) } }, _renderSeries: function(drawOptions, isRotated, isLegendInside) { this._calculateSeriesLayout(drawOptions, isRotated); if (!drawOptions.sizeGroupLayout && this.getSizeGroup()) { pieSizeEqualizer.queue(this); return } this._renderSeriesElements(drawOptions, isRotated, isLegendInside) }, _getLegendCallBack: function() { var that = this, legend = this._legend, items = this._getLegendTargets().map(function(i) { return i.legendData }); return function(target) { items.forEach(function(data) { var points = [], callback = legend.getActionCallback({ index: data.id }); that.series.forEach(function(series) { var seriesPoints = series.getPointsByKeys(data.argument, data.argumentIndex); points.push.apply(points, seriesPoints) }); if (target && target.argument === data.argument && target.argumentIndex === data.argumentIndex) { points.push(target) } callback(getLegendItemAction(points)) }) } }, _adjustSeries: function() { _each(this.series, function(_, singleSeries) { singleSeries.adjustLabels() }) }, _prepareStackPoints: _noop, _resetStackPoints: _noop, _applyExtraSettings: _noop, _resolveLabelOverlappingShift: function() { var that = this, series = that.series, center = that._center; _each(series, function(_, singleSeries) { if ("inside" === singleSeries.getOptions().label.position) { return } var points = singleSeries.getVisiblePoints(), lPoints = [], rPoints = []; $.each(points, function(_, point) { var angle = vizUtils.normalizeAngle(point.middleAngle); (angle <= 90 || angle >= 270 ? rPoints : lPoints).push(point) }); overlapping.resolveLabelOverlappingInOneDirection(lPoints, that._canvas, false, shiftFunction); overlapping.resolveLabelOverlappingInOneDirection(rPoints, that._canvas, false, shiftFunction) }); function shiftFunction(box, length) { return _getVerticallyShiftedAngularCoords(box, -length, center) } }, _setCenter: function(center) { this._center = center }, _disposeSeries: function() { this.callBase.apply(this, arguments); this._abstractSeries = null }, getSeries: function() { errors.log("W0002", "dxPieChart", "getSeries", "15.2", "Use the 'getAllSeries' method instead"); return this.series[0] }, _legendDataField: "point", _legendItemTextField: "argument", _updateLegendPosition: _noop, _renderTrackers: _noop, _trackerType: "PieTracker", _createScrollBar: _noop, _updateAxesLayout: _noop, _applyClipRects: _noop, _appendAdditionalSeriesGroups: _noop, _prepareToRender: _noop, _isLegendInside: _noop, _renderAxes: _noop, _shrinkAxes: _noop, _isRotated: _noop, _seriesPopulatedHandlerCore: _noop, _reinitAxes: _noop, _correctAxes: _noop, _getExtraOptions: function() { var that = this; return { startAngle: that.option("startAngle"), innerRadius: that.option("innerRadius"), segmentsDirection: that.option("segmentsDirection"), type: that.option("type") } }, getSizeGroup: function() { return this._themeManager.getOptions("sizeGroup") }, getSizeGroupLayout: function() { return this._sizeGroupLayout }, setPieSize: function(layout) { var drawOptions = this._sizeGroupLayout.drawOptions; drawOptions.sizeGroupLayout = layout; this._renderSeries(drawOptions, this._isRotated(), this._isLegendInside()) } }); _each(OPTIONS_FOR_REFRESH_SERIES, function(_, name) { dxPieChart.prototype._optionChangesMap[name] = "REFRESH_SERIES_DATA_INIT" }); registerComponent("dxPieChart", dxPieChart); module.exports = dxPieChart; var pieSizeEqualizer = function() { function equalize(group, allPies) { var pies = allPies.filter(function(p) { return p.getSizeGroup() === group }), minRadius = Math.min.apply(null, pies.map(function(p) { return p.getSizeGroupLayout().radius })), layout = pies.filter(function(p) { return p.getSizeGroupLayout().radius === minRadius })[0].getSizeGroupLayout(); pies.forEach(function(p) { p.setPieSize({ x: layout.x, y: layout.y, radius: minRadius }) }) } function removeFromList(list, item) { return list.filter(function(li) { return li !== item }) } function addToList(list, item) { return removeFromList(list, item).concat(item) } var pies = [], timers = {}; return { queue: function(pie) { var group = pie.getSizeGroup(); pies = addToList(pies, pie); clearTimeout(timers[group]); timers[group] = setTimeout(function() { equalize(group, pies) }) }, remove: function(pie) { pies = removeFromList(pies, pie); if (!pies.length) { timers = {} } } } }() }, /*!********************************************!*\ !*** ./js/viz/translators/translator1d.js ***! \********************************************/ function(module, exports) { var _Number = Number; function Translator1D() { this.setDomain(arguments[0], arguments[1]).setCodomain(arguments[2], arguments[3]) } Translator1D.prototype = { constructor: Translator1D, setDomain: function(domain1, domain2) { var that = this; that._domain1 = _Number(domain1); that._domain2 = _Number(domain2); that._domainDelta = that._domain2 - that._domain1; return that }, setCodomain: function(codomain1, codomain2) { var that = this; that._codomain1 = _Number(codomain1); that._codomain2 = _Number(codomain2); that._codomainDelta = that._codomain2 - that._codomain1; return that }, getDomain: function() { return [this._domain1, this._domain2] }, getCodomain: function() { return [this._codomain1, this._codomain2] }, getDomainStart: function() { return this._domain1 }, getDomainEnd: function() { return this._domain2 }, getCodomainStart: function() { return this._codomain1 }, getCodomainEnd: function() { return this._codomain2 }, getDomainRange: function() { return this._domainDelta }, getCodomainRange: function() { return this._codomainDelta }, translate: function(value) { var ratio = (_Number(value) - this._domain1) / this._domainDelta; return 0 <= ratio && ratio <= 1 ? this._codomain1 + ratio * this._codomainDelta : NaN }, adjust: function(value) { var ratio = (_Number(value) - this._domain1) / this._domainDelta, result = NaN; if (ratio < 0) { result = this._domain1 } else { if (ratio > 1) { result = this._domain2 } else { if (0 <= ratio && ratio <= 1) { result = _Number(value) } } } return result } }; exports.Translator1D = Translator1D }, /*!*******************************!*\ !*** ./js/viz/polar_chart.js ***! \*******************************/ function(module, exports, __webpack_require__) { var noop = __webpack_require__( /*! ../core/utils/common */ 14).noop, registerComponent = __webpack_require__( /*! ../core/component_registrator */ 57), extend = __webpack_require__( /*! ../core/utils/extend */ 11).extend, vizUtils = __webpack_require__( /*! ./core/utils */ 509), AdvancedChart = __webpack_require__( /*! ./chart_components/advanced_chart */ 563).AdvancedChart, _noop = noop, DEFAULT_PANE_NAME = "default"; var dxPolarChart = AdvancedChart.inherit({ _chartType: "polar", _createPanes: function() { return [{ name: DEFAULT_PANE_NAME }] }, _checkPaneName: function() { return true }, _getAxisRenderingOptions: function(typeSelector) { var isArgumentAxis = "argumentAxis" === typeSelector, type = isArgumentAxis ? "circular" : "linear", useSpiderWeb = this.option("useSpiderWeb"); if (useSpiderWeb) { type += "Spider" } return { axisType: "polarAxes", drawingType: type } }, _prepareAxisOptions: function(typeSelector, axisOptions) { var isArgumentAxis = "argumentAxis" === typeSelector, themeManager = this._themeManager, axisUserOptions = this.option("argumentAxis"), argumentAxisOptions = themeManager.getOptions("argumentAxis", axisUserOptions) || {}, startAngle = isFinite(argumentAxisOptions.startAngle) ? vizUtils.normalizeAngle(argumentAxisOptions.startAngle) : 0; return { type: this.option("useSpiderWeb") && isArgumentAxis ? "discrete" : axisOptions.type, isHorizontal: true, showCustomBoundaryTicks: isArgumentAxis, startAngle: startAngle, endAngle: startAngle + 360 } }, _optionChangesMap: { useSpiderWeb: "REINIT" }, _getExtraOptions: function() { return { spiderWidget: this.option("useSpiderWeb") } }, _prepareToRender: function() { this._appendAxesGroups(); return {} }, _renderAxes: function(drawOptions) { this._drawAxes(drawOptions) }, _getValueAxis: function() { return this._valueAxes[0] }, _prepareAxesAndDraw: function(drawOptions, panesBorderOptions) { var that = this, valueAxis = that._getValueAxis(), argumentAxis = that._getArgumentAxis(); var canvas = that._calcCanvas(argumentAxis.measureLabels(true)); argumentAxis.draw(canvas); valueAxis.setSpiderTicks(argumentAxis.getSpiderTicks()); valueAxis.draw(canvas) }, _shrinkAxes: function(drawOptions, sizeShortage) { var valueAxis = this._getValueAxis(), argumentAxis = this._getArgumentAxis(); if (sizeShortage.width || sizeShortage.height) { argumentAxis.hideOuterElements(); argumentAxis.updateSize(this._canvas); valueAxis.updateSize(this._canvas) } }, _calcCanvas: function(measure) { var canvas = extend({}, this._canvas); canvas.left += measure.width; canvas.right += measure.width; canvas.top += measure.height; canvas.bottom += measure.height; return canvas }, _getLayoutTargets: function() { return [{ canvas: this._canvas }] }, _getSeriesForPane: function() { return this.series }, _applyExtraSettings: _noop, _updateLegendPosition: _noop, _createScrollBar: _noop, _applyClipRects: _noop, _isRotated: _noop, _getCrosshairOptions: _noop, _isLegendInside: _noop, _processSingleSeries: _noop }); registerComponent("dxPolarChart", dxPolarChart); module.exports = dxPolarChart }, /*!********************************!*\ !*** ./js/viz/linear_gauge.js ***! \********************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./gauges/linear_gauge */ 588) }, /*!***************************************!*\ !*** ./js/viz/gauges/linear_gauge.js ***! \***************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), _max = Math.max, _min = Math.min, _round = Math.round, _each = $.each, registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), dxBaseGauge = __webpack_require__( /*! ./base_gauge */ 589).dxBaseGauge, dxGauge = __webpack_require__( /*! ./common */ 591).dxGauge, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, linearIndicatorsModule = __webpack_require__( /*! ./linear_indicators */ 592), createIndicatorCreator = __webpack_require__( /*! ./common */ 591).createIndicatorCreator, LinearRangeContainer = __webpack_require__( /*! ./linear_range_container */ 594), ThemeManager = __webpack_require__( /*! ./theme_manager */ 596); var dxLinearGauge = dxGauge.inherit({ _rootClass: "dxg-linear-gauge", _factoryMethods: { rangeContainer: "createLinearRangeContainer", indicator: "createLinearIndicator" }, _gridSpacingFactor: 25, _scaleTypes: { type: "xyAxes", drawingType: "linear" }, _getTicksOrientation: function(scaleOptions) { return scaleOptions.isHorizontal ? scaleOptions.verticalOrientation : scaleOptions.horizontalOrientation }, _updateScaleTickIndent: function(scaleOptions) { var orientation, textCorrection, tickCorrection, indentFromTick = scaleOptions.label.indentFromTick, length = scaleOptions.tick.length, textParams = this._scale.measureLabels(), verticalTextCorrection = scaleOptions.isHorizontal ? textParams.height + textParams.y : 0, isIndentPositive = indentFromTick > 0; if (scaleOptions.isHorizontal) { orientation = isIndentPositive ? { center: .5, middle: .5, top: 0, bottom: 1 } : { center: .5, middle: .5, top: 1, bottom: 0 }; tickCorrection = length * orientation[scaleOptions.verticalOrientation]; textCorrection = textParams.y } else { orientation = isIndentPositive ? { center: .5, left: 0, right: 1 } : { center: .5, left: 1, right: 0 }; tickCorrection = length * orientation[scaleOptions.horizontalOrientation]; textCorrection = -textParams.width } scaleOptions.label.indentFromAxis = -indentFromTick + (isIndentPositive ? -tickCorrection + textCorrection : tickCorrection - verticalTextCorrection); this._scale.updateOptions(scaleOptions) }, _shiftScale: function(layout, scaleOptions) { var that = this, canvas = extend({}, that._canvas), isHorizontal = scaleOptions.isHorizontal, scale = that._scale; canvas[isHorizontal ? "left" : "top"] = that._area[isHorizontal ? "startCoord" : "endCoord"]; canvas[isHorizontal ? "right" : "bottom"] = canvas[isHorizontal ? "width" : "height"] - that._area[isHorizontal ? "endCoord" : "startCoord"]; scale.draw(canvas); scale.shift({ left: -layout.x, top: -layout.y }) }, _setupCodomain: function() { var that = this, geometry = that.option("geometry") || {}, vertical = "vertical" === _normalizeEnum(geometry.orientation); that._area = { vertical: vertical, x: 0, y: 0, startCoord: -100, endCoord: 100 }; that._rangeContainer.vertical = vertical }, _getScaleLayoutValue: function() { return this._area[this._area.vertical ? "x" : "y"] }, _getTicksCoefficients: function(options) { var coefs = { inner: 0, outer: 1 }; if (this._area.vertical) { if ("left" === options.horizontalOrientation) { coefs.inner = 1; coefs.outer = 0 } else { if ("center" === options.horizontalOrientation) { coefs.inner = coefs.outer = .5 } } } else { if ("top" === options.verticalOrientation) { coefs.inner = 1; coefs.outer = 0 } else { if ("center" === options.verticalOrientation || "middle" === options.verticalOrientation) { coefs.inner = coefs.outer = .5 } } } return coefs }, _correctScaleIndents: function(result, indentFromTick, textParams) { var vertical = this._area.vertical; if (indentFromTick >= 0) { result.max += indentFromTick + textParams[vertical ? "width" : "height"] } else { result.min -= -indentFromTick + textParams[vertical ? "width" : "height"] } result.indent = textParams[vertical ? "height" : "width"] / 2 }, _measureMainElements: function(elements, scaleMeasurement) { var that = this, x = that._area.x, y = that._area.y, minBound = 1e3, maxBound = 0, indent = 0, scale = that._scale; _each(elements.concat(scale), function(_, element) { var bounds = element.measure ? element.measure({ x: x + element.getOffset(), y: y + element.getOffset() }) : scaleMeasurement; void 0 !== bounds.max && (maxBound = _max(maxBound, bounds.max)); void 0 !== bounds.min && (minBound = _min(minBound, bounds.min)); bounds.indent > 0 && (indent = _max(indent, bounds.indent)) }); return { minBound: minBound, maxBound: maxBound, indent: indent } }, _applyMainLayout: function(elements, scaleMeasurement) { var rect, offset, that = this, measurements = that._measureMainElements(elements, scaleMeasurement), area = that._area; if (area.vertical) { rect = selectRectBySizes(that._innerRect, { width: measurements.maxBound - measurements.minBound }); offset = (rect.left + rect.right) / 2 - (measurements.minBound + measurements.maxBound) / 2; area.startCoord = rect.bottom - measurements.indent; area.endCoord = rect.top + measurements.indent; area.x = _round(area.x + offset) } else { rect = selectRectBySizes(that._innerRect, { height: measurements.maxBound - measurements.minBound }); offset = (rect.top + rect.bottom) / 2 - (measurements.minBound + measurements.maxBound) / 2; area.startCoord = rect.left + measurements.indent; area.endCoord = rect.right - measurements.indent; area.y = _round(area.y + offset) } that._translator.setCodomain(area.startCoord, area.endCoord); that._innerRect = rect }, _getElementLayout: function(offset) { return { x: _round(this._area.x + offset), y: _round(this._area.y + offset) } }, _getApproximateScreenRange: function() { var that = this, area = that._area, s = area.vertical ? that._canvas.height : that._canvas.width; s > area.totalSize && (s = area.totalSize); s = .8 * s; return s }, _getDefaultSize: function() { var geometry = this.option("geometry") || {}; if ("vertical" === geometry.orientation) { return { width: 100, height: 300 } } else { return { width: 300, height: 100 } } }, _factory: objectUtils.clone(dxBaseGauge.prototype._factory) }); function selectRectBySizes(srcRect, sizes, margins) { var step, rect = extend({}, srcRect); margins = margins || {}; if (sizes) { rect.left += margins.left || 0; rect.right -= margins.right || 0; rect.top += margins.top || 0; rect.bottom -= margins.bottom || 0; if (sizes.width > 0) { step = (rect.right - rect.left - sizes.width) / 2; if (step > 0) { rect.left += step; rect.right -= step } } if (sizes.height > 0) { step = (rect.bottom - rect.top - sizes.height) / 2; if (step > 0) { rect.top += step; rect.bottom -= step } } } return rect } dxLinearGauge._TESTS_selectRectBySizes = selectRectBySizes; var indicators = dxLinearGauge.prototype._factory.indicators = {}; dxLinearGauge.prototype._factory.createIndicator = createIndicatorCreator(indicators); indicators._default = linearIndicatorsModule._default; indicators.rectangle = linearIndicatorsModule.rectangle; indicators.rhombus = linearIndicatorsModule.rhombus; indicators.circle = linearIndicatorsModule.circle; indicators.trianglemarker = linearIndicatorsModule.trianglemarker; indicators.textcloud = linearIndicatorsModule.textcloud; indicators.rangebar = linearIndicatorsModule.rangebar; dxLinearGauge.prototype._factory.RangeContainer = LinearRangeContainer; dxLinearGauge.prototype._factory.ThemeManager = ThemeManager.inherit({ _subTheme: "_linear" }); registerComponent("dxLinearGauge", dxLinearGauge); module.exports = dxLinearGauge }, /*!*************************************!*\ !*** ./js/viz/gauges/base_gauge.js ***! \*************************************/ function(module, exports, __webpack_require__) { var _Number = Number, _getAppropriateFormat = __webpack_require__( /*! ../core/utils */ 509).getAppropriateFormat, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, translator1DModule = __webpack_require__( /*! ../translators/translator1d */ 585), _extend = extend, BaseWidget = __webpack_require__( /*! ../core/base_widget */ 515), _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), Tracker = __webpack_require__( /*! ./tracker */ 590), _isString = commonUtils.isString; var dxBaseGauge = BaseWidget.inherit({ _rootClassPrefix: "dxg", _createThemeManager: function() { return new this._factory.ThemeManager }, _setDeprecatedOptions: function() { this.callBase(); _extend(this._deprecatedOptions, { subtitle: { since: "15.2", message: "Use the 'title.subtitle' option instead" }, "title.position": { since: "15.2", message: "Use the 'verticalAlignment' and 'horizontalAlignment' options instead" }, "scale.hideFirstTick": { since: "15.2", message: "The functionality is not more available" }, "scale.hideLastTick": { since: "15.2", message: "The functionality is not more available" }, "scale.hideFirstLabel": { since: "15.2", message: "The functionality is not more available" }, "scale.hideLastLabel": { since: "15.2", message: "The functionality is not more available" }, "scale.majorTick": { since: "15.2", message: "Use the 'tick' option instead" }, "scale.minorTick.showCalculatedTicks": { since: "15.2", message: "The functionality is not more available" }, "scale.minorTick.customTickValues": { since: "15.2", message: "Use the 'customMinorTicks' option instead" }, "scale.minorTick.tickInterval": { since: "15.2", message: "Use the 'minorTickInterval' option instead" }, "scale.label.overlappingBehavior.useAutoArrangement": { since: "17.1", message: "Use the 'scale.label.overlappingBehavior' option instead" }, "scale.label.overlappingBehavior.hideFirstOrLast": { since: "17.1", message: "Use the 'scale.label.hideFirstOrLast' option instead" } }) }, _initCore: function() { var that = this, root = that._renderer.root; that._valueChangingLocker = 0; that._translator = that._factory.createTranslator(); that._initDeltaIndicator(); that._tracker = that._factory.createTracker({ renderer: that._renderer, container: root }); that._setTrackerCallbacks() }, _beginValueChanging: function() { this._resetIsReady(); ++this._valueChangingLocker }, _endValueChanging: function() { if (0 === --this._valueChangingLocker) { this._drawn() } }, _initDeltaIndicator: function() { var that = this, DeltaIndicator = that._DeltaIndicator; if (DeltaIndicator) { that._deltaIndicator = new DeltaIndicator({ renderer: that._renderer, container: that._renderer.root }); that._deltaIndicator.layoutOptions = function() { this.clean(); this.draw(that._getOption("indicator")); var options = this.getLayoutOptions(); this._size = options ? [options.width, options.height] : null; return options && { horizontalAlignment: options.horizontalAlignment || "center", verticalAlignment: options.verticalAlignment || "bottom" } }; that._deltaIndicator.measure = function() { return this._size }; that._deltaIndicator.move = function(rect) { return this.shift(Math.round(rect[0]), Math.round(rect[1])) }; that._layout.add(that._deltaIndicator) } }, _disposeDeltaIndicator: function() { if (this._deltaIndicator) { this._deltaIndicator.clean(); this._deltaIndicator.dispose() } }, _setTrackerCallbacks: function() { var that = this, renderer = that._renderer, tooltip = that._tooltip; that._tracker.setCallbacks({ "tooltip-show": function(target, info) { var tooltipParameters = target.getTooltipParameters(), offset = renderer.getRootOffset(), formatObject = _extend({ value: tooltipParameters.value, valueText: tooltip.formatValue(tooltipParameters.value), color: tooltipParameters.color }, info); return tooltip.show(formatObject, { x: tooltipParameters.x + offset.left, y: tooltipParameters.y + offset.top, offset: tooltipParameters.offset }, { target: info }) }, "tooltip-hide": function() { return tooltip.hide() } }) }, _dispose: function() { this._cleanCore(); this.callBase.apply(this, arguments) }, _disposeCore: function() { var that = this; that._themeManager.dispose(); that._tracker.dispose(); that._disposeDeltaIndicator(); that._translator = that._tracker = null }, _cleanCore: function() { var that = this; that._tracker.deactivate(); that._cleanContent() }, _renderCore: function() { var that = this; if (!that._isValidDomain) { return } that._renderContent(); that._tracker.setTooltipState(that._tooltip.isEnabled()); that._tracker.activate(); that._noAnimation = false; that._debug_rendered && that._debug_rendered() }, _applyChanges: function() { this.callBase.apply(this, arguments); this._resizing = this._noAnimation = false }, _setContentSize: function() { var that = this; that._resizing = that._noAnimation = 2 === that._changes.count(); that.callBase.apply(that, arguments) }, _applySize: function(rect) { var that = this; that._DEBUG_rootRect = rect; that._innerRect = { left: rect[0], top: rect[1], right: rect[2], bottom: rect[3] }; var layoutCache = that._layout._cache; that._cleanCore(); that._renderCore(); that._layout._cache = that._layout._cache || layoutCache; return [rect[0], that._innerRect.top, rect[2], that._innerRect.bottom] }, _initialChanges: ["DOMAIN"], _themeDependentChanges: ["DOMAIN"], _optionChangesMap: { subtitle: "MOSTLY_TOTAL", indicator: "MOSTLY_TOTAL", geometry: "MOSTLY_TOTAL", animation: "MOSTLY_TOTAL", startValue: "DOMAIN", endValue: "DOMAIN" }, _optionChangesOrder: ["DOMAIN", "MOSTLY_TOTAL"], _change_DOMAIN: function() { this._setupDomain() }, _change_MOSTLY_TOTAL: function() { this._applyMostlyTotalChange() }, _setupDomain: function() { var that = this; that._setupDomainCore(); that._isValidDomain = isFinite(1 / (that._translator.getDomain()[1] - that._translator.getDomain()[0])); if (!that._isValidDomain) { that._incidentOccurred("W2301") } that._change(["MOSTLY_TOTAL"]) }, _applyMostlyTotalChange: function() { var that = this; that._setupCodomain(); that._setupAnimationSettings(); that._setupDefaultFormat(); that._change(["LAYOUT"]) }, _setupAnimationSettings: function() { var that = this, option = that.option("animation"); that._animationSettings = null; if (void 0 === option || option) { option = _extend({ enabled: true, duration: 1e3, easing: "easeOutCubic" }, option); if (option.enabled && option.duration > 0) { that._animationSettings = { duration: _Number(option.duration), easing: option.easing } } } that._containerBackgroundColor = that.option("containerBackgroundColor") || that._themeManager.theme().containerBackgroundColor }, _setupDefaultFormat: function() { var domain = this._translator.getDomain(); this._defaultFormatOptions = _getAppropriateFormat(domain[0], domain[1], this._getApproximateScreenRange()) }, _setupDomainCore: null, _calculateSize: null, _cleanContent: null, _renderContent: null, _setupCodomain: null, _getApproximateScreenRange: null, _factory: { createTranslator: function() { return new translator1DModule.Translator1D }, createTracker: function(parameters) { return new Tracker(parameters) } } }); exports.dxBaseGauge = dxBaseGauge; var _format = __webpack_require__( /*! ../core/format */ 530); var formatValue = function(value, options, extra) { options = options || {}; var formatObject, text = _format(value, options); if ("function" === typeof options.customizeText) { formatObject = _extend({ value: value, valueText: text }, extra); return String(options.customizeText.call(formatObject, formatObject)) } return text }; var getSampleText = function(translator, options) { var text1 = formatValue(translator.getDomainStart(), options), text2 = formatValue(translator.getDomainEnd(), options); return text1.length >= text2.length ? text1 : text2 }; exports.formatValue = formatValue; exports.getSampleText = getSampleText; exports.compareArrays = function(array1, array2) { return array1 && array2 && array1.length === array2.length && compareArraysElements(array1, array2) }; function compareArraysElements(array1, array2) { var i, ii = array1.length; for (i = 0; i < ii; ++i) { if (array1[i] !== array2[i]) { return false } } return true } dxBaseGauge.addPlugin(__webpack_require__( /*! ../core/export */ 511).plugin); dxBaseGauge.addPlugin(__webpack_require__( /*! ../core/title */ 558).plugin); dxBaseGauge.addPlugin(__webpack_require__( /*! ../core/tooltip */ 559).plugin); dxBaseGauge.addPlugin(__webpack_require__( /*! ../core/loading_indicator */ 560).plugin); var _setTooltipOptions = dxBaseGauge.prototype._setTooltipOptions; dxBaseGauge.prototype._setTooltipOptions = function() { _setTooltipOptions.apply(this, arguments); this._tracker && this._tracker.setTooltipState(this._tooltip.isEnabled()) }; function processTitleOptions(options) { return _isString(options) ? { text: options } : options || {} } dxBaseGauge.prototype._getTitleOptions = function() { var options, position, that = this, titleOptions = processTitleOptions(that.option("title")); that._suppressDeprecatedWarnings(); titleOptions.subtitle = extend(processTitleOptions(titleOptions.subtitle), processTitleOptions(that.option("subtitle"))); that._resumeDeprecatedWarnings(); options = _extend(true, {}, that._themeManager.theme("title"), titleOptions); if (options.position) { position = _normalizeEnum(options.position).split("-"); options.verticalAlignment = position[0]; options.horizontalAlignment = position[1] } return options } }, /*!**********************************!*\ !*** ./js/viz/gauges/tracker.js ***! \**********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), _abs = Math.abs, Class = __webpack_require__( /*! ../../core/class */ 25), wheelEvent = __webpack_require__( /*! ../../events/core/wheel */ 85), TOOLTIP_SHOW_DELAY = 300, TOOLTIP_HIDE_DELAY = 300, TOOLTIP_TOUCH_SHOW_DELAY = 400, TOOLTIP_TOUCH_HIDE_DELAY = 300; var Tracker = Class.inherit({ ctor: function(parameters) { var debug = __webpack_require__( /*! ../../core/utils/console */ 13).debug; debug.assertParam(parameters, "parameters"); debug.assertParam(parameters.renderer, "parameters.renderer"); debug.assertParam(parameters.container, "parameters.container"); var that = this; that._element = parameters.renderer.g().attr({ "class": "dxg-tracker", stroke: "none", "stroke-width": 0, fill: "#000000", opacity: 1e-4 }).linkOn(parameters.container, { name: "tracker", after: "peripheral" }); that._showTooltipCallback = function() { that._showTooltipTimeout = null; var target = that._tooltipEvent.target, data_target = target["gauge-data-target"], data_info = target["gauge-data-info"]; that._targetEvent = null; if (that._tooltipTarget !== target && that._callbacks["tooltip-show"](data_target, data_info)) { that._tooltipTarget = target } }; that._hideTooltipCallback = function() { that._hideTooltipTimeout = null; that._targetEvent = null; if (that._tooltipTarget) { that._callbacks["tooltip-hide"](); that._tooltipTarget = null } }; that._dispose = function() { clearTimeout(that._showTooltipTimeout); clearTimeout(that._hideTooltipTimeout); that._showTooltipCallback = that._hideTooltipCallback = that._dispose = null }; that._DEBUG_showTooltipTimeoutSet = that._DEBUG_showTooltipTimeoutCleared = that._DEBUG_hideTooltipTimeoutSet = that._DEBUG_hideTooltipTimeoutCleared = 0; that.TOOLTIP_SHOW_DELAY = TOOLTIP_SHOW_DELAY; that.TOOLTIP_HIDE_DELAY = TOOLTIP_HIDE_DELAY; that.TOOLTIP_TOUCH_SHOW_DELAY = TOOLTIP_TOUCH_SHOW_DELAY; that.TOOLTIP_TOUCH_HIDE_DELAY = TOOLTIP_TOUCH_HIDE_DELAY }, dispose: function() { var that = this; that._dispose(); that.deactivate(); that._element.linkOff(); that._element = that._context = that._callbacks = null; return that }, activate: function() { this._element.linkAppend(); return this }, deactivate: function() { this._element.linkRemove().clear(); return this }, attach: function(element, target, info) { element.data({ "gauge-data-target": target, "gauge-data-info": info }).append(this._element); return this }, detach: function(element) { element.remove(); return this }, setTooltipState: function(state) { var data, that = this; that._element.off(tooltipMouseEvents).off(tooltipTouchEvents).off(tooltipMouseWheelEvents); if (state) { data = { tracker: that }; that._element.on(tooltipMouseEvents, data).on(tooltipTouchEvents, data).on(tooltipMouseWheelEvents, data) } return that }, setCallbacks: function(callbacks) { this._callbacks = callbacks; return this }, _showTooltip: function(event, delay) { var that = this; that._hideTooltipTimeout && ++that._DEBUG_hideTooltipTimeoutCleared; clearTimeout(that._hideTooltipTimeout); that._hideTooltipTimeout = null; if (that._tooltipTarget === event.target) { return } clearTimeout(that._showTooltipTimeout); that._tooltipEvent = event; ++that._DEBUG_showTooltipTimeoutSet; that._showTooltipTimeout = setTimeout(that._showTooltipCallback, delay) }, _hideTooltip: function(delay) { var that = this; that._showTooltipTimeout && ++that._DEBUG_showTooltipTimeoutCleared; clearTimeout(that._showTooltipTimeout); that._showTooltipTimeout = null; clearTimeout(that._hideTooltipTimeout); if (delay) { ++that._DEBUG_hideTooltipTimeoutSet; that._hideTooltipTimeout = setTimeout(that._hideTooltipCallback, delay) } else { that._hideTooltipCallback() } } }); var tooltipMouseEvents = { "mouseover.gauge-tooltip": handleTooltipMouseOver, "mouseout.gauge-tooltip": handleTooltipMouseOut }; var tooltipMouseMoveEvents = { "mousemove.gauge-tooltip": handleTooltipMouseMove }; var tooltipMouseWheelEvents = {}; tooltipMouseWheelEvents[wheelEvent.name + ".gauge-tooltip"] = handleTooltipMouseWheel; var tooltipTouchEvents = { "touchstart.gauge-tooltip": handleTooltipTouchStart }; function handleTooltipMouseOver(event) { var tracker = event.data.tracker; tracker._x = event.pageX; tracker._y = event.pageY; tracker._element.off(tooltipMouseMoveEvents).on(tooltipMouseMoveEvents, event.data); tracker._showTooltip(event, TOOLTIP_SHOW_DELAY) } function handleTooltipMouseMove(event) { var tracker = event.data.tracker; if (tracker._showTooltipTimeout && _abs(event.pageX - tracker._x) > 4 || _abs(event.pageY - tracker._y) > 4) { tracker._x = event.pageX; tracker._y = event.pageY; tracker._showTooltip(event, TOOLTIP_SHOW_DELAY) } } function handleTooltipMouseOut(event) { var tracker = event.data.tracker; tracker._element.off(tooltipMouseMoveEvents); tracker._hideTooltip(TOOLTIP_HIDE_DELAY) } function handleTooltipMouseWheel(event) { event.data.tracker._hideTooltip() } var active_touch_tooltip_tracker = null; Tracker._DEBUG_reset = function() { active_touch_tooltip_tracker = null }; function handleTooltipTouchStart(event) { event.preventDefault(); var tracker = active_touch_tooltip_tracker; if (tracker && tracker !== event.data.tracker) { tracker._hideTooltip(TOOLTIP_TOUCH_HIDE_DELAY) } tracker = active_touch_tooltip_tracker = event.data.tracker; tracker._showTooltip(event, TOOLTIP_TOUCH_SHOW_DELAY); tracker._touch = true } function handleTooltipDocumentTouchStart() { var tracker = active_touch_tooltip_tracker; if (tracker) { if (!tracker._touch) { tracker._hideTooltip(TOOLTIP_TOUCH_HIDE_DELAY); active_touch_tooltip_tracker = null } tracker._touch = null } } function handleTooltipDocumentTouchEnd() { var tracker = active_touch_tooltip_tracker; if (tracker) { if (tracker._showTooltipTimeout) { tracker._hideTooltip(TOOLTIP_TOUCH_HIDE_DELAY); active_touch_tooltip_tracker = null } } } $(window.document).on({ "touchstart.gauge-tooltip": handleTooltipDocumentTouchStart, "touchend.gauge-tooltip": handleTooltipDocumentTouchEnd }); module.exports = Tracker }, /*!*********************************!*\ !*** ./js/viz/gauges/common.js ***! \*********************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), dxBaseGauge = __webpack_require__( /*! ./base_gauge */ 589).dxBaseGauge, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _isDefined = commonUtils.isDefined, _isString = commonUtils.isString, _isArray = Array.isArray, _isNumber = commonUtils.isNumeric, rangeModule = __webpack_require__( /*! ../translators/range */ 564), axisModule = __webpack_require__( /*! ../axes/base_axis */ 565), _map = __webpack_require__( /*! ../core/utils */ 509).map, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _compareArrays = __webpack_require__( /*! ./base_gauge */ 589).compareArrays, _isFinite = isFinite, _Number = Number, _min = Math.min, _max = Math.max, _extend = extend, _each = $.each, _noop = commonUtils.noop, SHIFT_ANGLE = 90, OPTION_VALUE = "value", OPTION_SUBVALUES = "subvalues", DEFAULT_MINOR_AXIS_DIVISION_FACTOR = 5, DEFAULT_NUMBER_MULTIPLIERS = [1, 2, 5]; function processValue(value, fallbackValue) { return _isFinite(value) ? _Number(value) : fallbackValue } function parseArrayOfNumbers(arg) { return _isArray(arg) ? arg : _isNumber(arg) ? [arg] : null } exports.dxGauge = dxBaseGauge.inherit({ _initCore: function() { var that = this, renderer = that._renderer; that._setupValue(that.option(OPTION_VALUE)); that.__subvalues = parseArrayOfNumbers(that.option(OPTION_SUBVALUES)); that._setupSubvalues(that.__subvalues); selectMode(that); that.callBase.apply(that, arguments); that._rangeContainer = new that._factory.RangeContainer({ renderer: renderer, container: renderer.root, translator: that._translator, themeManager: that._themeManager }); that._initScale() }, _initScale: function() { var that = this; that._scaleGroup = that._renderer.g().attr({ "class": "dxg-scale" }).linkOn(that._renderer.root, "scale"); that._scale = new axisModule.Axis({ incidentOccurred: that._incidentOccurred, renderer: that._renderer, axesContainerGroup: that._scaleGroup, axisType: that._scaleTypes.type, drawingType: that._scaleTypes.drawingType, widgetClass: "dxg" }) }, _disposeCore: function() { var that = this; that.callBase.apply(that, arguments); that._scale.dispose(); that._scaleGroup.linkOff(); that._rangeContainer.dispose(); that._disposeValueIndicators(); that._scale = that._scaleGroup = that._rangeContainer = null }, _disposeValueIndicators: function() { var that = this; that._valueIndicator && that._valueIndicator.dispose(); that._subvalueIndicatorsSet && that._subvalueIndicatorsSet.dispose(); that._valueIndicator = that._subvalueIndicatorsSet = null }, _setupDomainCore: function() { var that = this, scaleOption = that.option("scale") || {}, startValue = that.option("startValue"), endValue = that.option("endValue"); startValue = _isNumber(startValue) ? _Number(startValue) : _isNumber(scaleOption.startValue) ? _Number(scaleOption.startValue) : 0; endValue = _isNumber(endValue) ? _Number(endValue) : _isNumber(scaleOption.endValue) ? _Number(scaleOption.endValue) : 100; that._baseValue = startValue < endValue ? startValue : endValue; that._translator.setDomain(startValue, endValue) }, _cleanContent: function() { var that = this; that._rangeContainer.clean(); that._cleanValueIndicators() }, _measureScale: function(scaleOptions) { var textParams, layoutValue, result, coefs, innerCoef, outerCoef, that = this, majorTick = scaleOptions.tick, majorTickEnabled = majorTick.visible && majorTick.length > 0 && majorTick.width > 0, minorTick = scaleOptions.minorTick, minorTickEnabled = minorTick.visible && minorTick.length > 0 && minorTick.width > 0, label = scaleOptions.label, indentFromTick = Number(label.indentFromTick); if (!majorTickEnabled && !minorTickEnabled && !label.visible) { return {} } textParams = that._scale.measureLabels(); layoutValue = that._getScaleLayoutValue(); result = { min: layoutValue, max: layoutValue }; coefs = that._getTicksCoefficients(scaleOptions); innerCoef = coefs.inner; outerCoef = coefs.outer; if (majorTickEnabled) { result.min = _min(result.min, layoutValue - innerCoef * majorTick.length); result.max = _max(result.max, layoutValue + outerCoef * majorTick.length) } if (minorTickEnabled) { result.min = _min(result.min, layoutValue - innerCoef * minorTick.length); result.max = _max(result.max, layoutValue + outerCoef * minorTick.length) } label.visible && that._correctScaleIndents(result, indentFromTick, textParams); return result }, _renderContent: function() { var elements, that = this, scaleOptions = that._prepareScaleSettings(); that._rangeContainer.render(_extend(that._getOption("rangeContainer"), { vertical: that._area.vertical })); that._renderScale(scaleOptions); elements = _map([that._rangeContainer].concat(that._prepareValueIndicators()), function(element) { return element && element.enabled ? element : null }); that._applyMainLayout(elements, that._measureScale(scaleOptions)); _each(elements, function(_, element) { element.resize(that._getElementLayout(element.getOffset())) }); that._shiftScale(that._getElementLayout(0), scaleOptions); that._beginValueChanging(); that._updateActiveElements(); that._endValueChanging() }, _prepareScaleSettings: function() { var that = this, scaleOptions = extend(true, {}, that._themeManager.theme("scale"), that.option("scale")), scaleMajorTick = scaleOptions.majorTick, scaleMinorTick = scaleOptions.minorTick, overlappingBehavior = scaleOptions.label.overlappingBehavior, useAutoArrangement = overlappingBehavior.useAutoArrangement; if (_isString(overlappingBehavior)) { overlappingBehavior = { mode: overlappingBehavior } } if (scaleMajorTick) { scaleOptions.tick = _extend(scaleOptions.tick, scaleMajorTick); useAutoArrangement = _isDefined(scaleMajorTick.useTickAutoArrangement) ? scaleMajorTick.useTickAutoArrangement : useAutoArrangement; void 0 !== scaleMajorTick.tickInterval && (scaleOptions.tickInterval = scaleMajorTick.tickInterval); void 0 !== scaleMajorTick.customTickValues && (scaleOptions.customTicks = scaleMajorTick.customTickValues); if (scaleOptions.customTicks) { scaleOptions.tick.showCalculatedTicks = void 0 !== scaleMajorTick.showCalculatedTicks ? scaleMajorTick.showCalculatedTicks : true } else { scaleOptions.tick.showCalculatedTicks = false } } overlappingBehavior.hideFirstTick = scaleOptions.hideFirstTick; overlappingBehavior.hideFirstLabel = scaleOptions.hideFirstLabel; overlappingBehavior.hideLastTick = scaleOptions.hideLastTick; overlappingBehavior.hideLastLabel = scaleOptions.hideLastLabel; if (!_isDefined(overlappingBehavior.hideFirstOrLast)) { overlappingBehavior.hideFirstOrLast = scaleOptions.label.hideFirstOrLast } if (_isDefined(useAutoArrangement)) { overlappingBehavior.mode = useAutoArrangement ? "hide" : "none" } void 0 !== scaleMinorTick.customTickValues && (scaleOptions.customMinorTicks = scaleOptions.minorTick.customTickValues); void 0 !== scaleMinorTick.tickInterval && (scaleOptions.minorTickInterval = scaleOptions.minorTick.tickInterval); if (scaleOptions.customMinorTicks) { scaleMinorTick.showCalculatedTicks = void 0 !== scaleMinorTick.showCalculatedTicks ? scaleMinorTick.showCalculatedTicks : true } else { scaleMinorTick.showCalculatedTicks = false } scaleOptions.label.indentFromAxis = 0; scaleOptions.isHorizontal = !that._area.vertical; scaleOptions.axisDivisionFactor = that._gridSpacingFactor; scaleOptions.minorAxisDivisionFactor = DEFAULT_MINOR_AXIS_DIVISION_FACTOR; scaleOptions.numberMultipliers = DEFAULT_NUMBER_MULTIPLIERS; scaleOptions.tickOrientation = that._getTicksOrientation(scaleOptions); if (scaleOptions.label.useRangeColors) { scaleOptions.label.customizeColor = function() { return that._rangeContainer.getColorForValue(this.value) } } scaleOptions.label.overlappingBehavior = overlappingBehavior; return scaleOptions }, _renderScale: function(scaleOptions) { var that = this, bounds = that._translator.getDomain(), startValue = bounds[0], endValue = bounds[1], angles = that._translator.getCodomain(); scaleOptions.min = startValue; scaleOptions.max = endValue; scaleOptions.startAngle = SHIFT_ANGLE - angles[0]; scaleOptions.endAngle = SHIFT_ANGLE - angles[1]; that._scale.updateOptions(scaleOptions); that._updateScaleTickIndent(scaleOptions); that._scale.setBusinessRange(new rangeModule.Range({ axisType: "continuous", dataType: "numeric", stick: true, minVisible: startValue, maxVisible: endValue, invert: startValue > endValue })); that._scaleGroup.linkAppend(); that._scale.draw(extend({}, that._canvas)) }, _updateIndicatorSettings: function(settings) { var that = this; settings.currentValue = settings.baseValue = _isFinite(that._translator.translate(settings.baseValue)) ? _Number(settings.baseValue) : that._baseValue; settings.vertical = that._area.vertical; if (settings.text && !settings.text.format && !settings.text.precision) { settings.text.format = that._defaultFormatOptions } }, _prepareIndicatorSettings: function(options, defaultTypeField) { var that = this, theme = that._themeManager.theme("valueIndicators"), type = _normalizeEnum(options.type || that._themeManager.theme(defaultTypeField)), settings = _extend(true, {}, theme._default, theme[type], options); settings.type = type; settings.animation = that._animationSettings; settings.containerBackgroundColor = that._containerBackgroundColor; that._updateIndicatorSettings(settings); return settings }, _cleanValueIndicators: function() { this._valueIndicator && this._valueIndicator.clean(); this._subvalueIndicatorsSet && this._subvalueIndicatorsSet.clean() }, _prepareValueIndicators: function() { var that = this; that._prepareValueIndicator(); null !== that.__subvalues && that._prepareSubvalueIndicators(); return [that._valueIndicator, that._subvalueIndicatorsSet] }, _updateActiveElements: function() { this._updateValueIndicator(); this._updateSubvalueIndicators() }, _prepareValueIndicator: function() { var that = this, target = that._valueIndicator, settings = that._prepareIndicatorSettings(that.option("valueIndicator") || {}, "valueIndicatorType"); if (target && target.type !== settings.type) { target.dispose(); target = null } if (!target) { target = that._valueIndicator = that._createIndicator(settings.type, that._renderer.root, "dxg-value-indicator", "value-indicator") } target.render(settings) }, _createSubvalueIndicatorsSet: function() { var that = this, root = that._renderer.root; return new ValueIndicatorsSet({ createIndicator: function(type, i) { return that._createIndicator(type, root, "dxg-subvalue-indicator", "subvalue-indicator", i) }, createPalette: function(palette) { return that._themeManager.createPalette(palette) } }) }, _prepareSubvalueIndicators: function() { var isRecreate, dummy, that = this, target = that._subvalueIndicatorsSet, settings = that._prepareIndicatorSettings(that.option("subvalueIndicator") || {}, "subvalueIndicatorType"); if (!target) { target = that._subvalueIndicatorsSet = that._createSubvalueIndicatorsSet() } isRecreate = settings.type !== target.type; target.type = settings.type; dummy = that._createIndicator(settings.type, that._renderer.root); if (dummy) { dummy.dispose(); target.render(settings, isRecreate) } }, _setupValue: function(value) { this.__value = processValue(value, this.__value) }, _setupSubvalues: function(subvalues) { var i, ii, list, vals = void 0 === subvalues ? this.__subvalues : parseArrayOfNumbers(subvalues); if (null === vals) { return } for (i = 0, ii = vals.length, list = []; i < ii; ++i) { list.push(processValue(vals[i], this.__subvalues[i])) } this.__subvalues = list }, _updateValueIndicator: function() { var that = this; that._valueIndicator && that._valueIndicator.value(that.__value, that._noAnimation) }, _updateSubvalueIndicators: function() { var that = this; that._subvalueIndicatorsSet && that._subvalueIndicatorsSet.values(that.__subvalues, that._noAnimation) }, value: function(arg) { if (void 0 !== arg) { this._changeValue(arg); return this } return this.__value }, subvalues: function(arg) { if (void 0 !== arg) { this._changeSubvalues(arg); return this } return null !== this.__subvalues ? this.__subvalues.slice() : void 0 }, _changeValue: function(value) { var that = this; that._setupValue(value); that._beginValueChanging(); that._updateValueIndicator(); if (that.__value !== that.option(OPTION_VALUE)) { that.option(OPTION_VALUE, that.__value) } that._endValueChanging() }, _changeSubvalues: function(subvalues) { var that = this; if (null !== that.__subvalues) { that._setupSubvalues(subvalues); that._beginValueChanging(); that._updateSubvalueIndicators(); that._endValueChanging() } else { that.__subvalues = parseArrayOfNumbers(subvalues); that._setContentSize(); that._renderContent() } if (!_compareArrays(that.__subvalues, that.option(OPTION_SUBVALUES))) { that.option(OPTION_SUBVALUES, that.__subvalues) } }, _optionChangesMap: { scale: "DOMAIN", rangeContainer: "MOSTLY_TOTAL", valueIndicator: "MOSTLY_TOTAL", subvalueIndicator: "MOSTLY_TOTAL", containerBackgroundColor: "MOSTLY_TOTAL", value: "VALUE", subvalues: "SUBVALUES", valueIndicators: "MOSTLY_TOTAL" }, _customChangesOrder: ["VALUE", "SUBVALUES"], _change_VALUE: function() { this._changeValue(this.option(OPTION_VALUE)) }, _change_SUBVALUES: function() { this._changeSubvalues(this.option(OPTION_SUBVALUES)) }, _applyMainLayout: null, _getElementLayout: null, _createIndicator: function(type, owner, className, trackerType, trackerIndex, _strict) { var that = this, indicator = that._factory.createIndicator({ renderer: that._renderer, translator: that._translator, owner: owner, tracker: that._tracker, className: className }, type, _strict); if (indicator) { indicator.type = type; indicator._trackerInfo = { type: trackerType, index: trackerIndex } } return indicator }, _getApproximateScreenRange: null }); function valueGetter(arg) { return arg ? arg.value : null } function setupValues(that, fieldName, optionItems) { var currentValues = that[fieldName], newValues = _isArray(optionItems) ? _map(optionItems, valueGetter) : [], i = 0, ii = newValues.length, list = []; for (; i < ii; ++i) { list.push(processValue(newValues[i], currentValues[i])) } that[fieldName] = list } function selectMode(gauge) { if (void 0 === gauge.option(OPTION_VALUE) && void 0 === gauge.option(OPTION_SUBVALUES)) { if (void 0 !== gauge.option("valueIndicators")) { disableDefaultMode(gauge); selectHardMode(gauge) } } } function disableDefaultMode(that) { that.value = that.subvalues = _noop; that._setupValue = that._setupSubvalues = that._updateValueIndicator = that._updateSubvalueIndicators = null } function selectHardMode(that) { that._indicatorValues = []; setupValues(that, "_indicatorValues", that.option("valueIndicators")); that._valueIndicators = []; var _applyMostlyTotalChange = that._applyMostlyTotalChange; that._applyMostlyTotalChange = function() { setupValues(this, "_indicatorValues", this.option("valueIndicators")); _applyMostlyTotalChange.call(this) }; that._updateActiveElements = updateActiveElements_hardMode; that._prepareValueIndicators = prepareValueIndicators_hardMode; that._disposeValueIndicators = disposeValueIndicators_hardMode; that._cleanValueIndicators = cleanValueIndicators_hardMode; that.indicatorValue = indicatorValue_hardMode } function updateActiveElements_hardMode() { var that = this; _each(that._valueIndicators, function(_, valueIndicator) { valueIndicator.value(that._indicatorValues[valueIndicator.index], that._noAnimation) }) } function prepareValueIndicators_hardMode() { var ii, that = this, valueIndicators = that._valueIndicators || [], userOptions = that.option("valueIndicators"), optionList = [], i = 0; for (ii = _isArray(userOptions) ? userOptions.length : 0; i < ii; ++i) { optionList.push(userOptions[i]) } for (ii = valueIndicators.length; i < ii; ++i) { optionList.push(null) } var newValueIndicators = []; _each(optionList, function(i, userSettings) { var valueIndicator = valueIndicators[i]; if (!userSettings) { valueIndicator && valueIndicator.dispose(); return } var settings = that._prepareIndicatorSettings(userSettings, "valueIndicatorType"); if (valueIndicator && valueIndicator.type !== settings.type) { valueIndicator.dispose(); valueIndicator = null } if (!valueIndicator) { valueIndicator = that._createIndicator(settings.type, that._renderer.root, "dxg-value-indicator", "value-indicator", i, true) } if (valueIndicator) { valueIndicator.index = i; valueIndicator.render(settings); newValueIndicators.push(valueIndicator) } }); that._valueIndicators = newValueIndicators; return that._valueIndicators } function disposeValueIndicators_hardMode() { _each(this._valueIndicators, function(_, valueIndicator) { valueIndicator.dispose() }); this._valueIndicators = null } function cleanValueIndicators_hardMode() { _each(this._valueIndicators, function(_, valueIndicator) { valueIndicator.clean() }) } function indicatorValue_hardMode(index, value) { return accessPointerValue(this, this._valueIndicators, this._indicatorValues, index, value) } function accessPointerValue(that, pointers, values, index, value) { if (void 0 !== value) { if (void 0 !== values[index]) { values[index] = processValue(value, values[index]); pointers[index] && pointers[index].value(values[index]) } return that } else { return values[index] } } function ValueIndicatorsSet(parameters) { this._parameters = parameters; this._indicators = [] } ValueIndicatorsSet.prototype = { constructor: ValueIndicatorsSet, dispose: function() { var that = this; _each(that._indicators, function(_, indicator) { indicator.dispose() }); that._parameters = that._options = that._indicators = that._colorPalette = that._palette = null; return that }, clean: function() { var that = this; that._sample && that._sample.clean().dispose(); _each(that._indicators, function(_, indicator) { indicator.clean() }); that._sample = that._options = that._palette = null; return that }, render: function(options, isRecreate) { var that = this; that._options = options; that._sample = that._parameters.createIndicator(that.type); that._sample.render(options); that.enabled = that._sample.enabled; that._palette = _isDefined(options.palette) ? that._parameters.createPalette(options.palette) : null; if (that.enabled) { that._generatePalette(that._indicators.length); that._indicators = _map(that._indicators, function(indicator, i) { if (isRecreate) { indicator.dispose(); indicator = that._parameters.createIndicator(that.type, i) } indicator.render(that._getIndicatorOptions(i)); return indicator }) } return that }, getOffset: function() { return _Number(this._options.offset) || 0 }, resize: function(layout) { var that = this; that._layout = layout; _each(that._indicators, function(_, indicator) { indicator.resize(layout) }); return that }, measure: function(layout) { return this._sample.measure(layout) }, _getIndicatorOptions: function(index) { var result = this._options; if (this._colorPalette) { result = _extend({}, result, { color: this._colorPalette[index] }) } return result }, _generatePalette: function(count) { var that = this, colors = null; if (that._palette) { colors = []; that._palette.reset(); var i = 0; for (; i < count; ++i) { colors.push(that._palette.getNextColor()) } } that._colorPalette = colors }, _adjustIndicatorsCount: function(count) { var i, ii, indicator, that = this, indicators = that._indicators, indicatorsLen = indicators.length; if (indicatorsLen > count) { for (i = count, ii = indicatorsLen; i < ii; ++i) { indicators[i].clean().dispose() } that._indicators = indicators.slice(0, count); that._generatePalette(indicators.length) } else { if (indicatorsLen < count) { that._generatePalette(count); for (i = indicatorsLen, ii = count; i < ii; ++i) { indicator = that._parameters.createIndicator(that.type, i); indicator.render(that._getIndicatorOptions(i)).resize(that._layout); indicators.push(indicator) } } } }, values: function(arg, _noAnimation) { var that = this; if (!that.enabled) { return } if (void 0 !== arg) { if (!_isArray(arg)) { arg = _isFinite(arg) ? [Number(arg)] : null } if (arg) { that._adjustIndicatorsCount(arg.length); _each(that._indicators, function(i, indicator) { indicator.value(arg[i], _noAnimation) }) } return that } return _map(that._indicators, function(indicator) { return indicator.value() }) } }; exports.createIndicatorCreator = function(indicators) { return function(parameters, type, _strict) { var indicatorType = indicators[_normalizeEnum(type)] || !_strict && indicators._default; return indicatorType ? new indicatorType(parameters) : null } } }, /*!********************************************!*\ !*** ./js/viz/gauges/linear_indicators.js ***! \********************************************/ function(module, exports, __webpack_require__) { var baseIndicatorsModule = __webpack_require__( /*! ./base_indicators */ 593), BaseIndicator = baseIndicatorsModule.BaseIndicator, BaseTextCloudMarker = baseIndicatorsModule.BaseTextCloudMarker, BaseRangeBar = baseIndicatorsModule.BaseRangeBar, _Number = Number, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum; var SimpleIndicator = BaseIndicator.inherit({ _move: function() { var that = this, delta = that._actualPosition - that._zeroPosition; that._rootElement.move(that.vertical ? 0 : delta, that.vertical ? delta : 0); that._trackerElement && that._trackerElement.move(that.vertical ? 0 : delta, that.vertical ? delta : 0) }, _isEnabled: function() { this.vertical = this._options.vertical; return this._options.length > 0 && this._options.width > 0 }, _isVisible: function() { return true }, _getTrackerSettings: function() { var x1, x2, y1, y2, options = this._options, width = options.width / 2, length = options.length / 2, p = this._zeroPosition; width > 10 || (width = 10); length > 10 || (length = 10); if (this.vertical) { x1 = options.x - length; x2 = options.x + length; y1 = p + width; y2 = p - width } else { x1 = p - width; x2 = p + width; y1 = options.y + length; y2 = options.y - length } return { points: [x1, y1, x1, y2, x2, y2, x2, y1] } }, _render: function() { var that = this; that._zeroPosition = that._translator.getCodomainStart() }, _clear: function() { delete this._element }, measure: function(layout) { var p = this.vertical ? layout.x : layout.y; return { min: p - this._options.length / 2, max: p + this._options.length / 2 } }, getTooltipParameters: function() { var that = this, options = that._options, p = that._actualPosition, parameters = { x: p, y: p, value: that._currentValue, color: options.color, offset: options.width / 2 }; that.vertical ? parameters.x = options.x : parameters.y = options.y; return parameters } }); var rectangle = SimpleIndicator.inherit({ _render: function() { var p, x1, x2, y1, y2, that = this, options = that._options; that.callBase(); p = that._zeroPosition; if (that.vertical) { x1 = options.x - options.length / 2; x2 = options.x + options.length / 2; y1 = p + options.width / 2; y2 = p - options.width / 2 } else { x1 = p - options.width / 2; x2 = p + options.width / 2; y1 = options.y + options.length / 2; y2 = options.y - options.length / 2 } that._element = that._element || that._renderer.path([], "area").append(that._rootElement); that._element.attr({ points: [x1, y1, x1, y2, x2, y2, x2, y1] }) } }); var rhombus = SimpleIndicator.inherit({ _render: function() { var x, y, dx, dy, that = this, options = that._options; that.callBase(); if (that.vertical) { x = options.x; y = that._zeroPosition; dx = options.length / 2 || 0; dy = options.width / 2 || 0 } else { x = that._zeroPosition; y = options.y; dx = options.width / 2 || 0; dy = options.length / 2 || 0 } that._element = that._element || that._renderer.path([], "area").append(that._rootElement); that._element.attr({ points: [x - dx, y, x, y - dy, x + dx, y, x, y + dy] }) } }); var circle = SimpleIndicator.inherit({ _render: function() { var x, y, r, that = this, options = that._options; that.callBase(); if (that.vertical) { x = options.x; y = that._zeroPosition } else { x = that._zeroPosition; y = options.y } r = options.length / 2 || 0; that._element = that._element || that._renderer.circle().append(that._rootElement); that._element.attr({ cx: x, cy: y, r: r }) } }); var triangleMarker = SimpleIndicator.inherit({ _isEnabled: function() { var that = this; that.vertical = that._options.vertical; that._inverted = that.vertical ? "right" === _normalizeEnum(that._options.horizontalOrientation) : "bottom" === _normalizeEnum(that._options.verticalOrientation); return that._options.length > 0 && that._options.width > 0 }, _isVisible: function() { return true }, _render: function() { var x1, x2, y1, y2, that = this, options = that._options, settings = { stroke: "none", "stroke-width": 0, "stroke-linecap": "square" }; that.callBase(); if (that.vertical) { x1 = options.x; y1 = that._zeroPosition; x2 = x1 + _Number(that._inverted ? options.length : -options.length); settings.points = [x1, y1, x2, y1 - options.width / 2, x2, y1 + options.width / 2] } else { y1 = options.y; x1 = that._zeroPosition; y2 = y1 + _Number(that._inverted ? options.length : -options.length); settings.points = [x1, y1, x1 - options.width / 2, y2, x1 + options.width / 2, y2] } if (options.space > 0) { settings["stroke-width"] = Math.min(options.space, options.width / 4) || 0; settings.stroke = settings["stroke-width"] > 0 ? options.containerBackgroundColor || "none" : "none" } that._element = that._element || that._renderer.path([], "area").append(that._rootElement); that._element.attr(settings).sharp() }, _getTrackerSettings: function() { var x1, x2, y1, y2, result, that = this, options = that._options, width = options.width / 2, length = _Number(options.length); width > 10 || (width = 10); length > 20 || (length = 20); if (that.vertical) { x1 = x2 = options.x; x2 = x1 + (that._inverted ? length : -length); y1 = that._zeroPosition + width; y2 = that._zeroPosition - width; result = [x1, y1, x2, y1, x2, y2, x1, y2] } else { y1 = options.y; y2 = y1 + (that._inverted ? length : -length); x1 = that._zeroPosition - width; x2 = that._zeroPosition + width; result = [x1, y1, x1, y2, x2, y2, x2, y1] } return { points: result } }, measure: function(layout) { var minBound, maxBound, that = this, length = _Number(that._options.length); if (that.vertical) { minBound = maxBound = layout.x; if (that._inverted) { maxBound = minBound + length } else { minBound = maxBound - length } } else { minBound = maxBound = layout.y; if (that._inverted) { maxBound = minBound + length } else { minBound = maxBound - length } } return { min: minBound, max: maxBound, indent: that._options.width / 2 } }, getTooltipParameters: function() { var that = this, options = that._options, s = (that._inverted ? options.length : -options.length) / 2, parameters = that.callBase(); that.vertical ? parameters.x += s : parameters.y += s; parameters.offset = options.length / 2; return parameters } }); var textCloud = BaseTextCloudMarker.inherit({ _isEnabled: function() { var that = this; that.vertical = that._options.vertical; that._inverted = that.vertical ? "right" === _normalizeEnum(that._options.horizontalOrientation) : "bottom" === _normalizeEnum(that._options.verticalOrientation); return true }, _isVisible: function() { return true }, _getTextCloudOptions: function() { var type, that = this, x = that._actualPosition, y = that._actualPosition; if (that.vertical) { x = that._options.x; type = that._inverted ? "top-left" : "top-right" } else { y = that._options.y; type = that._inverted ? "right-top" : "right-bottom" } return { x: x, y: y, type: type } }, measure: function(layout) { var minBound, maxBound, indent, that = this, arrowLength = _Number(that._options.arrowLength) || 0; that._measureText(); if (that.vertical) { indent = that._textFullHeight; if (that._inverted) { minBound = layout.x; maxBound = layout.x + arrowLength + that._textFullWidth } else { minBound = layout.x - arrowLength - that._textFullWidth; maxBound = layout.x } } else { indent = that._textFullWidth; if (that._inverted) { minBound = layout.y; maxBound = layout.y + arrowLength + that._textFullHeight } else { minBound = layout.y - arrowLength - that._textFullHeight; maxBound = layout.y } } return { min: minBound, max: maxBound, indent: indent } } }); var rangeBar = BaseRangeBar.inherit({ _isEnabled: function() { var that = this; that.vertical = that._options.vertical; that._inverted = that.vertical ? "right" === _normalizeEnum(that._options.horizontalOrientation) : "bottom" === _normalizeEnum(that._options.verticalOrientation); return that._options.size > 0 }, _isVisible: function() { return true }, _createBarItem: function() { return this._renderer.path([], "area").append(this._rootElement) }, _createTracker: function() { return this._renderer.path([], "area") }, _setBarSides: function() { var minSide, maxSide, that = this, options = that._options, size = _Number(options.size); if (that.vertical) { if (that._inverted) { minSide = options.x; maxSide = options.x + size } else { minSide = options.x - size; maxSide = options.x } } else { if (that._inverted) { minSide = options.y; maxSide = options.y + size } else { minSide = options.y - size; maxSide = options.y } } that._minSide = minSide; that._maxSide = maxSide; that._minBound = minSide; that._maxBound = maxSide }, _getSpace: function() { var options = this._options; return options.space > 0 ? _Number(options.space) : 0 }, _isTextVisible: function() { var textOptions = this._options.text || {}; return textOptions.indent > 0 || textOptions.indent < 0 }, _getTextAlign: function() { return this.vertical ? this._options.text.indent > 0 ? "left" : "right" : "center" }, _setTextItemsSides: function() { var that = this, indent = _Number(that._options.text.indent); if (indent > 0) { that._lineStart = that._maxSide; that._lineEnd = that._maxSide + indent; that._textPosition = that._lineEnd + (that.vertical ? 2 : that._textHeight / 2); that._maxBound = that._textPosition + (that.vertical ? that._textWidth : that._textHeight / 2) } else { if (indent < 0) { that._lineStart = that._minSide; that._lineEnd = that._minSide + indent; that._textPosition = that._lineEnd - (that.vertical ? 2 : that._textHeight / 2); that._minBound = that._textPosition - (that.vertical ? that._textWidth : that._textHeight / 2) } } }, _getPositions: function() { var mainPosition1, mainPosition2, backPosition1, backPosition2, that = this, startPosition = that._startPosition, endPosition = that._endPosition, space = that._space, basePosition = that._basePosition, actualPosition = that._actualPosition; if (startPosition < endPosition) { if (basePosition < actualPosition) { mainPosition1 = basePosition; mainPosition2 = actualPosition } else { mainPosition1 = actualPosition; mainPosition2 = basePosition } backPosition1 = mainPosition1 - space; backPosition2 = mainPosition2 + space } else { if (basePosition > actualPosition) { mainPosition1 = basePosition; mainPosition2 = actualPosition } else { mainPosition1 = actualPosition; mainPosition2 = basePosition } backPosition1 = mainPosition1 + space; backPosition2 = mainPosition2 - space } return { start: startPosition, end: endPosition, main1: mainPosition1, main2: mainPosition2, back1: backPosition1, back2: backPosition2 } }, _buildItemSettings: function(from, to) { var that = this, side1 = that._minSide, side2 = that._maxSide, points = that.vertical ? [side1, from, side1, to, side2, to, side2, from] : [from, side1, from, side2, to, side2, to, side1]; return { points: points } }, _updateTextPosition: function() { var that = this; that._text.attr(that.vertical ? { x: that._textPosition, y: that._actualPosition + that._textVerticalOffset } : { x: that._actualPosition, y: that._textPosition + that._textVerticalOffset }) }, _updateLinePosition: function() { var side1, side2, points, that = this, actualPosition = that._actualPosition; if (that.vertical) { if (that._basePosition >= actualPosition) { side1 = actualPosition; side2 = actualPosition + 2 } else { side1 = actualPosition - 2; side2 = actualPosition } points = [that._lineStart, side1, that._lineStart, side2, that._lineEnd, side2, that._lineEnd, side1] } else { if (that._basePosition <= actualPosition) { side1 = actualPosition - 2; side2 = actualPosition } else { side1 = actualPosition; side2 = actualPosition + 2 } points = [side1, that._lineStart, side1, that._lineEnd, side2, that._lineEnd, side2, that._lineStart] } that._line.attr({ points: points }).sharp() }, _getTooltipPosition: function() { var that = this, crossCenter = (that._minSide + that._maxSide) / 2, alongCenter = (that._basePosition + that._actualPosition) / 2; return that.vertical ? { x: crossCenter, y: alongCenter } : { x: alongCenter, y: crossCenter } }, measure: function(layout) { var minBound, maxBound, indent, that = this, size = _Number(that._options.size), textIndent = _Number(that._options.text.indent); that._measureText(); if (that.vertical) { minBound = maxBound = layout.x; if (that._inverted) { maxBound += size } else { minBound -= size } if (that._hasText) { indent = that._textHeight / 2; if (textIndent > 0) { maxBound += textIndent + that._textWidth } if (textIndent < 0) { minBound += textIndent - that._textWidth } } } else { minBound = maxBound = layout.y; if (that._inverted) { maxBound += size } else { minBound -= size } if (that._hasText) { indent = that._textWidth / 2; if (textIndent > 0) { maxBound += textIndent + that._textHeight } if (textIndent < 0) { minBound += textIndent - that._textHeight } } } return { min: minBound, max: maxBound, indent: indent } } }); exports._default = rangeBar; exports.rectangle = rectangle; exports.rhombus = rhombus; exports.circle = circle; exports.trianglemarker = triangleMarker; exports.textcloud = textCloud; exports.rangebar = rangeBar }, /*!******************************************!*\ !*** ./js/viz/gauges/base_indicators.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, _isFinite = isFinite, _Number = Number, _round = Math.round, baseGaugeModule = __webpack_require__( /*! ./base_gauge */ 589), _formatValue = baseGaugeModule.formatValue, _getSampleText = baseGaugeModule.getSampleText, _patchFontOptions = __webpack_require__( /*! ../core/utils */ 509).patchFontOptions, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, Class = __webpack_require__( /*! ../../core/class */ 25); var BaseElement = Class.inherit({ ctor: function(parameters) { var that = this; $.each(parameters, function(name, value) { that["_" + name] = value }); that._init() }, dispose: function() { var that = this; that._dispose(); $.each(that, function(name) { that[name] = null }); return that }, getOffset: function() { return _Number(this._options.offset) || 0 } }); var BaseIndicator = BaseElement.inherit({ _init: function() { var that = this; that._rootElement = that._createRoot().linkOn(that._owner, { name: "value-indicator", after: "core" }); that._trackerElement = that._createTracker() }, _dispose: function() { this._rootElement.linkOff() }, _setupAnimation: function() { var that = this; if (that._options.animation) { that._animation = { step: function(pos) { that._actualValue = that._animation.start + that._animation.delta * pos; that._actualPosition = that._translator.translate(that._actualValue); that._move() }, duration: that._options.animation.duration > 0 ? _Number(that._options.animation.duration) : 0, easing: that._options.animation.easing } } }, _runAnimation: function(value) { var that = this, animation = that._animation; animation.start = that._actualValue; animation.delta = value - that._actualValue; that._rootElement.animate({ _: 0 }, { step: animation.step, duration: animation.duration, easing: animation.easing }) }, _createRoot: function() { return this._renderer.g().attr({ "class": this._className }) }, _createTracker: function() { return this._renderer.path([], "area") }, _getTrackerSettings: noop, clean: function() { var that = this; that._animation && that._rootElement.stopAnimation(); that._rootElement.linkRemove().clear(); that._clear(); that._tracker.detach(that._trackerElement); that._options = that.enabled = that._animation = null; return that }, render: function(options) { var that = this; that.type = options.type; that._options = options; that._actualValue = that._currentValue = that._translator.adjust(that._options.currentValue); that.enabled = that._isEnabled(); if (that.enabled) { that._setupAnimation(); that._rootElement.attr({ fill: that._options.color }).linkAppend(); that._tracker.attach(that._trackerElement, that, that._trackerInfo) } return that }, resize: function(layout) { var that = this; that._rootElement.clear(); that._clear(); that.visible = that._isVisible(layout); if (that.visible) { extend(that._options, layout); that._actualPosition = that._translator.translate(that._actualValue); that._render(); that._trackerElement.attr(that._getTrackerSettings()); that._move() } return that }, value: function(arg, _noAnimation) { var val, that = this; if (void 0 !== arg) { val = that._translator.adjust(arg); if (that._currentValue !== val && _isFinite(val)) { that._currentValue = val; if (that.visible) { if (that._animation && !_noAnimation) { that._runAnimation(val) } else { that._actualValue = val; that._actualPosition = that._translator.translate(val); that._move() } } } return that } return that._currentValue }, _isEnabled: null, _isVisible: null, _render: null, _clear: null, _move: null }); var COEFFICIENTS_MAP = {}; COEFFICIENTS_MAP["right-bottom"] = COEFFICIENTS_MAP.rb = [0, -1, -1, 0, 0, 1, 1, 0]; COEFFICIENTS_MAP["bottom-right"] = COEFFICIENTS_MAP.br = [-1, 0, 0, -1, 1, 0, 0, 1]; COEFFICIENTS_MAP["left-bottom"] = COEFFICIENTS_MAP.lb = [0, -1, 1, 0, 0, 1, -1, 0]; COEFFICIENTS_MAP["bottom-left"] = COEFFICIENTS_MAP.bl = [1, 0, 0, -1, -1, 0, 0, 1]; COEFFICIENTS_MAP["left-top"] = COEFFICIENTS_MAP.lt = [0, 1, 1, 0, 0, -1, -1, 0]; COEFFICIENTS_MAP["top-left"] = COEFFICIENTS_MAP.tl = [1, 0, 0, 1, -1, 0, 0, -1]; COEFFICIENTS_MAP["right-top"] = COEFFICIENTS_MAP.rt = [0, 1, -1, 0, 0, -1, 1, 0]; COEFFICIENTS_MAP["top-right"] = COEFFICIENTS_MAP.tr = [-1, 0, 0, 1, 1, 0, 0, -1]; function getTextCloudInfo(options) { var tailWidth, tailHeight, x = options.x, y = options.y, type = COEFFICIENTS_MAP[options.type], cloudWidth = options.textWidth + 2 * options.horMargin, cloudHeight = options.textHeight + 2 * options.verMargin, cx = x, cy = y; tailWidth = tailHeight = options.tailLength; if (1 & type[0]) { tailHeight = Math.min(tailHeight, cloudHeight / 3) } else { tailWidth = Math.min(tailWidth, cloudWidth / 3) } return { cx: _round(cx + type[0] * tailWidth + (type[0] + type[2]) * cloudWidth / 2), cy: _round(cy + type[1] * tailHeight + (type[1] + type[3]) * cloudHeight / 2), points: [_round(x), _round(y), _round(x += type[0] * (cloudWidth + tailWidth)), _round(y += type[1] * (cloudHeight + tailHeight)), _round(x += type[2] * cloudWidth), _round(y += type[3] * cloudHeight), _round(x += type[4] * cloudWidth), _round(y += type[5] * cloudHeight), _round(x += type[6] * (cloudWidth - tailWidth)), _round(y += type[7] * (cloudHeight - tailHeight))] } } var BaseTextCloudMarker = BaseIndicator.inherit({ _move: function() { var bBox, info, that = this, textCloudOptions = that._getTextCloudOptions(), text = _formatValue(that._actualValue, that._options.text); that._text.attr({ text: text }); bBox = that._text.getBBox(); info = getTextCloudInfo({ x: textCloudOptions.x, y: textCloudOptions.y, textWidth: bBox.width || text.length * that._textUnitWidth, textHeight: bBox.height || that._textHeight, horMargin: that._options.horizontalOffset, verMargin: that._options.verticalOffset, tailLength: that._options.arrowLength, type: textCloudOptions.type }); that._text.attr({ x: info.cx, y: info.cy + that._textVerticalOffset }); that._cloud.attr({ points: info.points }); that._trackerElement && that._trackerElement.attr({ points: info.points }) }, _measureText: function() { var root, text, bBox, sampleText, that = this; if (!that._textVerticalOffset) { root = that._createRoot().append(that._owner); sampleText = _getSampleText(that._translator, that._options.text); text = that._renderer.text(sampleText, 0, 0).attr({ align: "center" }).css(_patchFontOptions(that._options.text.font)).append(root); bBox = text.getBBox(); root.remove(); that._textVerticalOffset = -bBox.y - bBox.height / 2; that._textWidth = bBox.width; that._textHeight = bBox.height; that._textUnitWidth = that._textWidth / sampleText.length; that._textFullWidth = that._textWidth + 2 * that._options.horizontalOffset; that._textFullHeight = that._textHeight + 2 * that._options.verticalOffset } }, _render: function() { var that = this; that._measureText(); that._cloud = that._cloud || that._renderer.path([], "area").append(that._rootElement); that._text = that._text || that._renderer.text().append(that._rootElement); that._text.attr({ align: "center" }).css(_patchFontOptions(that._options.text.font)) }, _clear: function() { delete this._cloud; delete this._text }, getTooltipParameters: function() { var position = this._getTextCloudOptions(); return { x: position.x, y: position.y, value: this._currentValue, color: this._options.color } } }); var BaseRangeBar = BaseIndicator.inherit({ _measureText: function() { var root, text, bBox, that = this; that._hasText = that._isTextVisible(); if (that._hasText && !that._textVerticalOffset) { root = that._createRoot().append(that._owner); text = that._renderer.text(_getSampleText(that._translator, that._options.text), 0, 0).attr({ "class": "dxg-text", align: "center" }).css(_patchFontOptions(that._options.text.font)).append(root); bBox = text.getBBox(); root.remove(); that._textVerticalOffset = -bBox.y - bBox.height / 2; that._textWidth = bBox.width; that._textHeight = bBox.height } }, _move: function() { var that = this; that._updateBarItemsPositions(); if (that._hasText) { that._text.attr({ text: _formatValue(that._actualValue, that._options.text) }); that._updateTextPosition(); that._updateLinePosition() } }, _updateBarItems: function() { var backgroundColor, spaceColor, that = this, options = that._options, translator = that._translator; that._setBarSides(); that._startPosition = translator.translate(translator.getDomainStart()); that._endPosition = translator.translate(translator.getDomainEnd()); that._basePosition = translator.translate(options.baseValue); that._space = that._getSpace(); backgroundColor = options.backgroundColor || "none"; if ("none" !== backgroundColor && that._space > 0) { spaceColor = options.containerBackgroundColor || "none" } else { that._space = 0; spaceColor = "none" } that._backItem1.attr({ fill: backgroundColor }); that._backItem2.attr({ fill: backgroundColor }); that._spaceItem1.attr({ fill: spaceColor }); that._spaceItem2.attr({ fill: spaceColor }) }, _getSpace: function() { return 0 }, _updateTextItems: function() { var that = this; if (that._hasText) { that._line = that._line || that._renderer.path([], "line").attr({ "class": "dxg-main-bar", "stroke-linecap": "square" }).append(that._rootElement); that._text = that._text || that._renderer.text("", 0, 0).attr({ "class": "dxg-text" }).append(that._rootElement); that._text.attr({ align: that._getTextAlign() }).css(that._getFontOptions()); that._setTextItemsSides() } else { if (that._line) { that._line.remove(); delete that._line } if (that._text) { that._text.remove(); delete that._text } } }, _isTextVisible: function() { return false }, _getTextAlign: function() { return "center" }, _getFontOptions: function() { var options = this._options, font = options.text.font; if (!font || !font.color) { font = extend({}, font, { color: options.color }) } return _patchFontOptions(font) }, _updateBarItemsPositions: function() { var that = this, positions = that._getPositions(); that._backItem1.attr(that._buildItemSettings(positions.start, positions.back1)); that._backItem2.attr(that._buildItemSettings(positions.back2, positions.end)); that._spaceItem1.attr(that._buildItemSettings(positions.back1, positions.main1)); that._spaceItem2.attr(that._buildItemSettings(positions.main2, positions.back2)); that._mainItem.attr(that._buildItemSettings(positions.main1, positions.main2)); that._trackerElement && that._trackerElement.attr(that._buildItemSettings(positions.main1, positions.main2)) }, _render: function() { var that = this; that._measureText(); if (!that._backItem1) { that._backItem1 = that._createBarItem(); that._backItem1.attr({ "class": "dxg-back-bar" }) } if (!that._backItem2) { that._backItem2 = that._createBarItem(); that._backItem2.attr({ "class": "dxg-back-bar" }) } if (!that._spaceItem1) { that._spaceItem1 = that._createBarItem(); that._spaceItem1.attr({ "class": "dxg-space-bar" }) } if (!that._spaceItem2) { that._spaceItem2 = that._createBarItem(); that._spaceItem2.attr({ "class": "dxg-space-bar" }) } if (!that._mainItem) { that._mainItem = that._createBarItem(); that._mainItem.attr({ "class": "dxg-main-bar" }) } that._updateBarItems(); that._updateTextItems() }, _clear: function() { var that = this; delete that._backItem1; delete that._backItem2; delete that._spaceItem1; delete that._spaceItem2; delete that._mainItem; delete that._hasText; delete that._line; delete that._text }, getTooltipParameters: function() { var position = this._getTooltipPosition(); return { x: position.x, y: position.y, value: this._currentValue, color: this._options.color, offset: 0 } } }); exports.BaseElement = BaseElement; exports.BaseIndicator = BaseIndicator; exports.BaseTextCloudMarker = BaseTextCloudMarker; exports.BaseRangeBar = BaseRangeBar; exports.getTextCloudInfo = getTextCloudInfo }, /*!*************************************************!*\ !*** ./js/viz/gauges/linear_range_container.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var BaseRangeContainer = __webpack_require__( /*! ./base_range_container */ 595), _Number = Number, _max = Math.max, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum; var LinearRangeContainer = BaseRangeContainer.inherit({ _processOptions: function() { var that = this; that.vertical = that._options.vertical; that._inner = that._outer = 0; if (that.vertical) { switch (_normalizeEnum(that._options.horizontalOrientation)) { case "left": that._inner = 1; break; case "center": that._inner = that._outer = .5; break; default: that._outer = 1 } } else { switch (_normalizeEnum(that._options.verticalOrientation)) { case "top": that._inner = 1; break; case "center": case "middle": that._inner = that._outer = .5; break; default: that._outer = 1 } } }, _isVisible: function() { return true }, _createRange: function(range, layout) { var points, that = this, inner = that._inner, outer = that._outer, startPosition = that._translator.translate(range.start), endPosition = that._translator.translate(range.end), x = layout.x, y = layout.y, startWidth = range.startWidth, endWidth = range.endWidth; if (that.vertical) { points = [x - startWidth * inner, startPosition, x - endWidth * inner, endPosition, x + endWidth * outer, endPosition, x + startWidth * outer, startPosition] } else { points = [startPosition, y + startWidth * outer, startPosition, y - startWidth * inner, endPosition, y - endWidth * inner, endPosition, y + endWidth * outer] } return that._renderer.path(points, "area") }, measure: function(layout) { var width, result = {}; result.min = result.max = layout[this.vertical ? "x" : "y"]; width = this._options.width; width = _Number(width) || _max(_Number(width.start), _Number(width.end)); result.min -= this._inner * width; result.max += this._outer * width; return result } }); module.exports = LinearRangeContainer }, /*!***********************************************!*\ !*** ./js/viz/gauges/base_range_container.js ***! \***********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), BaseElement = __webpack_require__( /*! ./base_indicators */ 593).BaseElement, _Number = Number, _abs = Math.abs, commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), _isString = commonUtils.isString, _isArray = Array.isArray, _isFinite = isFinite, _each = $.each, _map = $.map; var BaseRangeContainer = BaseElement.inherit({ _init: function() { this._root = this._renderer.g().attr({ "class": "dxg-range-container" }).linkOn(this._container, "range-container") }, _dispose: function() { this._root.linkOff() }, clean: function() { this._root.linkRemove().clear(); this._options = this.enabled = null; return this }, _getRanges: function() { var that = this, options = that._options, translator = that._translator, totalStart = translator.getDomain()[0], totalEnd = translator.getDomain()[1], totalDelta = totalEnd - totalStart, isNotEmptySegment = totalDelta >= 0 ? isNotEmptySegmentAsc : isNotEmptySegmentDesc, subtractSegment = totalDelta >= 0 ? subtractSegmentAsc : subtractSegmentDesc, list = [], ranges = [], backgroundRanges = [{ start: totalStart, end: totalEnd }], threshold = _abs(totalDelta) / 1e4, palette = that._themeManager.createPalette(options.palette, { type: "indicatingSet" }), backgroundColor = _isString(options.backgroundColor) ? options.backgroundColor : "none", width = options.width || {}, startWidth = _Number(width > 0 ? width : width.start), endWidth = _Number(width > 0 ? width : width.end), deltaWidth = endWidth - startWidth; if (void 0 !== options.ranges && !_isArray(options.ranges)) { return null } if (!(startWidth >= 0 && endWidth >= 0 && startWidth + endWidth > 0)) { return null } list = _map(_isArray(options.ranges) ? options.ranges : [], function(rangeOptions, i) { rangeOptions = rangeOptions || {}; var start = translator.adjust(rangeOptions.startValue), end = translator.adjust(rangeOptions.endValue); return _isFinite(start) && _isFinite(end) && isNotEmptySegment(start, end, threshold) ? { start: start, end: end, color: rangeOptions.color, classIndex: i } : null }); _each(list, function(i, item) { var paletteColor = palette.getNextColor(); item.color = _isString(item.color) && item.color || paletteColor || "none"; item.className = "dxg-range dxg-range-" + item.classIndex; delete item.classIndex }); _each(list, function(_, item) { var i, ii, sub, subs, range, newRanges = [], newBackgroundRanges = []; for (i = 0, ii = ranges.length; i < ii; ++i) { range = ranges[i]; subs = subtractSegment(range.start, range.end, item.start, item.end); (sub = subs[0]) && (sub.color = range.color) && (sub.className = range.className) && newRanges.push(sub); (sub = subs[1]) && (sub.color = range.color) && (sub.className = range.className) && newRanges.push(sub) } newRanges.push(item); ranges = newRanges; for (i = 0, ii = backgroundRanges.length; i < ii; ++i) { range = backgroundRanges[i]; subs = subtractSegment(range.start, range.end, item.start, item.end); (sub = subs[0]) && newBackgroundRanges.push(sub); (sub = subs[1]) && newBackgroundRanges.push(sub) } backgroundRanges = newBackgroundRanges }); _each(backgroundRanges, function(_, range) { range.color = backgroundColor; range.className = "dxg-range dxg-background-range"; ranges.push(range) }); _each(ranges, function(_, range) { range.startWidth = (range.start - totalStart) / totalDelta * deltaWidth + startWidth; range.endWidth = (range.end - totalStart) / totalDelta * deltaWidth + startWidth }); return ranges }, render: function(options) { var that = this; that._options = options; that._processOptions(); that._ranges = that._getRanges(); if (that._ranges) { that.enabled = true; that._root.linkAppend() } return that }, resize: function(layout) { var that = this; that._root.clear(); if (that._isVisible(layout)) { _each(that._ranges, function(_, range) { that._createRange(range, layout).attr({ fill: range.color, "class": range.className }).append(that._root) }) } return that }, _processOptions: null, _isVisible: null, _createRange: null, getColorForValue: function(value) { var color = null; _each(this._ranges, function(_, range) { if (range.start <= value && value <= range.end || range.start >= value && value >= range.end) { color = range.color; return false } }); return color } }); function subtractSegmentAsc(segmentStart, segmentEnd, otherStart, otherEnd) { var result; if (otherStart > segmentStart && otherEnd < segmentEnd) { result = [{ start: segmentStart, end: otherStart }, { start: otherEnd, end: segmentEnd }] } else { if (otherStart >= segmentEnd || otherEnd <= segmentStart) { result = [{ start: segmentStart, end: segmentEnd }] } else { if (otherStart <= segmentStart && otherEnd >= segmentEnd) { result = [] } else { if (otherStart > segmentStart) { result = [{ start: segmentStart, end: otherStart }] } else { if (otherEnd < segmentEnd) { result = [{ start: otherEnd, end: segmentEnd }] } } } } } return result } function subtractSegmentDesc(segmentStart, segmentEnd, otherStart, otherEnd) { var result; if (otherStart < segmentStart && otherEnd > segmentEnd) { result = [{ start: segmentStart, end: otherStart }, { start: otherEnd, end: segmentEnd }] } else { if (otherStart <= segmentEnd || otherEnd >= segmentStart) { result = [{ start: segmentStart, end: segmentEnd }] } else { if (otherStart >= segmentStart && otherEnd <= segmentEnd) { result = [] } else { if (otherStart < segmentStart) { result = [{ start: segmentStart, end: otherStart }] } else { if (otherEnd > segmentEnd) { result = [{ start: otherEnd, end: segmentEnd }] } } } } } return result } function isNotEmptySegmentAsc(start, end, threshold) { return end - start >= threshold } function isNotEmptySegmentDesc(start, end, threshold) { return start - end >= threshold } module.exports = BaseRangeContainer }, /*!****************************************!*\ !*** ./js/viz/gauges/theme_manager.js ***! \****************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _extend = extend, BaseThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager; var ThemeManager = BaseThemeManager.inherit({ _themeSection: "gauge", _fontFields: ["scale.label.font", "valueIndicators.rangebar.text.font", "valueIndicators.textcloud.text.font", "title.font", "title.subtitle.font", "tooltip.font", "indicator.text.font", "loadingIndicator.font", "export.font"], _initializeTheme: function() { var subTheme, that = this; if (that._subTheme) { subTheme = _extend(true, {}, that._theme[that._subTheme], that._theme); _extend(true, that._theme, subTheme) } that.callBase.apply(that, arguments) } }); module.exports = ThemeManager }, /*!**********************************!*\ !*** ./js/viz/circular_gauge.js ***! \**********************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./gauges/circular_gauge */ 598) }, /*!*****************************************!*\ !*** ./js/viz/gauges/circular_gauge.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), _isFinite = isFinite, registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, dxBaseGauge = __webpack_require__( /*! ./base_gauge */ 589).dxBaseGauge, dxGauge = __webpack_require__( /*! ./common */ 591).dxGauge, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _normalizeAngle = vizUtils.normalizeAngle, _getCosAndSin = vizUtils.getCosAndSin, circularIndicatorsModule = __webpack_require__( /*! ./circular_indicators */ 599), createIndicatorCreator = __webpack_require__( /*! ./common */ 591).createIndicatorCreator, CircularRangeContainer = __webpack_require__( /*! ./circular_range_container */ 600), ThemeManager = __webpack_require__( /*! ./theme_manager */ 596), _abs = Math.abs, _max = Math.max, _min = Math.min, _round = Math.round, _each = $.each, PI = Math.PI; function getSides(startAngle, endAngle) { var startCosSin = _getCosAndSin(startAngle), endCosSin = _getCosAndSin(endAngle), startCos = startCosSin.cos, startSin = startCosSin.sin, endCos = endCosSin.cos, endSin = endCosSin.sin; return { left: startSin <= 0 && endSin >= 0 || startSin <= 0 && endSin <= 0 && startCos <= endCos || startSin >= 0 && endSin >= 0 && startCos >= endCos ? -1 : _min(startCos, endCos, 0), right: startSin >= 0 && endSin <= 0 || startSin >= 0 && endSin >= 0 && startCos >= endCos || startSin <= 0 && endSin <= 0 && startCos <= endCos ? 1 : _max(startCos, endCos, 0), up: startCos <= 0 && endCos >= 0 || startCos <= 0 && endCos <= 0 && startSin >= endSin || startCos >= 0 && endCos >= 0 && startSin <= endSin ? -1 : -_max(startSin, endSin, 0), down: startCos >= 0 && endCos <= 0 || startCos >= 0 && endCos >= 0 && startSin <= endSin || startCos <= 0 && endCos <= 0 && startSin >= endSin ? 1 : -_min(startSin, endSin, 0) } } var dxCircularGauge = dxGauge.inherit({ _rootClass: "dxg-circular-gauge", _factoryMethods: { rangeContainer: "createCircularRangeContainer", indicator: "createCircularIndicator" }, _gridSpacingFactor: 17, _scaleTypes: { type: "polarAxes", drawingType: "circular" }, _updateScaleTickIndent: function(scaleOptions) { var indentFromTick = scaleOptions.label.indentFromTick, length = scaleOptions.tick.length, textParams = this._scale.measureLabels(), tickCorrection = length; if ("inside" === scaleOptions.orientation) { tickCorrection = 0 } else { if ("center" === scaleOptions.orientation) { tickCorrection = .5 * length } } scaleOptions.label.indentFromAxis = indentFromTick >= 0 ? indentFromTick + tickCorrection : indentFromTick - tickCorrection - _max(textParams.width, textParams.height); this._scale.updateOptions(scaleOptions) }, _setupCodomain: function() { var sides, that = this, geometry = that.option("geometry") || {}, startAngle = geometry.startAngle, endAngle = geometry.endAngle; startAngle = _isFinite(startAngle) ? _normalizeAngle(startAngle) : 225; endAngle = _isFinite(endAngle) ? _normalizeAngle(endAngle) : -45; if (_abs(startAngle - endAngle) < 1) { endAngle -= 360; sides = { left: -1, up: -1, right: 1, down: 1 } } else { startAngle < endAngle && (endAngle -= 360); sides = getSides(startAngle, endAngle) } that._area = { x: 0, y: 0, radius: 100, startCoord: startAngle, endCoord: endAngle, sides: sides }; that._translator.setCodomain(startAngle, endAngle) }, _shiftScale: function(layout) { var centerCoords, scale = this._scale, canvas = scale.getCanvas(); canvas.width = canvas.height = 2 * layout.radius; scale.draw(canvas); centerCoords = scale.getCenter(); scale.shift({ right: layout.x - centerCoords.x, bottom: layout.y - centerCoords.y }) }, _getScaleLayoutValue: function() { return this._area.radius }, _getTicksOrientation: function(scaleOptions) { return scaleOptions.orientation }, _getTicksCoefficients: function(options) { var coefs = { inner: 0, outer: 1 }; if ("inside" === options.orientation) { coefs.inner = 1; coefs.outer = 0 } else { if ("center" === options.orientation) { coefs.inner = coefs.outer = .5 } } return coefs }, _correctScaleIndents: function(result, indentFromTick, textParams) { if (indentFromTick >= 0) { result.horizontalOffset = indentFromTick + textParams.width; result.verticalOffset = indentFromTick + textParams.height } else { result.horizontalOffset = result.verticalOffset = 0; result.min -= -indentFromTick + _max(textParams.width, textParams.height) } result.inverseHorizontalOffset = textParams.width / 2; result.inverseVerticalOffset = textParams.height / 2 }, _measureMainElements: function(elements, scaleMeasurement) { var that = this, radius = that._area.radius, maxRadius = 0, minRadius = 1 / 0, maxHorizontalOffset = 0, maxVerticalOffset = 0, maxInverseHorizontalOffset = 0, maxInverseVerticalOffset = 0, scale = that._scale; _each(elements.concat(scale), function(_, element) { var bounds = element.measure ? element.measure({ radius: radius - element.getOffset() }) : scaleMeasurement; bounds.min > 0 && (minRadius = _min(minRadius, bounds.min)); bounds.max > 0 && (maxRadius = _max(maxRadius, bounds.max)); bounds.horizontalOffset > 0 && (maxHorizontalOffset = _max(maxHorizontalOffset, bounds.max + bounds.horizontalOffset)); bounds.verticalOffset > 0 && (maxVerticalOffset = _max(maxVerticalOffset, bounds.max + bounds.verticalOffset)); bounds.inverseHorizontalOffset > 0 && (maxInverseHorizontalOffset = _max(maxInverseHorizontalOffset, bounds.inverseHorizontalOffset)); bounds.inverseVerticalOffset > 0 && (maxInverseVerticalOffset = _max(maxInverseVerticalOffset, bounds.inverseVerticalOffset)) }); maxHorizontalOffset = _max(maxHorizontalOffset - maxRadius, 0); maxVerticalOffset = _max(maxVerticalOffset - maxRadius, 0); return { minRadius: minRadius, maxRadius: maxRadius, horizontalMargin: maxHorizontalOffset, verticalMargin: maxVerticalOffset, inverseHorizontalMargin: maxInverseHorizontalOffset, inverseVerticalMargin: maxInverseVerticalOffset } }, _applyMainLayout: function(elements, scaleMeasurement) { var x, y, measurements = this._measureMainElements(elements, scaleMeasurement), area = this._area, sides = area.sides, margins = { left: (sides.left < -.1 ? measurements.horizontalMargin : measurements.inverseHorizontalMargin) || 0, right: (sides.right > .1 ? measurements.horizontalMargin : measurements.inverseHorizontalMargin) || 0, top: (sides.up < -.1 ? measurements.verticalMargin : measurements.inverseVerticalMargin) || 0, bottom: (sides.down > .1 ? measurements.verticalMargin : measurements.inverseVerticalMargin) || 0 }, rect = selectRectByAspectRatio(this._innerRect, (sides.down - sides.up) / (sides.right - sides.left), margins), radius = _min(getWidth(rect) / (sides.right - sides.left), getHeight(rect) / (sides.down - sides.up)); radius = radius - measurements.maxRadius + area.radius; x = rect.left - getWidth(rect) * sides.left / (sides.right - sides.left); y = rect.top - getHeight(rect) * sides.up / (sides.down - sides.up); area.x = _round(x); area.y = _round(y); area.radius = radius; rect.left -= margins.left; rect.right += margins.right; rect.top -= margins.top; rect.bottom += margins.bottom; this._innerRect = rect }, _getElementLayout: function(offset) { return { x: this._area.x, y: this._area.y, radius: _round(this._area.radius - offset) } }, _getApproximateScreenRange: function() { var that = this, area = that._area, r = _min(that._canvas.width / (area.sides.right - area.sides.left), that._canvas.height / (area.sides.down - area.sides.up)); r > area.totalRadius && (r = area.totalRadius); r = .8 * r; return -that._translator.getCodomainRange() * r * PI / 180 }, _getDefaultSize: function() { return { width: 300, height: 300 } }, _factory: objectUtils.clone(dxBaseGauge.prototype._factory) }); function getWidth(rect) { return rect.right - rect.left } function getHeight(rect) { return rect.bottom - rect.top } function selectRectByAspectRatio(srcRect, aspectRatio, margins) { var selfAspectRatio, rect = extend({}, srcRect), width = 0, height = 0; margins = margins || {}; if (aspectRatio > 0) { rect.left += margins.left || 0; rect.right -= margins.right || 0; rect.top += margins.top || 0; rect.bottom -= margins.bottom || 0; if (getWidth(rect) > 0 && getHeight(rect) > 0) { selfAspectRatio = getHeight(rect) / getWidth(rect); if (selfAspectRatio > 1) { aspectRatio < selfAspectRatio ? width = getWidth(rect) : height = getHeight(rect) } else { aspectRatio > selfAspectRatio ? height = getHeight(rect) : width = getWidth(rect) } width > 0 || (width = height / aspectRatio); height > 0 || (height = width * aspectRatio); width = (getWidth(rect) - width) / 2; height = (getHeight(rect) - height) / 2; rect.left += width; rect.right -= width; rect.top += height; rect.bottom -= height } else { rect.left = rect.right = (rect.left + rect.right) / 2; rect.top = rect.bottom = (rect.top + rect.bottom) / 2 } } return rect } dxCircularGauge._TESTS_selectRectByAspectRatio = selectRectByAspectRatio; var indicators = dxCircularGauge.prototype._factory.indicators = {}; dxCircularGauge.prototype._factory.createIndicator = createIndicatorCreator(indicators); indicators._default = circularIndicatorsModule._default; indicators.rectangleneedle = circularIndicatorsModule.rectangleneedle; indicators.triangleneedle = circularIndicatorsModule.triangleneedle; indicators.twocolorneedle = circularIndicatorsModule.twocolorneedle; indicators.trianglemarker = circularIndicatorsModule.trianglemarker; indicators.textcloud = circularIndicatorsModule.textcloud; indicators.rangebar = circularIndicatorsModule.rangebar; dxCircularGauge.prototype._factory.RangeContainer = CircularRangeContainer; dxCircularGauge.prototype._factory.ThemeManager = ThemeManager.inherit({ _subTheme: "_circular" }); registerComponent("dxCircularGauge", dxCircularGauge); module.exports = dxCircularGauge }, /*!**********************************************!*\ !*** ./js/viz/gauges/circular_indicators.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var baseIndicatorsModule = __webpack_require__( /*! ./base_indicators */ 593), BaseIndicator = baseIndicatorsModule.BaseIndicator, BaseTextCloudMarker = baseIndicatorsModule.BaseTextCloudMarker, BaseRangeBar = baseIndicatorsModule.BaseRangeBar, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _Number = Number, _getCosAndSin = vizUtils.getCosAndSin, _convertAngleToRendererSpace = vizUtils.convertAngleToRendererSpace; var SimpleIndicator = BaseIndicator.inherit({ _move: function() { var that = this, options = that._options, angle = _convertAngleToRendererSpace(that._actualPosition); that._rootElement.rotate(angle, options.x, options.y); that._trackerElement && that._trackerElement.rotate(angle, options.x, options.y) }, _isEnabled: function() { return this._options.width > 0 }, _isVisible: function(layout) { return layout.radius - _Number(this._options.indentFromCenter) > 0 }, _getTrackerSettings: function() { var options = this._options, x = options.x, y = options.y - (options.radius + _Number(options.indentFromCenter)) / 2, width = options.width / 2, length = (options.radius - _Number(options.indentFromCenter)) / 2; width > 10 || (width = 10); length > 10 || (length = 10); return { points: [x - width, y - length, x - width, y + length, x + width, y + length, x + width, y - length] } }, _renderSpindle: function() { var gapSize, that = this, options = that._options; if (options.spindleSize > 0) { gapSize = _Number(options.spindleGapSize) || 0; if (gapSize > 0) { gapSize = gapSize <= options.spindleSize ? gapSize : _Number(options.spindleSize) } that._spindleOuter = that._spindleOuter || that._renderer.circle().append(that._rootElement); that._spindleInner = that._spindleInner || that._renderer.circle().append(that._rootElement); that._spindleOuter.attr({ "class": "dxg-spindle-border", cx: options.x, cy: options.y, r: options.spindleSize / 2 }); that._spindleInner.attr({ "class": "dxg-spindle-hole", cx: options.x, cy: options.y, r: gapSize / 2, fill: options.containerBackgroundColor }) } }, _render: function() { var that = this; that._renderPointer(); that._renderSpindle() }, _clearSpindle: function() { delete this._spindleOuter; delete this._spindleInner }, _clearPointer: function() { delete this._element }, _clear: function() { this._clearPointer(); this._clearSpindle() }, measure: function(layout) { var result = { max: layout.radius }; if (this._options.indentFromCenter < 0) { result.inverseHorizontalOffset = result.inverseVerticalOffset = -_Number(this._options.indentFromCenter) } return result }, getTooltipParameters: function() { var options = this._options, cosSin = _getCosAndSin(this._actualPosition), r = (options.radius + _Number(options.indentFromCenter)) / 2; return { x: options.x + cosSin.cos * r, y: options.y - cosSin.sin * r, value: this._currentValue, color: options.color, offset: options.width / 2 } } }); var rectangleNeedle = SimpleIndicator.inherit({ _renderPointer: function() { var that = this, options = that._options, y2 = options.y - options.radius, y1 = options.y - _Number(options.indentFromCenter), x1 = options.x - options.width / 2, x2 = x1 + _Number(options.width); that._element = that._element || that._renderer.path([], "area").append(that._rootElement); that._element.attr({ points: [x1, y1, x1, y2, x2, y2, x2, y1] }) } }); var triangleNeedle = SimpleIndicator.inherit({ _renderPointer: function() { var that = this, options = that._options, y2 = options.y - options.radius, y1 = options.y - _Number(options.indentFromCenter), x1 = options.x - options.width / 2, x2 = options.x + options.width / 2; that._element = that._element || that._renderer.path([], "area").append(that._rootElement); that._element.attr({ points: [x1, y1, options.x, y2, x2, y1] }) } }); var twoColorNeedle = SimpleIndicator.inherit({ _renderPointer: function() { var y2, y3, that = this, options = that._options, x1 = options.x - options.width / 2, x2 = options.x + options.width / 2, y4 = options.y - options.radius, y1 = options.y - _Number(options.indentFromCenter), fraction = _Number(options.secondFraction) || 0; if (fraction >= 1) { y2 = y3 = y1 } else { if (fraction <= 0) { y2 = y3 = y4 } else { y3 = y4 + (y1 - y4) * fraction; y2 = y3 + _Number(options.space) } } that._firstElement = that._firstElement || that._renderer.path([], "area").append(that._rootElement); that._spaceElement = that._spaceElement || that._renderer.path([], "area").append(that._rootElement); that._secondElement = that._secondElement || that._renderer.path([], "area").append(that._rootElement); that._firstElement.attr({ points: [x1, y1, x1, y2, x2, y2, x2, y1] }); that._spaceElement.attr({ points: [x1, y2, x1, y3, x2, y3, x2, y2], "class": "dxg-hole", fill: options.containerBackgroundColor }); that._secondElement.attr({ points: [x1, y3, x1, y4, x2, y4, x2, y3], "class": "dxg-part", fill: options.secondColor }) }, _clearPointer: function() { delete this._firstElement; delete this._secondElement; delete this._spaceElement } }); var triangleMarker = SimpleIndicator.inherit({ _isEnabled: function() { return this._options.length > 0 && this._options.width > 0 }, _isVisible: function(layout) { return layout.radius > 0 }, _render: function() { var settings, that = this, options = that._options, x = options.x, y1 = options.y - options.radius, dx = options.width / 2 || 0, y2 = y1 - _Number(options.length); that._element = that._element || that._renderer.path([], "area").append(that._rootElement); settings = { points: [x, y1, x - dx, y2, x + dx, y2], stroke: "none", "stroke-width": 0, "stroke-linecap": "square" }; if (options.space > 0) { settings["stroke-width"] = Math.min(options.space, options.width / 4) || 0; settings.stroke = settings["stroke-width"] > 0 ? options.containerBackgroundColor || "none" : "none" } that._element.attr(settings).sharp() }, _clear: function() { delete this._element }, _getTrackerSettings: function() { var options = this._options, x = options.x, y = options.y - options.radius - options.length / 2, width = options.width / 2, length = options.length / 2; width > 10 || (width = 10); length > 10 || (length = 10); return { points: [x - width, y - length, x - width, y + length, x + width, y + length, x + width, y - length] } }, measure: function(layout) { return { min: layout.radius, max: layout.radius + _Number(this._options.length) } }, getTooltipParameters: function() { var options = this._options, cosSin = _getCosAndSin(this._actualPosition), r = options.radius + options.length / 2, parameters = this.callBase(); parameters.x = options.x + cosSin.cos * r; parameters.y = options.y - cosSin.sin * r; parameters.offset = options.length / 2; return parameters } }); var textCloud = BaseTextCloudMarker.inherit({ _isEnabled: function() { return true }, _isVisible: function(layout) { return layout.radius > 0 }, _getTextCloudOptions: function() { var that = this, cosSin = _getCosAndSin(that._actualPosition), nAngle = vizUtils.normalizeAngle(that._actualPosition); return { x: that._options.x + cosSin.cos * that._options.radius, y: that._options.y - cosSin.sin * that._options.radius, type: nAngle > 270 ? "left-top" : nAngle > 180 ? "top-right" : nAngle > 90 ? "right-bottom" : "bottom-left" } }, measure: function(layout) { var verticalOffset, horizontalOffset, that = this, arrowLength = _Number(that._options.arrowLength) || 0; that._measureText(); verticalOffset = that._textFullHeight + arrowLength; horizontalOffset = that._textFullWidth + arrowLength; return { min: layout.radius, max: layout.radius, horizontalOffset: horizontalOffset, verticalOffset: verticalOffset, inverseHorizontalOffset: horizontalOffset, inverseVerticalOffset: verticalOffset } } }); var rangeBar = BaseRangeBar.inherit({ _isEnabled: function() { return this._options.size > 0 }, _isVisible: function(layout) { return layout.radius - _Number(this._options.size) > 0 }, _createBarItem: function() { return this._renderer.arc().attr({ "stroke-linejoin": "round" }).append(this._rootElement) }, _createTracker: function() { return this._renderer.arc().attr({ "stroke-linejoin": "round" }) }, _setBarSides: function() { var that = this; that._maxSide = that._options.radius; that._minSide = that._maxSide - _Number(that._options.size) }, _getSpace: function() { var options = this._options; return options.space > 0 ? 180 * options.space / options.radius / Math.PI : 0 }, _isTextVisible: function() { var options = this._options.text || {}; return options.indent > 0 }, _setTextItemsSides: function() { var that = this, options = that._options, indent = _Number(options.text.indent); that._lineFrom = options.y - options.radius; that._lineTo = that._lineFrom - indent; that._textRadius = options.radius + indent }, _getPositions: function() { var mainPosition1, mainPosition2, that = this, basePosition = that._basePosition, actualPosition = that._actualPosition; if (basePosition >= actualPosition) { mainPosition1 = basePosition; mainPosition2 = actualPosition } else { mainPosition1 = actualPosition; mainPosition2 = basePosition } return { start: that._startPosition, end: that._endPosition, main1: mainPosition1, main2: mainPosition2, back1: Math.min(mainPosition1 + that._space, that._startPosition), back2: Math.max(mainPosition2 - that._space, that._endPosition) } }, _buildItemSettings: function(from, to) { var that = this; return { x: that._options.x, y: that._options.y, innerRadius: that._minSide, outerRadius: that._maxSide, startAngle: to, endAngle: from } }, _updateTextPosition: function() { var that = this, cosSin = _getCosAndSin(that._actualPosition), x = that._options.x + that._textRadius * cosSin.cos, y = that._options.y - that._textRadius * cosSin.sin; x += cosSin.cos * that._textWidth * .6; y -= cosSin.sin * that._textHeight * .6; that._text.attr({ x: x, y: y + that._textVerticalOffset }) }, _updateLinePosition: function() { var x1, x2, that = this, x = that._options.x; if (that._basePosition > that._actualPosition) { x1 = x - 2; x2 = x } else { if (that._basePosition < that._actualPosition) { x1 = x; x2 = x + 2 } else { x1 = x - 1; x2 = x + 1 } } that._line.attr({ points: [x1, that._lineFrom, x1, that._lineTo, x2, that._lineTo, x2, that._lineFrom] }).rotate(_convertAngleToRendererSpace(that._actualPosition), x, that._options.y).sharp() }, _getTooltipPosition: function() { var that = this, cosSin = _getCosAndSin((that._basePosition + that._actualPosition) / 2), r = (that._minSide + that._maxSide) / 2; return { x: that._options.x + cosSin.cos * r, y: that._options.y - cosSin.sin * r } }, measure: function(layout) { var that = this, result = { min: layout.radius - _Number(that._options.size), max: layout.radius }; that._measureText(); if (that._hasText) { result.max += _Number(that._options.text.indent); result.horizontalOffset = that._textWidth; result.verticalOffset = that._textHeight } return result } }); exports._default = rectangleNeedle; exports.rectangleneedle = rectangleNeedle; exports.triangleneedle = triangleNeedle; exports.twocolorneedle = twoColorNeedle; exports.trianglemarker = triangleMarker; exports.textcloud = textCloud; exports.rangebar = rangeBar }, /*!***************************************************!*\ !*** ./js/viz/gauges/circular_range_container.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var BaseRangeContainer = __webpack_require__( /*! ./base_range_container */ 595), _Number = Number, _max = Math.max, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum; var CircularRangeContainer = BaseRangeContainer.inherit({ _processOptions: function() { var that = this; that._inner = that._outer = 0; switch (_normalizeEnum(that._options.orientation)) { case "inside": that._inner = 1; break; case "center": that._inner = that._outer = .5; break; default: that._outer = 1 } }, _isVisible: function(layout) { var width = this._options.width; width = _Number(width) || _max(_Number(width.start), _Number(width.end)); return layout.radius - this._inner * width > 0 }, _createRange: function(range, layout) { var that = this, width = (range.startWidth + range.endWidth) / 2; return that._renderer.arc(layout.x, layout.y, layout.radius - that._inner * width, layout.radius + that._outer * width, that._translator.translate(range.end), that._translator.translate(range.start)).attr({ "stroke-linejoin": "round" }) }, measure: function(layout) { var width = this._options.width; width = _Number(width) || _max(_Number(width.start), _Number(width.end)); return { min: layout.radius - this._inner * width, max: layout.radius + this._outer * width } } }); module.exports = CircularRangeContainer }, /*!*****************************!*\ !*** ./js/viz/bar_gauge.js ***! \*****************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./gauges/bar_gauge */ 602).dxBarGauge }, /*!************************************!*\ !*** ./js/viz/gauges/bar_gauge.js ***! \************************************/ function(module, exports, __webpack_require__) { var PI_DIV_180 = Math.PI / 180, _abs = Math.abs, _round = Math.round, _floor = Math.floor, _min = Math.min, _max = Math.max, registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), objectUtils = __webpack_require__( /*! ../../core/utils/object */ 27), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, baseGaugeModule = __webpack_require__( /*! ./base_gauge */ 589), dxBaseGauge = baseGaugeModule.dxBaseGauge, _getSampleText = baseGaugeModule.getSampleText, _formatValue = baseGaugeModule.formatValue, _compareArrays = baseGaugeModule.compareArrays, dxCircularGauge = __webpack_require__( /*! ./circular_gauge */ 598), BaseThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager, _isArray = Array.isArray, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _convertAngleToRendererSpace = vizUtils.convertAngleToRendererSpace, _getCosAndSin = vizUtils.getCosAndSin, _patchFontOptions = vizUtils.patchFontOptions, _Number = Number, _isFinite = isFinite, _noop = commonUtils.noop, _extend = extend, OPTION_VALUES = "values"; var dxBarGauge = dxBaseGauge.inherit({ _rootClass: "dxbg-bar-gauge", _initCore: function() { var that = this; that.callBase.apply(that, arguments); that._barsGroup = that._renderer.g().attr({ "class": "dxbg-bars" }).linkOn(that._renderer.root, "bars"); that._values = []; that._context = { renderer: that._renderer, translator: that._translator, tracker: that._tracker, group: that._barsGroup }; that._animateStep = function(pos) { var i, ii, bars = that._bars; for (i = 0, ii = bars.length; i < ii; ++i) { bars[i].animate(pos) } }; that._animateComplete = function() { var i, ii, bars = that._bars; for (i = 0, ii = bars.length; i < ii; ++i) { bars[i].endAnimation() } } }, _disposeCore: function() { var that = this; that._barsGroup.linkOff(); that._barsGroup = that._values = that._context = that._animateStep = that._animateComplete = null; that.callBase.apply(that, arguments) }, _setupDomainCore: function() { var that = this, startValue = that.option("startValue"), endValue = that.option("endValue"); _isFinite(startValue) || (startValue = 0); _isFinite(endValue) || (endValue = 100); that._translator.setDomain(startValue, endValue); that._baseValue = that._translator.adjust(that.option("baseValue")); _isFinite(that._baseValue) || (that._baseValue = startValue < endValue ? startValue : endValue) }, _getDefaultSize: function() { return { width: 300, height: 300 } }, _setupCodomain: dxCircularGauge.prototype._setupCodomain, _getApproximateScreenRange: function() { var that = this, sides = that._area.sides, width = that._canvas.width / (sides.right - sides.left), height = that._canvas.height / (sides.down - sides.up), r = width < height ? width : height; return -that._translator.getCodomainRange() * r * PI_DIV_180 }, _setupAnimationSettings: function() { var that = this; that.callBase.apply(that, arguments); if (that._animationSettings) { that._animationSettings.step = that._animateStep; that._animationSettings.complete = that._animateComplete } }, _cleanContent: function() { var i, ii, that = this; that._barsGroup.linkRemove(); that._animationSettings && that._barsGroup.stopAnimation(); for (i = 0, ii = that._bars ? that._bars.length : 0; i < ii; ++i) { that._bars[i].dispose() } that._palette = that._bars = null }, _renderContent: function() { var text, bBox, that = this, labelOptions = that.option("label"), context = that._context; that._barsGroup.linkAppend(); context.textEnabled = void 0 === labelOptions || labelOptions && (!("visible" in labelOptions) || labelOptions.visible); if (context.textEnabled) { context.textColor = labelOptions && labelOptions.font && labelOptions.font.color || null; labelOptions = _extend(true, {}, that._themeManager.theme().label, labelOptions); context.formatOptions = { format: void 0 !== labelOptions.format ? labelOptions.format : that._defaultFormatOptions, precision: labelOptions.precision, customizeText: labelOptions.customizeText }; context.textOptions = { align: "center" }; context.fontStyles = _patchFontOptions(_extend({}, that._themeManager.theme().label.font, labelOptions.font, { color: null })); that._textIndent = labelOptions.indent > 0 ? _Number(labelOptions.indent) : 0; context.lineWidth = labelOptions.connectorWidth > 0 ? _Number(labelOptions.connectorWidth) : 0; context.lineColor = labelOptions.connectorColor || null; text = that._renderer.text(_getSampleText(that._translator, context.formatOptions), 0, 0).attr(context.textOptions).css(context.fontStyles).append(that._barsGroup); bBox = text.getBBox(); text.remove(); context.textVerticalOffset = -bBox.y - bBox.height / 2; context.textWidth = bBox.width; context.textHeight = bBox.height } dxCircularGauge.prototype._applyMainLayout.call(that); that._renderBars() }, _measureMainElements: function() { var result = { maxRadius: this._area.radius }; if (this._context.textEnabled) { result.horizontalMargin = this._context.textWidth; result.verticalMargin = this._context.textHeight } return result }, _renderBars: function() { var relativeInnerRadius, radius, that = this, options = _extend({}, that._themeManager.theme(), that.option()), area = that._area; that._palette = that._themeManager.createPalette(options.palette, { useHighlight: true }); relativeInnerRadius = options.relativeInnerRadius > 0 && options.relativeInnerRadius < 1 ? _Number(options.relativeInnerRadius) : .1; radius = area.radius; if (that._context.textEnabled) { that._textIndent = _round(_min(that._textIndent, radius / 2)); radius -= that._textIndent } that._outerRadius = _floor(radius); that._innerRadius = _floor(radius * relativeInnerRadius); that._barSpacing = options.barSpacing > 0 ? _Number(options.barSpacing) : 0; _extend(that._context, { backgroundColor: options.backgroundColor, x: area.x, y: area.y, startAngle: area.startCoord, endAngle: area.endCoord, baseAngle: that._translator.translate(that._baseValue) }); that._bars = []; that._updateValues(that.option(OPTION_VALUES)) }, _arrangeBars: function(count) { var spacing, _count, unitOffset, i, that = this, radius = that._outerRadius - that._innerRadius, context = that._context; context.barSize = count > 0 ? _max((radius - (count - 1) * that._barSpacing) / count, 1) : 0; spacing = count > 1 ? _max(_min((radius - count * context.barSize) / (count - 1), that._barSpacing), 0) : 0; _count = _min(_floor((radius + spacing) / context.barSize), count); that._setBarsCount(_count); radius = that._outerRadius; context.textRadius = radius + that._textIndent; that._palette.reset(); unitOffset = context.barSize + spacing; for (i = 0; i < _count; ++i, radius -= unitOffset) { that._bars[i].arrange({ radius: radius, color: that._palette.getNextColor() }) } }, _setBarsCount: function(count) { var i, ii, that = this; if (that._bars.length > count) { for (i = count, ii = that._bars.length; i < ii; ++i) { that._bars[i].dispose() } that._bars.splice(count, ii - count) } else { if (that._bars.length < count) { for (i = that._bars.length, ii = count; i < ii; ++i) { that._bars.push(new BarWrapper(i, that._context)) } } } if (that._bars.length > 0) { if (that._dummyBackground) { that._dummyBackground.dispose(); that._dummyBackground = null } } else { if (!that._dummyBackground) { that._dummyBackground = that._renderer.arc().attr({ "stroke-linejoin": "round" }).append(that._barsGroup) } that._dummyBackground.attr({ x: that._context.x, y: that._context.y, outerRadius: that._outerRadius, innerRadius: that._innerRadius, startAngle: that._context.endAngle, endAngle: that._context.startAngle, fill: that._context.backgroundColor }) } }, _updateBars: function(values) { var i, ii, that = this; for (i = 0, ii = that._bars.length; i < ii; ++i) { that._bars[i].setValue(values[i]) } }, _animateBars: function(values) { var i, that = this, ii = that._bars.length; if (ii > 0) { for (i = 0; i < ii; ++i) { that._bars[i].beginAnimation(values[i]) } that._barsGroup.animate({ _: 0 }, that._animationSettings) } }, _updateValues: function(values) { var i, value, that = this, list = _isArray(values) && values || _isFinite(values) && [values] || [], ii = list.length, barValues = []; that._values.length = ii; for (i = 0; i < ii; ++i) { value = list[i]; that._values[i] = value = _Number(_isFinite(value) ? value : that._values[i]); if (_isFinite(value)) { barValues.push(value) } } that._animationSettings && that._barsGroup.stopAnimation(); that._beginValueChanging(); if (that._bars) { that._arrangeBars(barValues.length); if (that._animationSettings && !that._noAnimation) { that._animateBars(barValues) } else { that._updateBars(barValues) } } if (!that._resizing) { if (!_compareArrays(that._values, that.option(OPTION_VALUES))) { that.option(OPTION_VALUES, that._values) } } that._endValueChanging() }, values: function(arg) { if (void 0 !== arg) { this._updateValues(arg); return this } else { return this._values.slice(0) } }, _optionChangesMap: { backgroundColor: "MOSTLY_TOTAL", relativeInnerRadius: "MOSTLY_TOTAL", barSpacing: "MOSTLY_TOTAL", label: "MOSTLY_TOTAL", palette: "MOSTLY_TOTAL", values: "VALUES" }, _customChangesOrder: ["VALUES"], _change_VALUES: function() { this._updateValues(this.option(OPTION_VALUES)) }, _factory: objectUtils.clone(dxBaseGauge.prototype._factory) }); var BarWrapper = function(index, context) { var that = this; that._context = context; that._background = context.renderer.arc().attr({ "stroke-linejoin": "round", fill: context.backgroundColor }).append(context.group); that._bar = context.renderer.arc().attr({ "stroke-linejoin": "round" }).append(context.group); if (context.textEnabled) { that._line = context.renderer.path([], "line").attr({ "stroke-width": context.lineWidth }).append(context.group); that._text = context.renderer.text().css(context.fontStyles).attr(context.textOptions).append(context.group) } that._tracker = context.renderer.arc().attr({ "stroke-linejoin": "round" }); context.tracker.attach(that._tracker, that, { index: index }); that._index = index; that._angle = context.baseAngle; that._settings = { x: context.x, y: context.y, startAngle: context.baseAngle, endAngle: context.baseAngle } }; _extend(BarWrapper.prototype, { dispose: function() { var that = this; that._background.dispose(); that._bar.dispose(); if (that._context.textEnabled) { that._line.dispose(); that._text.dispose() } that._context.tracker.detach(that._tracker); that._context = that._settings = that._background = that._bar = that._line = that._text = that._tracker = null; return that }, arrange: function(options) { var that = this, context = that._context; that._settings.outerRadius = options.radius; that._settings.innerRadius = options.radius - context.barSize; that._background.attr(_extend({}, that._settings, { startAngle: context.endAngle, endAngle: context.startAngle })); that._bar.attr(that._settings); that._tracker.attr(that._settings); that._color = options.color; that._bar.attr({ fill: options.color }); if (context.textEnabled) { that._line.attr({ points: [context.x, context.y - that._settings.innerRadius, context.x, context.y - context.textRadius], stroke: context.lineColor || options.color }).sharp(); that._text.css({ fill: context.textColor || options.color }) } return that }, getTooltipParameters: function() { var that = this, cosSin = _getCosAndSin((that._angle + that._context.baseAngle) / 2); return { x: _round(that._context.x + (that._settings.outerRadius + that._settings.innerRadius) / 2 * cosSin.cos), y: _round(that._context.y - (that._settings.outerRadius + that._settings.innerRadius) / 2 * cosSin.sin), offset: 0, color: that._color, value: that._value } }, setAngle: function(angle) { var cosSin, that = this; that._angle = angle; setAngles(that._settings, that._context.baseAngle, that._angle); that._bar.attr(that._settings); that._tracker.attr(that._settings); if (that._context.textEnabled) { var text = _formatValue(that._value, that._context.formatOptions, { index: that._index }); that._line.attr({ visibility: "" === text ? "hidden" : null }); that._line.rotate(_convertAngleToRendererSpace(that._angle), that._context.x, that._context.y); cosSin = _getCosAndSin(that._angle); that._text.attr({ text: text, x: that._context.x + (that._context.textRadius + .6 * that._context.textWidth) * cosSin.cos, y: that._context.y - (that._context.textRadius + .6 * that._context.textHeight) * cosSin.sin + that._context.textVerticalOffset }) } return that }, _processValue: function(value) { this._value = this._context.translator.adjust(value); return this._context.translator.translate(this._value) }, setValue: function(value) { return this.setAngle(this._processValue(value)) }, beginAnimation: function(value) { var that = this, angle = this._processValue(value); if (!compareFloats(that._angle, angle)) { that._start = that._angle; that._delta = angle - that._angle; that._tracker.attr({ visibility: "hidden" }); if (that._context.textEnabled) { that._line.attr({ visibility: "hidden" }); that._text.attr({ visibility: "hidden" }) } } else { that.animate = _noop; that.setAngle(that._angle) } }, animate: function(pos) { var that = this; that._angle = that._start + that._delta * pos; setAngles(that._settings, that._context.baseAngle, that._angle); that._bar.attr(that._settings) }, endAnimation: function() { var that = this; if (void 0 !== that._delta) { if (compareFloats(that._angle, that._start + that._delta)) { that._tracker.attr({ visibility: null }); if (that._context.textEnabled) { that._line.attr({ visibility: null }); that._text.attr({ visibility: null }) } that.setAngle(that._angle) } } else { delete that.animate } delete that._start; delete that._delta } }); function setAngles(target, angle1, angle2) { target.startAngle = angle1 < angle2 ? angle1 : angle2; target.endAngle = angle1 < angle2 ? angle2 : angle1 } function compareFloats(value1, value2) { return _abs(value1 - value2) < 1e-4 } dxBarGauge.prototype._factory.ThemeManager = BaseThemeManager.inherit({ _themeSection: "barGauge", _fontFields: ["label.font", "title.font", "tooltip.font", "loadingIndicator.font"] }); registerComponent("dxBarGauge", dxBarGauge); exports.dxBarGauge = dxBarGauge; var __BarWrapper = BarWrapper; exports.BarWrapper = __BarWrapper; exports.stubBarWrapper = function(barWrapperType) { BarWrapper = barWrapperType }; exports.restoreBarWrapper = function() { BarWrapper = __BarWrapper } }, /*!**********************************!*\ !*** ./js/viz/range_selector.js ***! \**********************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./range_selector/range_selector */ 604) }, /*!*************************************************!*\ !*** ./js/viz/range_selector/range_selector.js ***! \*************************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), registerComponent = __webpack_require__( /*! ../../core/component_registrator */ 57), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, vizUtils = __webpack_require__( /*! ../core/utils */ 509), adjustValue = vizUtils.adjustValue, dateUtils = __webpack_require__( /*! ../../core/utils/date */ 63), addInterval = dateUtils.addInterval, dateToMilliseconds = dateUtils.dateToMilliseconds, getSequenceByInterval = dateUtils.getSequenceByInterval, rangeModule = __webpack_require__( /*! ../translators/range */ 564), axisModule = __webpack_require__( /*! ../axes/base_axis */ 565), patchFontOptions = vizUtils.patchFontOptions, parseUtils = __webpack_require__( /*! ../components/parse_utils */ 524), _normalizeEnum = vizUtils.normalizeEnum, formatHelper = __webpack_require__( /*! ../../format_helper */ 66), commonModule = __webpack_require__( /*! ./common */ 605), slidersControllerModule = __webpack_require__( /*! ./sliders_controller */ 606), trackerModule = __webpack_require__( /*! ./tracker */ 609), rangeViewModule = __webpack_require__( /*! ./range_view */ 610), seriesDataSourceModule = __webpack_require__( /*! ./series_data_source */ 611), themeManagerModule = __webpack_require__( /*! ./theme_manager */ 612), tickManagerModule = __webpack_require__( /*! ../axes/base_tick_manager */ 567), log = __webpack_require__( /*! ../../core/errors */ 7).log, _isDefined = commonUtils.isDefined, _isNumber = commonUtils.isNumeric, _isDate = commonUtils.isDate, _max = Math.max, _ceil = Math.ceil, _floor = Math.floor, START_VALUE = "startValue", END_VALUE = "endValue", DATETIME = "datetime", SELECTED_RANGE = "selectedRange", VALUE = "value", DISCRETE = "discrete", SEMIDISCRETE = "semidiscrete", STRING = "string", SELECTED_RANGE_CHANGED = SELECTED_RANGE + "Changed", VALUE_CHANGED = VALUE + "Changed", CONTAINER_BACKGROUND_COLOR = "containerBackgroundColor", SLIDER_MARKER = "sliderMarker", OPTION_BACKGROUND = "background", LOGARITHMIC = "logarithmic", INVISIBLE_POS = -1e3, SEMIDISCRETE_GRID_SPACING_FACTOR = 50, logarithmBase = 10; function calculateMarkerHeight(renderer, value, sliderMarkerOptions) { var formattedText = void 0 === value ? commonModule.consts.emptySliderMarkerText : commonModule.formatValue(value, sliderMarkerOptions), textBBox = getTextBBox(renderer, formattedText, sliderMarkerOptions.font); return _ceil(textBBox.height) + 2 * sliderMarkerOptions.paddingTopBottom + commonModule.consts.pointerSize } function calculateScaleLabelHalfWidth(renderer, value, scaleOptions) { var formattedText = commonModule.formatValue(value, scaleOptions.label), textBBox = getTextBBox(renderer, formattedText, scaleOptions.label.font); return _ceil(textBBox.width / 2) } function parseValue(value) { return { startValue: value[0], endValue: value[1] } } function parseSelectedRange(selectedRange) { return [selectedRange.startValue, selectedRange.endValue] } function parseSliderMarkersPlaceholderSize(placeholderSize) { var placeholderWidthLeft, placeholderWidthRight, placeholderHeight; if (_isNumber(placeholderSize)) { placeholderWidthLeft = placeholderWidthRight = placeholderHeight = placeholderSize } else { if (placeholderSize) { if (_isNumber(placeholderSize.height)) { placeholderHeight = placeholderSize.height } if (_isNumber(placeholderSize.width)) { placeholderWidthLeft = placeholderWidthRight = placeholderSize.width } else { if (placeholderSize.width) { if (_isNumber(placeholderSize.width.left)) { placeholderWidthLeft = placeholderSize.width.left } if (_isNumber(placeholderSize.width.right)) { placeholderWidthRight = placeholderSize.width.right } } } } else { return null } } return { widthLeft: placeholderWidthLeft, widthRight: placeholderWidthRight, height: placeholderHeight } } function calculateIndents(renderer, scale, sliderMarkerOptions, indentOptions) { var leftMarkerHeight, rightMarkerHeight, placeholderHeight, parsedPlaceholderSize, leftScaleLabelWidth = 0, rightScaleLabelWidth = 0, placeholderWidthLeft = 0, placeholderWidthRight = 0; indentOptions = indentOptions || {}; parsedPlaceholderSize = parseSliderMarkersPlaceholderSize(sliderMarkerOptions.placeholderSize); if (parsedPlaceholderSize && void 0 === indentOptions.left && void 0 === indentOptions.right) { placeholderWidthLeft = parsedPlaceholderSize.widthLeft; placeholderWidthRight = parsedPlaceholderSize.widthRight } else { placeholderWidthLeft = indentOptions.left; placeholderWidthRight = indentOptions.right } if (parsedPlaceholderSize && void 0 === sliderMarkerOptions.placeholderHeight) { placeholderHeight = parsedPlaceholderSize.height } else { placeholderHeight = sliderMarkerOptions.placeholderHeight } if (sliderMarkerOptions.visible) { leftMarkerHeight = calculateMarkerHeight(renderer, scale.startValue, sliderMarkerOptions); rightMarkerHeight = calculateMarkerHeight(renderer, scale.endValue, sliderMarkerOptions); if (void 0 === placeholderHeight) { placeholderHeight = _max(leftMarkerHeight, rightMarkerHeight) } } if (scale.label.visible) { leftScaleLabelWidth = calculateScaleLabelHalfWidth(renderer, scale.startValue, scale); rightScaleLabelWidth = calculateScaleLabelHalfWidth(renderer, scale.endValue, scale) } placeholderWidthLeft = void 0 !== placeholderWidthLeft ? placeholderWidthLeft : leftScaleLabelWidth; placeholderWidthRight = (void 0 !== placeholderWidthRight ? placeholderWidthRight : rightScaleLabelWidth) || 1; return { left: placeholderWidthLeft, right: placeholderWidthRight, top: placeholderHeight || 0, bottom: 0 } } function calculateValueType(firstValue, secondValue) { var typeFirstValue = commonUtils.type(firstValue), typeSecondValue = commonUtils.type(secondValue), validType = function(type) { return typeFirstValue === type || typeSecondValue === type }; return validType("date") ? DATETIME : validType("number") ? "numeric" : validType(STRING) ? STRING : "" } function showScaleMarkers(scaleOptions) { return scaleOptions.valueType === DATETIME && scaleOptions.marker.visible } function updateTranslatorRangeInterval(translatorRange, scaleOptions) { var intervalX = scaleOptions.minorTickInterval || scaleOptions.tickInterval; if ("datetime" === scaleOptions.valueType) { intervalX = dateUtils.dateToMilliseconds(intervalX) } translatorRange.addRange({ interval: intervalX }) } function checkLogarithmicOptions(options, defaultLogarithmBase, incidentOccurred) { var logarithmBase; if (!options) { return } logarithmBase = options.logarithmBase; if (options.type === LOGARITHMIC && logarithmBase <= 0 || logarithmBase && !_isNumber(logarithmBase)) { options.logarithmBase = defaultLogarithmBase; incidentOccurred("E2104") } else { if (options.type !== LOGARITHMIC) { options.logarithmBase = void 0 } } } function calculateScaleAreaHeight(renderer, scaleOptions, visibleMarkers) { var textBBox, value = "0", formatObject = { value: 0, valueText: value }, labelScaleOptions = scaleOptions.label, markerScaleOptions = scaleOptions.marker, customizeText = labelScaleOptions.customizeText, placeholderHeight = scaleOptions.placeholderHeight, text = commonUtils.isFunction(customizeText) ? customizeText.call(formatObject, formatObject) : value, visibleLabels = labelScaleOptions.visible; if (placeholderHeight) { return placeholderHeight } else { textBBox = getTextBBox(renderer, text, labelScaleOptions.font); return (visibleLabels ? labelScaleOptions.topIndent + textBBox.height : 0) + (visibleMarkers ? markerScaleOptions.topIndent + markerScaleOptions.separatorHeight : 0) } } function getNextTickInterval(tickInterval, minorTickInterval, isDateType) { if (!tickInterval) { tickInterval = minorTickInterval } else { if (isDateType) { tickInterval = dateUtils.getNextDateUnit(tickInterval) } else { tickInterval += minorTickInterval } } return tickInterval } function calculateTickIntervalsForSemidiscreteScale(scaleOptions, min, max, screenDelta) { var interval, tickCountByInterval, tickCountByScreen, minorTickInterval = scaleOptions.minorTickInterval, tickInterval = scaleOptions.tickInterval, isDateType = "datetime" === scaleOptions.valueType, gridSpacingFactor = scaleOptions.axisDivisionFactor || {}; if (!tickInterval) { do { interval = getNextTickInterval(tickInterval, minorTickInterval, isDateType); if (tickInterval !== interval) { tickInterval = interval } else { break } if (isDateType) { interval = dateToMilliseconds(tickInterval) } tickCountByInterval = _ceil((max - min) / interval); tickCountByScreen = _floor(screenDelta / (gridSpacingFactor[tickInterval] || SEMIDISCRETE_GRID_SPACING_FACTOR)) || 1 } while (interval && tickCountByInterval > tickCountByScreen) } return { tickInterval: tickInterval, minorTickInterval: minorTickInterval, bounds: { minVisible: min, maxVisible: max }, ticks: [] } } function updateTickIntervals(scaleOptions, screenDelta, incidentOccurred, range) { var result, tickManager, ticks, min = _isDefined(range.minVisible) ? range.minVisible : range.min, max = _isDefined(range.maxVisible) ? range.maxVisible : range.max, categoriesInfo = scaleOptions._categoriesInfo; if (scaleOptions.type === SEMIDISCRETE) { result = calculateTickIntervalsForSemidiscreteScale(scaleOptions, min, max, screenDelta) } else { tickManager = new tickManagerModule.TickManager({ axisType: scaleOptions.type, dataType: scaleOptions.valueType }, { min: min, max: max, screenDelta: screenDelta, customTicks: categoriesInfo && categoriesInfo.categories }, { labelOptions: {}, boundCoef: 1, minorTickInterval: scaleOptions.minorTickInterval, tickInterval: scaleOptions.tickInterval, incidentOccurred: incidentOccurred, base: scaleOptions.logarithmBase, showMinorTicks: true, withMinorCorrection: true, stick: false !== range.stick }); ticks = tickManager.getTicks(true); result = { tickInterval: tickManager.getTickInterval(), minorTickInterval: tickManager.getMinorTickInterval(), bounds: tickManager.getTickBounds(), ticks: ticks } } return result } function calculateTranslatorRange(seriesDataSource, scaleOptions) { var minValue, maxValue, isEqualDates, categories, categoriesInfo, rangeForCategories, inverted = false, startValue = scaleOptions.startValue, endValue = scaleOptions.endValue, translatorRange = seriesDataSource ? seriesDataSource.getBoundRange().arg : new rangeModule.Range, isDate = "datetime" === scaleOptions.valueType, minRange = scaleOptions.minRange; if (scaleOptions.type === DISCRETE) { rangeForCategories = new rangeModule.Range({ minVisible: startValue, maxVisible: endValue }); rangeForCategories.addRange(translatorRange); translatorRange = rangeForCategories; categories = seriesDataSource ? seriesDataSource.argCategories : scaleOptions.categories || !seriesDataSource && startValue && endValue && [startValue, endValue]; categories = categories || []; scaleOptions._categoriesInfo = categoriesInfo = vizUtils.getCategoriesInfo(categories, startValue || categories[0], endValue || categories[categories.length - 1]) } if (scaleOptions.type === SEMIDISCRETE) { startValue = scaleOptions.startValue = correctValueByInterval(scaleOptions.startValue, isDate, minRange); endValue = scaleOptions.endValue = correctValueByInterval(scaleOptions.endValue, isDate, minRange); translatorRange.minVisible = correctValueByInterval(translatorRange.minVisible, isDate, minRange); translatorRange.maxVisible = correctValueByInterval(translatorRange.maxVisible, isDate, minRange); translatorRange.min = correctValueByInterval(translatorRange.min, isDate, minRange); translatorRange.max = correctValueByInterval(translatorRange.max, isDate, minRange) } if (_isDefined(startValue) && _isDefined(endValue)) { inverted = categoriesInfo ? categoriesInfo.inverted : startValue > endValue; minValue = categoriesInfo ? categoriesInfo.start : inverted ? endValue : startValue; maxValue = categoriesInfo ? categoriesInfo.end : inverted ? startValue : endValue } else { if (_isDefined(startValue) || _isDefined(endValue)) { minValue = startValue; maxValue = endValue } else { if (categoriesInfo) { minValue = categoriesInfo.start; maxValue = categoriesInfo.end } } } isEqualDates = _isDate(minValue) && _isDate(maxValue) && minValue.getTime() === maxValue.getTime(); if (scaleOptions.type === SEMIDISCRETE || minValue !== maxValue && !isEqualDates) { translatorRange.addRange({ invert: inverted, min: minValue, max: maxValue, minVisible: minValue, maxVisible: maxValue, dataType: scaleOptions.valueType }) } translatorRange.addRange({ categories: !seriesDataSource ? categories : void 0, base: scaleOptions.logarithmBase, axisType: scaleOptions.type }); seriesDataSource && translatorRange.sortCategories(categories); if (!translatorRange.isDefined()) { if (isEqualDates) { scaleOptions.valueType = "numeric" } translatorRange.setStubData(scaleOptions.valueType) } return translatorRange } function startEndNotDefined(start, end) { return !_isDefined(start) || !_isDefined(end) } function getTextBBox(renderer, text, fontOptions) { var textElement = renderer.text(text, INVISIBLE_POS, INVISIBLE_POS).css(patchFontOptions(fontOptions)).append(renderer.root); var textBBox = textElement.getBBox(); textElement.remove(); return textBBox } function getDateMarkerVisibilityChecker(screenDelta) { return function(isDateScale, isMarkerVisible, min, max, tickInterval) { if (isMarkerVisible && isDateScale) { if (tickInterval.years || tickInterval.months >= 6 || screenDelta / SEMIDISCRETE_GRID_SPACING_FACTOR < _ceil((max - min) / dateToMilliseconds("year")) + 1) { isMarkerVisible = false } } return isMarkerVisible } } function updateScaleOptions(scaleOptions, seriesDataSource, translatorRange, tickIntervalsInfo, checkDateMarkerVisibility) { var bounds, isEmptyInterval, intervals, categoriesInfo = scaleOptions._categoriesInfo, isDateTime = scaleOptions.valueType === DATETIME; if (seriesDataSource && !seriesDataSource.isEmpty() && !translatorRange.stubData) { bounds = tickIntervalsInfo.bounds; translatorRange.addRange(bounds); scaleOptions.startValue = translatorRange.invert ? bounds.maxVisible : bounds.minVisible; scaleOptions.endValue = translatorRange.invert ? bounds.minVisible : bounds.maxVisible } scaleOptions.marker.visible = checkDateMarkerVisibility(isDateTime && scaleOptions.type.indexOf(DISCRETE) === -1, scaleOptions.marker.visible, scaleOptions.startValue, scaleOptions.endValue, tickIntervalsInfo.tickInterval); if (categoriesInfo) { scaleOptions.startValue = categoriesInfo.start; scaleOptions.endValue = categoriesInfo.end } if (scaleOptions.type.indexOf(DISCRETE) === -1) { isEmptyInterval = _isDate(scaleOptions.startValue) && _isDate(scaleOptions.endValue) && scaleOptions.startValue.getTime() === scaleOptions.endValue.getTime() || scaleOptions.startValue === scaleOptions.endValue } scaleOptions.isEmpty = startEndNotDefined(scaleOptions.startValue, scaleOptions.endValue) || isEmptyInterval; if (scaleOptions.isEmpty) { scaleOptions.startValue = scaleOptions.endValue = void 0 } else { scaleOptions.minorTickInterval = tickIntervalsInfo.minorTickInterval; scaleOptions.tickInterval = tickIntervalsInfo.tickInterval; if (isDateTime && (!_isDefined(scaleOptions.label.format) || scaleOptions.type === SEMIDISCRETE && scaleOptions.minorTickInterval !== scaleOptions.tickInterval)) { if (scaleOptions.type === DISCRETE) { scaleOptions.label.format = formatHelper.getDateFormatByTicks(tickIntervalsInfo.ticks) } else { if (!scaleOptions.marker.visible) { scaleOptions.label.format = formatHelper.getDateFormatByTickInterval(scaleOptions.startValue, scaleOptions.endValue, scaleOptions.tickInterval) } else { scaleOptions.label.format = dateUtils.getDateFormatByTickInterval(scaleOptions.tickInterval) } } } } if (scaleOptions.type === SEMIDISCRETE) { intervals = getIntervalCustomTicks(scaleOptions); scaleOptions.customMinorTicks = intervals.altIntervals; scaleOptions.customTicks = intervals.intervals; scaleOptions.customBoundTicks = [scaleOptions.customTicks[0]] } } function prepareScaleOptions(scaleOption, seriesDataSource, incidentOccurred) { var parser, parsedValue = 0, valueType = parseUtils.correctValueType(_normalizeEnum(scaleOption.valueType)), validateStartEndValues = function(field, parser) { var messageToIncidentOccurred = field === START_VALUE ? "start" : "end"; if (_isDefined(scaleOption[field])) { parsedValue = parser(scaleOption[field]); if (_isDefined(parsedValue)) { scaleOption[field] = parsedValue } else { scaleOption[field] = void 0; incidentOccurred("E2202", [messageToIncidentOccurred]) } } }; if (seriesDataSource) { valueType = seriesDataSource.getCalculatedValueType() || valueType } if (!valueType) { valueType = calculateValueType(scaleOption.startValue, scaleOption.endValue) || "numeric" } if (valueType === STRING || scaleOption.categories) { scaleOption.type = DISCRETE; valueType = STRING } scaleOption.valueType = valueType; parser = parseUtils.getParser(valueType); validateStartEndValues(START_VALUE, parser); validateStartEndValues(END_VALUE, parser); checkLogarithmicOptions(scaleOption, logarithmBase, incidentOccurred); if (!scaleOption.type) { scaleOption.type = "continuous" } void 0 === scaleOption.tickInterval && (scaleOption.tickInterval = scaleOption.majorTickInterval); scaleOption.minorTick.visible && (scaleOption.minorTick.visible = scaleOption.showMinorTicks); scaleOption.parser = parser; if (scaleOption.type === SEMIDISCRETE) { scaleOption.minorTick.visible = false; scaleOption.minorTickInterval = scaleOption.minRange; scaleOption.marker.visible = false; scaleOption.maxRange = void 0 } return scaleOption } function correctValueByInterval(value, isDate, interval) { if (_isDefined(value)) { value = isDate ? dateUtils.correctDateWithUnitBeginning(new Date(value), interval) : adjustValue(_floor(value / interval) * interval) } return value } function getIntervalCustomTicks(options) { var min = options.startValue, max = options.endValue, isDate = "datetime" === options.valueType, tickInterval = options.tickInterval, res = { intervals: [] }; if (!_isDefined(min) || !_isDefined(max)) { return res } res.intervals = getSequenceByInterval(min, max, options.minorTickInterval); if (tickInterval !== options.minorTickInterval) { res.altIntervals = res.intervals; min = correctValueByInterval(min, isDate, tickInterval); max = correctValueByInterval(max, isDate, tickInterval); res.intervals = getSequenceByInterval(min, max, tickInterval) } return res } var dxRangeSelector = __webpack_require__( /*! ../core/base_widget */ 515).inherit({ _eventsMap: { onSelectedRangeChanged: { name: SELECTED_RANGE_CHANGED }, onValueChanged: { name: VALUE_CHANGED } }, _setDeprecatedOptions: function() { this.callBase.apply(this, arguments); extend(this._deprecatedOptions, { "sliderMarker.padding": { since: "15.1", message: "Use the 'paddingTopBottom' and 'paddingLeftRight' options instead" }, "sliderMarker.placeholderSize": { since: "15.1", message: "Use the 'placeholderHeight' and 'indent' options instead" }, "scale.majorTickInterval": { since: "15.2", message: "Use the 'tickInterval' options instead" }, "scale.showMinorTicks": { since: "15.2", message: "Use the 'minorTick.visible' options instead" }, selectedRange: { since: "16.2", message: "Use the 'value' option instead" }, onSelectedRangeChanged: { since: "16.2", message: "Use the 'onValueChanged' option instead" }, "behavior.callSelectedRangeChanged": { since: "16.2", message: "Use the 'behavior.callValueChanged' option instead" }, "scale.useTicksAutoArrangement": { since: "17.1", message: "Use the 'scale.label.overlappingBehavior' option instead" } }) }, _rootClassPrefix: "dxrs", _rootClass: "dxrs-range-selector", _dataIsReady: function() { return this._dataIsLoaded() }, _initialChanges: ["DATA_SOURCE", "SELECTED_RANGE", "VALUE", "DISABLED"], _themeDependentChanges: ["MOSTLY_TOTAL"], _initCore: function() { var rangeViewGroup, slidersGroup, scaleGroup, trackersGroup, that = this, renderer = that._renderer, root = renderer.root; root.css({ "touch-action": "pan-y", "-ms-touch-action": "pan-y" }); that._clipRect = renderer.clipRect(); rangeViewGroup = renderer.g().attr({ "class": "dxrs-view" }).append(root); slidersGroup = renderer.g().attr({ "class": "dxrs-slidersContainer", "clip-path": that._clipRect.id }).append(root); scaleGroup = renderer.g().attr({ "class": "dxrs-scale", "clip-path": that._clipRect.id }).append(root); trackersGroup = renderer.g().attr({ "class": "dxrs-trackers" }).append(root); that._axis = new AxisWrapper({ renderer: renderer, root: scaleGroup, updateSelectedRange: function(range) { that.setValue(parseSelectedRange(range)) } }); that._rangeView = new rangeViewModule.RangeView({ renderer: renderer, root: rangeViewGroup, translator: that._axis.getTranslator() }); that._slidersController = new slidersControllerModule.SlidersController({ renderer: renderer, root: slidersGroup, trackersGroup: trackersGroup, updateSelectedRange: function(range, lastSelectedRange) { if (!that._rangeOption) { that._suppressDeprecatedWarnings(); that.option(SELECTED_RANGE, range); that._resumeDeprecatedWarnings(); that.option(VALUE, parseSelectedRange(range)) } if (that._options.onSelectedRangeChanged || that.hasEvent("selectedRangeChanged")) { that._eventTrigger(SELECTED_RANGE_CHANGED, { startValue: range.startValue, endValue: range.endValue }) } that._eventTrigger(VALUE_CHANGED, { value: parseSelectedRange(range), previousValue: parseSelectedRange(lastSelectedRange) }) }, translator: that._axis.getTranslator() }); that._tracker = new trackerModule.Tracker({ renderer: renderer, controller: that._slidersController }) }, _getDefaultSize: function() { return { width: 400, height: 160 } }, _disposeCore: function() { this._axis.dispose(); this._slidersController.dispose(); this._tracker.dispose() }, _createThemeManager: function() { return new themeManagerModule.ThemeManager }, _applySize: function(rect) { this._clientRect = rect.slice(); this._change(["MOSTLY_TOTAL"]) }, _optionChangesMap: { scale: "SCALE", selectedRange: "SELECTED_RANGE", value: "VALUE", dataSource: "DATA_SOURCE", disabled: "DISABLED" }, _optionChangesOrder: ["SCALE", "DATA_SOURCE"], _change_SCALE: function() { this._change(["MOSTLY_TOTAL"]) }, _change_DATA_SOURCE: function() { if (this._initialized || this._options.dataSource) { this._options[SELECTED_RANGE] = this._options[VALUE] = null; this._updateDataSource() } }, _customChangesOrder: ["MOSTLY_TOTAL", "SELECTED_RANGE", "VALUE", "SLIDER_SELECTION", "DISABLED"], _change_MOSTLY_TOTAL: function() { this._applyMostlyTotalChange() }, _change_SLIDER_SELECTION: function() { var that = this, range = that._options[SELECTED_RANGE], value = that._options[VALUE]; that._slidersController.setSelectedRange(value ? parseValue(value) : range && range) }, _change_SELECTED_RANGE: function() { var that = this, option = that._rangeOption && that._rangeOption[SELECTED_RANGE]; if (option) { that._options[SELECTED_RANGE] = option; that._validateRange(option.startValue, option.endValue); that.setValue(parseSelectedRange(option)) } }, _change_VALUE: function() { var that = this, option = that._rangeOption && that._rangeOption[VALUE]; if (option) { that._options[VALUE] = option; that._validateRange(option[0], option[1]); that.setValue(option) } }, _change_DISABLED: function() { var renderer = this._renderer, root = renderer.root; if (this.option("disabled")) { root.attr({ "pointer-events": "none", filter: renderer.getGrayScaleFilter().id }) } else { root.attr({ "pointer-events": null, filter: null }) } }, _validateRange: function(start, end) { var that = this, translator = that._axis.getTranslator(); if (null !== start && !translator.isValid(start) || null !== end && !translator.isValid(end)) { that._incidentOccurred("E2203") } }, _applyChanges: function() { var that = this, selectedRange = that._options[SELECTED_RANGE], value = that._options[VALUE]; if (that._changes.has("VALUE") && value) { that._rangeOption = { value: [value[0], value[1]] } } else { if (that._changes.has("SELECTED_RANGE") && selectedRange) { that._rangeOption = { selectedRange: selectedRange } } } that.callBase.apply(that, arguments); that._rangeOption = null; that.__isResizing = false }, _applyMostlyTotalChange: function() { var currentAnimationEnabled, that = this, renderer = that._renderer, rect = that._clientRect; if (that.__isResizing) { currentAnimationEnabled = renderer.animationEnabled(); renderer.updateAnimationOptions({ enabled: false }) } that._clipRect.attr({ x: rect[0], y: rect[1], width: rect[2] - rect[0], height: rect[3] - rect[1] }); that._updateContent({ left: rect[0], top: rect[1], width: rect[2] - rect[0], height: rect[3] - rect[1] }); if (that.__isResizing) { renderer.updateAnimationOptions({ enabled: currentAnimationEnabled }) } that._drawn() }, _dataSourceChangedHandler: function() { this._requestChange(["MOSTLY_TOTAL"]) }, _updateContent: function(canvas) { var sliderMarkerOptions, indents, scaleLabelsAreaHeight, rangeContainerCanvas, that = this, chartOptions = that.option("chart"), seriesDataSource = that._createSeriesDataSource(chartOptions), isCompactMode = !(seriesDataSource && seriesDataSource.isShowChart() || that.option("background.image.url")), scaleOptions = prepareScaleOptions(that._getOption("scale"), seriesDataSource, that._incidentOccurred), argTranslatorRange = calculateTranslatorRange(seriesDataSource, scaleOptions), tickIntervalsInfo = updateTickIntervals(scaleOptions, canvas.width, that._incidentOccurred, argTranslatorRange), chartThemeManager = seriesDataSource && seriesDataSource.isShowChart() && seriesDataSource.getThemeManager(); if (chartThemeManager) { checkLogarithmicOptions(chartOptions && chartOptions.valueAxis, chartThemeManager.getOptions("valueAxis").logarithmBase, that._incidentOccurred) } updateScaleOptions(scaleOptions, seriesDataSource, argTranslatorRange, tickIntervalsInfo, getDateMarkerVisibilityChecker(canvas.width)); updateTranslatorRangeInterval(argTranslatorRange, scaleOptions); sliderMarkerOptions = that._prepareSliderMarkersOptions(scaleOptions, canvas.width, tickIntervalsInfo); indents = calculateIndents(that._renderer, scaleOptions, sliderMarkerOptions, that.option("indent")); scaleLabelsAreaHeight = calculateScaleAreaHeight(that._renderer, scaleOptions, showScaleMarkers(scaleOptions)); rangeContainerCanvas = { left: canvas.left + indents.left, top: canvas.top + indents.top, width: _max(canvas.width + canvas.left - indents.right, 1), height: _max(!isCompactMode ? canvas.height - indents.top - indents.bottom - scaleLabelsAreaHeight : commonModule.HEIGHT_COMPACT_MODE, 0), right: 0, bottom: 0 }; that._axis.update(scaleOptions, isCompactMode, rangeContainerCanvas, argTranslatorRange); scaleOptions.minorTickInterval = scaleOptions.isEmpty ? 0 : scaleOptions.minorTickInterval; that._updateElements(scaleOptions, sliderMarkerOptions, isCompactMode, rangeContainerCanvas, seriesDataSource); if (chartThemeManager) { chartThemeManager.dispose() } }, _updateElements: function(scaleOptions, sliderMarkerOptions, isCompactMode, canvas, seriesDataSource) { var that = this, behavior = that._getOption("behavior"), shutterOptions = that._getOption("shutter"), isNotSemiDiscrete = scaleOptions.type !== SEMIDISCRETE; shutterOptions.color = shutterOptions.color || that._getOption(CONTAINER_BACKGROUND_COLOR, true); that._rangeView.update(that.option("background"), that._themeManager.theme("background"), canvas, isCompactMode, behavior.animationEnabled && that._renderer.animationEnabled(), seriesDataSource); that._isUpdating = true; that._slidersController.update([canvas.top, canvas.top + canvas.height], behavior, isCompactMode, that._getOption("sliderHandle"), sliderMarkerOptions, shutterOptions, { minRange: isNotSemiDiscrete ? that.option("scale.minRange") : void 0, maxRange: isNotSemiDiscrete ? that.option("scale.maxRange") : void 0 }, that._axis.getFullTicks(), that._getOption("selectedRangeColor", true)); that._requestChange(["SLIDER_SELECTION"]); that._isUpdating = false; that._tracker.update(!that._axis.getTranslator().isEmptyValueRange(), behavior) }, _createSeriesDataSource: function(chartOptions) { var seriesDataSource, that = this, dataSource = that._dataSourceItems(), scaleOptions = that._getOption("scale"), valueType = scaleOptions.valueType || calculateValueType(scaleOptions.startValue, scaleOptions.endValue), valueAxis = new axisModule.Axis({ renderer: that._renderer, axisType: "xyAxes", drawingType: "linear" }); valueAxis.updateOptions({ isHorizontal: false, label: {} }); if (dataSource || chartOptions && chartOptions.series) { chartOptions = extend({}, chartOptions, { theme: that.option("theme") }); seriesDataSource = new seriesDataSourceModule.SeriesDataSource({ renderer: that._renderer, dataSource: dataSource, valueType: _normalizeEnum(valueType), axisType: scaleOptions.type, chart: chartOptions, dataSourceField: that.option("dataSourceField"), incidentOccurred: that._incidentOccurred, categories: scaleOptions.categories, argumentAxis: that._axis, valueAxis: valueAxis }) } return seriesDataSource }, _prepareSliderMarkersOptions: function(scaleOptions, screenDelta, tickIntervalsInfo) { var businessInterval, that = this, minorTickInterval = tickIntervalsInfo.minorTickInterval, tickInterval = tickIntervalsInfo.tickInterval, endValue = scaleOptions.endValue, startValue = scaleOptions.startValue, sliderMarkerOptions = that._getOption(SLIDER_MARKER), sliderMarkerUserOption = that.option(SLIDER_MARKER) || {}, isTypeDiscrete = scaleOptions.type === DISCRETE, isValueTypeDatetime = scaleOptions.valueType === DATETIME; sliderMarkerOptions.borderColor = that._getOption(CONTAINER_BACKGROUND_COLOR, true); if (!sliderMarkerOptions.format) { if (!that._getOption("behavior").snapToTicks && _isNumber(scaleOptions.startValue)) { businessInterval = Math.abs(endValue - startValue); sliderMarkerOptions.format = { type: "fixedPoint", precision: vizUtils.getSignificantDigitPosition(businessInterval / screenDelta) } } if (isValueTypeDatetime && !isTypeDiscrete) { if (!scaleOptions.marker.visible) { if (_isDefined(startValue) && _isDefined(endValue)) { sliderMarkerOptions.format = formatHelper.getDateFormatByTickInterval(startValue, endValue, _isDefined(minorTickInterval) && 0 !== minorTickInterval ? minorTickInterval : tickInterval) } } else { sliderMarkerOptions.format = dateUtils.getDateFormatByTickInterval(_isDefined(minorTickInterval) && 0 !== minorTickInterval ? minorTickInterval : tickInterval) } } if (isValueTypeDatetime && isTypeDiscrete && tickIntervalsInfo.ticks.length) { sliderMarkerOptions.format = formatHelper.getDateFormatByTicks(tickIntervalsInfo.ticks) } } if (void 0 !== sliderMarkerUserOption.padding && void 0 === sliderMarkerUserOption.paddingLeftRight && void 0 === sliderMarkerUserOption.paddingTopBottom) { sliderMarkerOptions.paddingLeftRight = sliderMarkerOptions.paddingTopBottom = sliderMarkerUserOption.padding } return sliderMarkerOptions }, getSelectedRange: function() { log("W0002", this.NAME, "getSelectedRange", "16.2", "Use the 'getValue' method instead"); return parseValue(this.getValue()) }, getValue: function() { return parseSelectedRange(this._slidersController.getSelectedRange()) }, setSelectedRange: function(range) { log("W0002", this.NAME, "setSelectedRange", "16.2", "Use the 'setValue' method instead"); this.setValue(parseSelectedRange(range)) }, setValue: function(value) { var current; if (!this._isUpdating && value) { current = this._slidersController.getSelectedRange(); if (!current || current.startValue !== value[0] || current.endValue !== value[1]) { this._slidersController.setSelectedRange(parseValue(value)) } } }, resetSelectedRange: function() { this.setValue([]) }, _setContentSize: function() { this.__isResizing = 2 === this._changes.count(); this.callBase.apply(this, arguments) } }); $.each(["selectedRangeColor", "containerBackgroundColor", "sliderMarker", "sliderHandle", "shutter", OPTION_BACKGROUND, "behavior", "chart", "indent"], function(_, name) { dxRangeSelector.prototype._optionChangesMap[name] = "MOSTLY_TOTAL" }); function prepareAxisOptions(scaleOptions, isCompactMode, height, axisPosition) { scaleOptions.label.overlappingBehavior = { mode: _isDefined(scaleOptions.useTicksAutoArrangement) ? scaleOptions.useTicksAutoArrangement ? "hide" : "none" : scaleOptions.label.overlappingBehavior }; scaleOptions.marker.label.font = scaleOptions.label.font; scaleOptions.color = scaleOptions.marker.color = scaleOptions.tick.color; scaleOptions.opacity = scaleOptions.marker.opacity = scaleOptions.tick.opacity; scaleOptions.width = scaleOptions.marker.width = scaleOptions.tick.width; scaleOptions.placeholderSize = (scaleOptions.placeholderHeight || 0) + axisPosition; scaleOptions.argumentType = scaleOptions.valueType; scaleOptions.visible = isCompactMode; scaleOptions.minorTick.showCalculatedTicks = scaleOptions.isHorizontal = scaleOptions.stick = true; scaleOptions.semiDiscreteInterval = scaleOptions.minRange; if (!isCompactMode) { scaleOptions.minorTick.length = scaleOptions.tick.length = height } scaleOptions.label.indentFromAxis = scaleOptions.label.topIndent + axisPosition; return scaleOptions } function createDateMarkersEvent(scaleOptions, markerTrackers, setSelectedRange) { $.each(markerTrackers, function(_, value) { value.on("dxpointerdown", onPointerDown) }); function onPointerDown(e) { var range = e.target.range, minRange = scaleOptions.minRange ? addInterval(range.startValue, scaleOptions.minRange) : void 0, maxRange = scaleOptions.maxRange ? addInterval(range.startValue, scaleOptions.maxRange) : void 0; if (!(minRange && minRange > range.endValue || maxRange && maxRange < range.endValue)) { setSelectedRange(range) } } } function AxisWrapper(params) { this._axis = new axisModule.Axis({ renderer: params.renderer, axesContainerGroup: params.root, axisType: "xyAxes", drawingType: "linear", widgetClass: "dxrs", axisClass: "range-selector" }); this._updateSelectedRangeCallback = params.updateSelectedRange } AxisWrapper.prototype = { constructor: AxisWrapper, dispose: function() { this._axis.dispose() }, update: function(options, isCompactMode, canvas, businessRange) { var axis = this._axis; axis.updateOptions(prepareAxisOptions(options, isCompactMode, canvas.height, canvas.height / 2 - Math.ceil(options.width / 2))); axis.setBusinessRange(businessRange); axis.draw(canvas); axis.shift({ left: 0, bottom: -canvas.height / 2 + canvas.top }); if (axis.getMarkerTrackers()) { createDateMarkersEvent(options, axis.getMarkerTrackers(), this._updateSelectedRangeCallback) } }, getFullTicks: function() { return this._axis.getFullTicks() }, getTranslator: function() { return this._axis.getTranslator() }, getViewport: function() {} }; registerComponent("dxRangeSelector", dxRangeSelector); module.exports = dxRangeSelector; dxRangeSelector.addPlugin(__webpack_require__( /*! ../core/export */ 511).plugin); dxRangeSelector.addPlugin(__webpack_require__( /*! ../core/title */ 558).plugin); dxRangeSelector.addPlugin(__webpack_require__( /*! ../core/loading_indicator */ 560).plugin); dxRangeSelector.addPlugin(__webpack_require__( /*! ../core/data_source */ 561).plugin) }, /*!*****************************************!*\ !*** ./js/viz/range_selector/common.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var _format = __webpack_require__( /*! ../core/format */ 530), isFunction = __webpack_require__( /*! ../../core/utils/common */ 14).isFunction, HEIGHT_COMPACT_MODE = 24, POINTER_SIZE = 4, EMPTY_SLIDER_MARKER_TEXT = ". . ."; var utils = { trackerSettings: { fill: "grey", stroke: "grey", opacity: 1e-4 }, animationSettings: { duration: 250 } }; var consts = { emptySliderMarkerText: EMPTY_SLIDER_MARKER_TEXT, pointerSize: POINTER_SIZE }; var formatValue = function(value, formatOptions) { var formatObject = { value: value, valueText: _format(value, formatOptions) }; return String(isFunction(formatOptions.customizeText) ? formatOptions.customizeText.call(formatObject, formatObject) : formatObject.valueText) }; exports.utils = utils; exports.consts = consts; exports.formatValue = formatValue; exports.HEIGHT_COMPACT_MODE = HEIGHT_COMPACT_MODE }, /*!*****************************************************!*\ !*** ./js/viz/range_selector/sliders_controller.js ***! \*****************************************************/ function(module, exports, __webpack_require__) { var noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, commonModule = __webpack_require__( /*! ./common */ 605), animationSettings = commonModule.utils.animationSettings, emptySliderMarkerText = commonModule.consts.emptySliderMarkerText, Slider = __webpack_require__( /*! ./slider */ 607), _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum; function buildRectPoints(left, top, right, bottom) { return [left, top, right, top, right, bottom, left, bottom] } function valueOf(value) { return value && value.valueOf() } function isLess(a, b) { return a < b } function isGreater(a, b) { return a > b } function selectClosestValue(target, values) { var middle, start = 0, end = values ? values.length - 1 : 0, val = target; while (end - start > 1) { middle = start + end >> 1; val = values[middle]; if (val === target) { return target } else { if (target < val) { end = middle } else { start = middle } } } if (values) { val = values[target - values[start] <= values[end] - target ? start : end] } return val } function dummyProcessSelectionChanged() { this._lastSelectedRange = this.getSelectedRange(); delete this._processSelectionChanged } function suppressSetSelectedRange(controller) { controller.setSelectedRange = noop; if (controller._processSelectionChanged === dummyProcessSelectionChanged) { controller._processSelectionChanged() } } function restoreSetSelectedRange(controller) { delete controller.setSelectedRange } function SlidersController(params) { var that = this, sliderParams = { renderer: params.renderer, root: params.root, trackersGroup: params.trackersGroup, translator: params.translator }; that._params = params; that._areaTracker = params.renderer.path(null, "area").attr({ "class": "area-tracker", fill: "#000000", opacity: 1e-4 }).append(params.trackersGroup); that._selectedAreaTracker = params.renderer.path(null, "area").attr({ "class": "selected-area-tracker", fill: "#000000", opacity: 1e-4 }).append(params.trackersGroup); that._shutter = params.renderer.path(null, "area").append(params.root); that._sliders = [new Slider(sliderParams, 0), new Slider(sliderParams, 1)]; that._processSelectionChanged = dummyProcessSelectionChanged } SlidersController.prototype = { constructor: SlidersController, dispose: function() { this._sliders[0].dispose(); this._sliders[1].dispose() }, getTrackerTargets: function() { return { area: this._areaTracker, selectedArea: this._selectedAreaTracker, sliders: this._sliders } }, _processSelectionChanged: function() { var that = this, selectedRange = that.getSelectedRange(); if (valueOf(selectedRange.startValue) !== valueOf(that._lastSelectedRange.startValue) || valueOf(selectedRange.endValue) !== valueOf(that._lastSelectedRange.endValue)) { that._params.updateSelectedRange(selectedRange, that._lastSelectedRange); that._lastSelectedRange = selectedRange } }, update: function(verticalRange, behavior, isCompactMode, sliderHandleOptions, sliderMarkerOptions, shutterOptions, rangeBounds, fullTicks, selectedRangeColor) { var that = this, callValueChanged = behavior.callValueChanged || behavior.callSelectedRangeChanged, screenRange = that._params.translator.getScreenRange(); that._verticalRange = verticalRange; that._minRange = rangeBounds.minRange; that._maxRange = rangeBounds.maxRange; that._animationEnabled = behavior.animationEnabled && that._params.renderer.animationEnabled(); that._allowSlidersSwap = behavior.allowSlidersSwap; that._sliders[0].update(verticalRange, sliderHandleOptions, sliderMarkerOptions); that._sliders[1].update(verticalRange, sliderHandleOptions, sliderMarkerOptions); that._sliders[0]._position = that._sliders[1]._position = screenRange[0]; that._values = !that._params.translator.isValueProlonged && behavior.snapToTicks ? fullTicks : null; that._areaTracker.attr({ points: buildRectPoints(screenRange[0], verticalRange[0], screenRange[1], verticalRange[1]) }); that._isCompactMode = isCompactMode; that._shutterOffset = sliderHandleOptions.width / 2; that._updateSelectedView(shutterOptions, selectedRangeColor); that._isOnMoving = "onmoving" === _normalizeEnum(callValueChanged); that._updateSelectedRange(); that._applyTotalPosition(false) }, _updateSelectedView: function(shutterOptions, selectedRangeColor) { var settings = { fill: null, "fill-opacity": null, stroke: null, "stroke-width": null }; if (this._isCompactMode) { settings.stroke = selectedRangeColor; settings["stroke-width"] = 3; settings.sharp = "v" } else { settings.fill = shutterOptions.color; settings["fill-opacity"] = shutterOptions.opacity } this._shutter.attr(settings) }, _updateSelectedRange: function() { var that = this, sliders = that._sliders; sliders[0].cancelAnimation(); sliders[1].cancelAnimation(); that._shutter.stopAnimation(); if (that._params.translator.isEmptyValueRange()) { sliders[0]._setText(emptySliderMarkerText); sliders[1]._setText(emptySliderMarkerText); sliders[0]._value = sliders[1]._value = void 0; sliders[0]._position = that._params.translator.getScreenRange()[0]; sliders[1]._position = that._params.translator.getScreenRange()[1]; that._applyTotalPosition(false); suppressSetSelectedRange(that) } else { restoreSetSelectedRange(that) } }, _applyTotalPosition: function(isAnimated) { var areOverlapped, sliders = this._sliders; isAnimated = this._animationEnabled && isAnimated; sliders[0].applyPosition(isAnimated); sliders[1].applyPosition(isAnimated); areOverlapped = sliders[0].getCloudBorder() > sliders[1].getCloudBorder(); sliders[0].setOverlapped(areOverlapped); sliders[1].setOverlapped(areOverlapped); this._applyAreaTrackersPosition(); this._applySelectedRangePosition(isAnimated) }, _applyAreaTrackersPosition: function() { var that = this, position1 = that._sliders[0].getPosition(), position2 = that._sliders[1].getPosition(); that._selectedAreaTracker.attr({ points: buildRectPoints(position1, that._verticalRange[0], position2, that._verticalRange[1]) }).css({ cursor: Math.abs(that._params.translator.getScreenRange()[1] - that._params.translator.getScreenRange()[0] - position2 + position1) < .001 ? "default" : "pointer" }) }, _applySelectedRangePosition: function(isAnimated) { var screenRange, points, that = this, verticalRange = that._verticalRange, pos1 = that._sliders[0].getPosition(), pos2 = that._sliders[1].getPosition(); if (that._isCompactMode) { points = [pos1 + Math.ceil(that._shutterOffset), (verticalRange[0] + verticalRange[1]) / 2, pos2 - Math.floor(that._shutterOffset), (verticalRange[0] + verticalRange[1]) / 2] } else { screenRange = that._params.translator.getScreenRange(); points = [buildRectPoints(screenRange[0], verticalRange[0], Math.max(pos1 - Math.floor(that._shutterOffset), screenRange[0]), verticalRange[1]), buildRectPoints(screenRange[1], verticalRange[0], Math.min(pos2 + Math.ceil(that._shutterOffset), screenRange[1]), verticalRange[1])] } if (isAnimated) { that._shutter.animate({ points: points }, animationSettings) } else { that._shutter.attr({ points: points }) } }, getSelectedRange: function() { return { startValue: this._sliders[0].getValue(), endValue: this._sliders[1].getValue() } }, setSelectedRange: function(arg) { arg = arg || {}; var that = this, translator = that._params.translator, startValue = translator.isValid(arg.startValue) ? translator.parse(arg.startValue) : translator.getRange()[0], endValue = translator.isValid(arg.endValue) ? translator.parse(arg.endValue) : translator.getRange()[1], values = translator.to(startValue, -1) < translator.to(endValue, 1) ? [startValue, endValue] : [endValue, startValue]; that._sliders[0].setDisplayValue(values[0]); that._sliders[1].setDisplayValue(values[1]); that._sliders[0]._position = translator.to(values[0], -1); that._sliders[1]._position = translator.to(values[1], 1); that._applyTotalPosition(true); that._processSelectionChanged() }, beginSelectedAreaMoving: function(initialPosition) { var that = this, sliders = that._sliders, offset = (sliders[0].getPosition() + sliders[1].getPosition()) / 2 - initialPosition, currentPosition = initialPosition; move.complete = function() { that._dockSelectedArea() }; return move; function move(position) { if (position !== currentPosition && position > currentPosition === position > (sliders[0].getPosition() + sliders[1].getPosition()) / 2 - offset) { that._moveSelectedArea(position + offset, false) } currentPosition = position } }, _dockSelectedArea: function() { var translator = this._params.translator, sliders = this._sliders; sliders[0]._position = translator.to(sliders[0].getValue(), -1); sliders[1]._position = translator.to(sliders[1].getValue(), 1); this._applyTotalPosition(true); this._processSelectionChanged() }, moveSelectedArea: function(screenPosition) { this._moveSelectedArea(screenPosition, true); this._dockSelectedArea() }, _moveSelectedArea: function(screenPosition, isAnimated) { var startValue, that = this, translator = that._params.translator, sliders = that._sliders, interval = sliders[1].getPosition() - sliders[0].getPosition(), startPosition = screenPosition - interval / 2, endPosition = screenPosition + interval / 2; if (startPosition < translator.getScreenRange()[0]) { startPosition = translator.getScreenRange()[0]; endPosition = startPosition + interval } if (endPosition > translator.getScreenRange()[1]) { endPosition = translator.getScreenRange()[1]; startPosition = endPosition - interval } startValue = selectClosestValue(translator.from(startPosition, -1), that._values); sliders[0].setDisplayValue(startValue); sliders[1].setDisplayValue(selectClosestValue(translator.from(translator.to(startValue, -1) + interval, 1), that._values)); sliders[0]._position = startPosition; sliders[1]._position = endPosition; that._applyTotalPosition(isAnimated); if (that._isOnMoving) { that._processSelectionChanged() } }, placeSliderAndBeginMoving: function(firstPosition, secondPosition) { var thresholdPosition, handler, that = this, translator = that._params.translator, sliders = that._sliders, index = firstPosition < secondPosition ? 0 : 1, dir = index > 0 ? 1 : -1, compare = index > 0 ? isGreater : isLess, antiCompare = index > 0 ? isLess : isGreater, positions = [], values = []; values[index] = translator.from(firstPosition, dir); values[1 - index] = translator.from(secondPosition, -dir); positions[1 - index] = secondPosition; if (translator.isValueProlonged) { if (compare(firstPosition, translator.to(values[index], dir))) { values[index] = translator.from(firstPosition, -dir) } if (compare(secondPosition, translator.to(values[index], -dir))) { values[1 - index] = values[index] } } if (that._minRange) { thresholdPosition = translator.to(translator.add(selectClosestValue(values[index], that._values), that._minRange, -dir), -dir); if (compare(secondPosition, thresholdPosition)) { values[1 - index] = translator.add(values[index], that._minRange, -dir) } thresholdPosition = translator.to(translator.add(translator.getRange()[1 - index], that._minRange, dir), -dir); if (antiCompare(firstPosition, thresholdPosition)) { values[1 - index] = translator.getRange()[1 - index]; values[index] = translator.add(values[1 - index], that._minRange, dir); positions[1 - index] = firstPosition } } values[0] = selectClosestValue(values[0], that._values); values[1] = selectClosestValue(values[1], that._values); positions[index] = translator.to(values[index], dir); sliders[0].setDisplayValue(values[0]); sliders[1].setDisplayValue(values[1]); sliders[0]._position = positions[0]; sliders[1]._position = positions[1]; that._applyTotalPosition(true); if (that._isOnMoving) { that._processSelectionChanged() } handler = that.beginSliderMoving(1 - index, secondPosition); sliders[1 - index]._sliderGroup.stopAnimation(); that._shutter.stopAnimation(); handler(secondPosition); return handler }, beginSliderMoving: function(initialIndex, initialPosition) { var that = this, translator = that._params.translator, sliders = that._sliders, minPosition = translator.getScreenRange()[0], maxPosition = translator.getScreenRange()[1], index = initialIndex, staticPosition = sliders[1 - index].getPosition(), currentPosition = initialPosition, dir = index > 0 ? 1 : -1, compareMin = index > 0 ? isLess : isGreater, compareMax = index > 0 ? isGreater : isLess, moveOffset = sliders[index].getPosition() - initialPosition, swapOffset = compareMin(sliders[index].getPosition(), initialPosition) ? -moveOffset : moveOffset; move.complete = function() { sliders[index]._setValid(true); that._dockSelectedArea() }; return move; function move(position) { var isValid, temp, pos, slider, value; if (position !== currentPosition) { if (compareMin(position + swapOffset, staticPosition)) { isValid = that._allowSlidersSwap; if (isValid && !translator.isValueProlonged && that._minRange) { isValid = translator.isValid(translator.add(sliders[1 - index].getValue(), that._minRange, -dir)) } if (isValid) { that._changeMovingSlider(index); index = 1 - index; dir = -dir; temp = compareMin; compareMin = compareMax; compareMax = temp; moveOffset = -dir * Math.abs(moveOffset); swapOffset = -moveOffset } } if (compareMax(position + moveOffset, staticPosition)) { isValid = true; slider = sliders[index]; value = sliders[1 - index].getValue(); pos = Math.max(Math.min(position + moveOffset, maxPosition), minPosition); if (isValid && translator.isValueProlonged) { isValid = !compareMin(pos, translator.to(value, dir)) } if (isValid && that._minRange) { isValid = !compareMin(pos, translator.to(translator.add(value, that._minRange, dir), dir)) } if (isValid && that._maxRange) { isValid = !compareMax(pos, translator.to(translator.add(value, that._maxRange, dir), dir)) } slider._setValid(isValid); slider.setDisplayValue(isValid ? selectClosestValue(translator.from(pos, dir), that._values) : slider.getValue()); slider._position = pos; that._applyTotalPosition(false); slider.toForeground(); if (that._isOnMoving) { that._processSelectionChanged() } } } currentPosition = position } }, _changeMovingSlider: function(index) { var newValue, that = this, translator = that._params.translator, sliders = that._sliders, position = sliders[1 - index].getPosition(), dir = index > 0 ? 1 : -1; sliders[index].setDisplayValue(selectClosestValue(translator.from(position, dir), that._values)); newValue = translator.from(position, -dir); if (translator.isValueProlonged) { newValue = translator.from(position, dir) } else { if (that._minRange) { newValue = translator.add(newValue, that._minRange, -dir) } } sliders[1 - index].setDisplayValue(selectClosestValue(newValue, that._values)); sliders[index]._setValid(true); sliders[index]._marker._update(); sliders[0]._position = sliders[1]._position = position }, foregroundSlider: function(index) { this._sliders[index].toForeground() } }; exports.SlidersController = SlidersController }, /*!*****************************************!*\ !*** ./js/viz/range_selector/slider.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var commonModule = __webpack_require__( /*! ./common */ 605), animationSettings = commonModule.utils.animationSettings, formatValue = commonModule.formatValue, SliderMarker = __webpack_require__( /*! ./slider_marker */ 608), support = __webpack_require__( /*! ../../core/utils/support */ 61), SPLITTER_WIDTH = 8, TOUCH_SPLITTER_WIDTH = 20; function getSliderTrackerWidth(sliderHandleWidth) { return support.touchEvents || support.pointer ? TOUCH_SPLITTER_WIDTH : SPLITTER_WIDTH < sliderHandleWidth ? sliderHandleWidth : SPLITTER_WIDTH } function Slider(params, index) { var that = this; that._translator = params.translator; that._sliderGroup = params.renderer.g().attr({ "class": "slider" }).append(params.root); that._line = params.renderer.path(null, "line").append(that._sliderGroup); that._marker = new SliderMarker(params.renderer, that._sliderGroup, 1 === index); that._tracker = params.renderer.rect().attr({ "class": "slider-tracker", fill: "#000000", opacity: 1e-4 }).css({ cursor: "w-resize" }).append(params.trackersGroup) } Slider.prototype = { constructor: Slider, cancelAnimation: function() { this._sliderGroup.stopAnimation(); this._tracker.stopAnimation() }, applyPosition: function(isAnimated) { var that = this, slider = that._sliderGroup, tracker = that._tracker, attrs = { translateX: that._position }; that._marker.setPosition(that._position); if (isAnimated) { slider.animate(attrs, animationSettings); tracker.animate(attrs, animationSettings) } else { slider.attr(attrs); tracker.attr(attrs) } }, _setValid: function(isValid) { this._marker.setValid(isValid); this._line.attr({ stroke: this._colors[Number(isValid)] }) }, _setText: function(text) { this._marker.setText(text) }, update: function(verticalRange, sliderHandleOptions, sliderMarkerOptions) { var that = this; that._formatOptions = { format: sliderMarkerOptions.format, precision: sliderMarkerOptions.precision, customizeText: sliderMarkerOptions.customizeText }; that._marker.applyOptions(sliderMarkerOptions, that._translator.getScreenRange()); that._colors = [sliderMarkerOptions.invalidRangeColor, sliderHandleOptions.color]; that._sliderGroup.attr({ translateY: verticalRange[0] }); that._line.attr({ "stroke-width": sliderHandleOptions.width, stroke: sliderHandleOptions.color, "stroke-opacity": sliderHandleOptions.opacity, sharp: "h", points: [0, 0, 0, verticalRange[1] - verticalRange[0]] }); var trackerWidth = getSliderTrackerWidth(sliderHandleOptions.width); that._tracker.attr({ x: -trackerWidth / 2, y: 0, width: trackerWidth, height: verticalRange[1] - verticalRange[0], translateY: verticalRange[0] }) }, toForeground: function() { this._sliderGroup.toForeground() }, getSliderTracker: function() { return this._tracker }, getPosition: function() { return this._position }, setDisplayValue: function(value) { this._value = value; this._setText(formatValue(value, this._formatOptions)) }, setOverlapped: function(isOverlapped) { this._marker.setOverlapped(isOverlapped) }, getValue: function() { return this._value }, on: function(event, handler) { this._tracker.on(event, handler); this._marker.getTracker().on(event, handler) }, getCloudBorder: function() { return this._marker.getBorderPosition() }, dispose: function() { this._marker.dispose() } }; module.exports = Slider }, /*!************************************************!*\ !*** ./js/viz/range_selector/slider_marker.js ***! \************************************************/ function(module, exports, __webpack_require__) { var patchFontOptions = __webpack_require__( /*! ../core/utils */ 509).patchFontOptions, SLIDER_MARKER_UPDATE_DELAY = 75, POINTER_SIZE = __webpack_require__( /*! ./common */ 605).consts.pointerSize; function SliderMarker(renderer, root, isLeftPointer) { var that = this; that._isLeftPointer = isLeftPointer; that._isOverlapped = false; that._group = renderer.g().attr({ "class": "slider-marker" }).append(root); that._area = renderer.path(null, "area").append(that._group); that._label = renderer.text().attr({ align: "left" }).append(that._group); that._tracker = renderer.rect().attr({ "class": "slider-marker-tracker", fill: "#000000", opacity: 1e-4 }).css({ cursor: "pointer" }).append(that._group); that._border = renderer.rect(0, 0, 1, 0) } SliderMarker.prototype = { constructor: SliderMarker, _getRectSize: function(textSize) { return { width: Math.round(2 * this._paddingLeftRight + textSize.width), height: Math.round(2 * this._paddingTopBottom + textSize.height) } }, _getTextSize: function() { var textSize = this._label.getBBox(); if (!this._textHeight && isFinite(textSize.height)) { this._textHeight = textSize.height } return { width: textSize.width, height: this._textHeight, y: textSize.y } }, _getAreaPointsInfo: function(textSize) { var that = this, rectSize = that._getRectSize(textSize), rectWidth = rectSize.width, rectHeight = rectSize.height, rectLeftBorder = -rectWidth, rectRightBorder = 0, pointerRightPoint = POINTER_SIZE, pointerCenterPoint = 0, pointerLeftPoint = -POINTER_SIZE, position = that._position, isLeft = that._isLeftPointer, correctCloudBorders = function() { rectLeftBorder++; rectRightBorder++; pointerRightPoint++; pointerCenterPoint++; pointerLeftPoint++ }, checkPointerBorders = function() { if (pointerRightPoint > rectRightBorder) { pointerRightPoint = rectRightBorder } else { if (pointerLeftPoint < rectLeftBorder) { pointerLeftPoint = rectLeftBorder } } isLeft && correctCloudBorders() }, borderPosition = position; if (isLeft) { if (position > that._range[1] - rectWidth) { rectRightBorder = -position + that._range[1]; rectLeftBorder = rectRightBorder - rectWidth; checkPointerBorders(); borderPosition += rectLeftBorder } else { rectLeftBorder = pointerLeftPoint = 0; rectRightBorder = rectWidth } } else { if (position - that._range[0] < rectWidth) { rectLeftBorder = -(position - that._range[0]); rectRightBorder = rectLeftBorder + rectWidth; checkPointerBorders(); borderPosition += rectRightBorder } else { pointerRightPoint = 0; correctCloudBorders() } } that._borderPosition = borderPosition; return { offset: rectLeftBorder, isCut: (!isLeft || pointerCenterPoint !== pointerLeftPoint) && (isLeft || pointerCenterPoint !== pointerRightPoint), points: [rectLeftBorder, 0, rectRightBorder, 0, rectRightBorder, rectHeight, pointerRightPoint, rectHeight, pointerCenterPoint, rectHeight + POINTER_SIZE, pointerLeftPoint, rectHeight, rectLeftBorder, rectHeight] } }, _update: function() { var textSize, currentTextSize, rectSize, that = this; clearTimeout(that._timeout); that._label.attr({ text: that._text || "" }); currentTextSize = that._getTextSize(); rectSize = that._getRectSize(currentTextSize); textSize = that._textSize || currentTextSize; textSize = that._textSize = currentTextSize.width > textSize.width || currentTextSize.height > textSize.height ? currentTextSize : textSize; that._timeout = setTimeout(function() { updateSliderMarker(currentTextSize, rectSize); that._textSize = currentTextSize }, SLIDER_MARKER_UPDATE_DELAY); function updateSliderMarker(size, rectSize) { var points, pointsData, offset; rectSize = rectSize || that._getRectSize(size); that._group.attr({ translateY: -(rectSize.height + POINTER_SIZE) }); pointsData = that._getAreaPointsInfo(size); points = pointsData.points; offset = pointsData.offset; that._area.attr({ points: points }); that._border.attr({ x: that._isLeftPointer ? points[0] - 1 : points[2], height: pointsData.isCut ? rectSize.height : rectSize.height + POINTER_SIZE }); that._tracker.attr({ translateX: offset, width: rectSize.width, height: rectSize.height + POINTER_SIZE }); that._label.attr({ translateX: that._paddingLeftRight + offset, translateY: rectSize.height / 2 - (size.y + size.height / 2) }) } updateSliderMarker(textSize) }, setText: function(value) { this._text = value }, setPosition: function(position) { this._position = position; this._update() }, applyOptions: function(options, screenRange) { var that = this; that._range = screenRange; that._paddingLeftRight = options.paddingLeftRight; that._paddingTopBottom = options.paddingTopBottom; that._textHeight = null; that._colors = [options.invalidRangeColor, options.color]; that._area.attr({ fill: options.color }); that._border.attr({ fill: options.borderColor }); that._label.css(patchFontOptions(options.font)); that._update() }, getTracker: function() { return this._tracker }, setValid: function(isValid) { this._area.attr({ fill: this._colors[Number(isValid)] }) }, setColor: function(color) { this._area.attr({ fill: color }) }, dispose: function() { clearTimeout(this._timeout) }, setOverlapped: function(isOverlapped) { var that = this; if (that._isOverlapped !== isOverlapped) { if (isOverlapped) { that._border.append(that._group) } else { that._isOverlapped && that._border.remove() } that._isOverlapped = isOverlapped } }, getBorderPosition: function() { return this._borderPosition } }; module.exports = SliderMarker }, /*!******************************************!*\ !*** ./js/viz/range_selector/tracker.js ***! \******************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), pointerEvents = __webpack_require__( /*! ../../events/pointer */ 76), msPointerEnabled = __webpack_require__( /*! ../../core/utils/support */ 61).pointer, MIN_MANUAL_SELECTING_WIDTH = 10; function isLeftButtonPressed(event) { var e = event || window.event, originalEvent = e.originalEvent, touches = e.touches, pointerType = originalEvent ? originalEvent.pointerType : false, eventTouches = originalEvent ? originalEvent.touches : false, isMSPointerLeftClick = originalEvent && void 0 !== pointerType && (pointerType === (originalEvent.MSPOINTER_TYPE_TOUCH || "touch") || pointerType === (originalEvent.MSPOINTER_TYPE_MOUSE || "mouse") && 1 === originalEvent.buttons), isTouches = touches && touches.length > 0 || eventTouches && eventTouches.length > 0; return 1 === e.which || isMSPointerLeftClick || isTouches } function isMultiTouches(event) { var originalEvent = event.originalEvent, touches = event.touches, eventTouches = originalEvent && originalEvent.touches; return touches && touches.length > 1 || eventTouches && eventTouches.length > 1 || null } function preventDefault(e) { if (!isMultiTouches(e)) { e.preventDefault() } } function stopPropagationAndPreventDefault(e) { if (!isMultiTouches(e)) { e.stopPropagation(); e.preventDefault() } } function isTouchEventArgs(e) { return e && e.type && 0 === e.type.indexOf("touch") } function getEventPageX(event) { var originalEvent = event.originalEvent, result = 0; if (event.pageX) { result = event.pageX } else { if (originalEvent && originalEvent.pageX) { result = originalEvent.pageX } } if (originalEvent && originalEvent.touches) { if (originalEvent.touches.length > 0) { result = originalEvent.touches[0].pageX } else { if (originalEvent.changedTouches.length > 0) { result = originalEvent.changedTouches[0].pageX } } } return result } function initializeAreaEvents(controller, area, state, getRootOffsetLeft) { var isTouchEvent, initialPosition, isActive = false, movingHandler = null, docEvents = {}; docEvents[pointerEvents.move] = function(e) { var position, offset; if (isTouchEvent !== isTouchEventArgs(e)) { return } if (!isLeftButtonPressed(e)) { cancel() } if (isActive) { position = getEventPageX(e); offset = getRootOffsetLeft(); if (movingHandler) { movingHandler(position - offset) } else { if (state.manualRangeSelectionEnabled && Math.abs(initialPosition - position) >= MIN_MANUAL_SELECTING_WIDTH) { movingHandler = controller.placeSliderAndBeginMoving(initialPosition - offset, position - offset) } } } }; docEvents[pointerEvents.up] = function(e) { var position; if (isActive) { position = getEventPageX(e); if (!movingHandler && state.moveSelectedRangeByClick && Math.abs(initialPosition - position) < MIN_MANUAL_SELECTING_WIDTH) { controller.moveSelectedArea(position - getRootOffsetLeft()) } cancel() } }; function cancel() { if (isActive) { isActive = false; if (movingHandler) { movingHandler.complete(); movingHandler = null } } } area.on(pointerEvents.down, function(e) { if (!state.enabled || !isLeftButtonPressed(e) || isActive) { return } isActive = true; isTouchEvent = isTouchEventArgs(e); initialPosition = getEventPageX(e) }); return docEvents } function initializeSelectedAreaEvents(controller, area, state, getRootOffsetLeft) { var isTouchEvent, isActive = false, movingHandler = null, docEvents = {}; docEvents[pointerEvents.move] = function(e) { if (isTouchEvent !== isTouchEventArgs(e)) { return } if (!isLeftButtonPressed(e)) { cancel() } if (isActive) { preventDefault(e); movingHandler(getEventPageX(e) - getRootOffsetLeft()) } }; docEvents[pointerEvents.up] = cancel; function cancel() { if (isActive) { isActive = false; movingHandler.complete(); movingHandler = null } } area.on(pointerEvents.down, function(e) { if (!state.enabled || !isLeftButtonPressed(e) || isActive) { return } isActive = true; isTouchEvent = isTouchEventArgs(e); movingHandler = controller.beginSelectedAreaMoving(getEventPageX(e) - getRootOffsetLeft()); stopPropagationAndPreventDefault(e) }); return docEvents } function initializeSliderEvents(controller, sliders, state, getRootOffsetLeft) { var isTouchEvent, isActive = false, movingHandler = null, docEvents = {}; docEvents[pointerEvents.move] = function(e) { if (isTouchEvent !== isTouchEventArgs(e)) { return } if (!isLeftButtonPressed(e)) { cancel() } if (isActive) { preventDefault(e); movingHandler(getEventPageX(e) - getRootOffsetLeft()) } }; docEvents[pointerEvents.up] = cancel; $.each(sliders, function(i, slider) { var events = {}; events[pointerEvents.down] = function(e) { if (!state.enabled || !isLeftButtonPressed(e) || isActive) { return } isActive = true; isTouchEvent = isTouchEventArgs(e); movingHandler = controller.beginSliderMoving(i, getEventPageX(e) - getRootOffsetLeft()); stopPropagationAndPreventDefault(e) }; events[pointerEvents.move] = function() { if (!movingHandler) { controller.foregroundSlider(i) } }; slider.on(events) }); function cancel() { if (isActive) { isActive = false; movingHandler.complete(); movingHandler = null } } return docEvents } function Tracker(params) { var state = this._state = {}, targets = params.controller.getTrackerTargets(); if (msPointerEnabled) { params.renderer.root.css({ msTouchAction: "pinch-zoom" }) } this._docEvents = [initializeSelectedAreaEvents(params.controller, targets.selectedArea, state, getRootOffsetLeft), initializeAreaEvents(params.controller, targets.area, state, getRootOffsetLeft), initializeSliderEvents(params.controller, targets.sliders, state, getRootOffsetLeft)]; $.each(this._docEvents, function(_, events) { $(document).on(events) }); function getRootOffsetLeft() { return params.renderer.getRootOffset().left } } Tracker.prototype = { constructor: Tracker, dispose: function() { $.each(this._docEvents, function(_, events) { $(document).off(events) }) }, update: function(enabled, behavior) { var state = this._state; state.enabled = enabled; state.moveSelectedRangeByClick = behavior.moveSelectedRangeByClick; state.manualRangeSelectionEnabled = behavior.manualRangeSelectionEnabled } }; exports.Tracker = Tracker }, /*!*********************************************!*\ !*** ./js/viz/range_selector/range_view.js ***! \*********************************************/ function(module, exports) { function drawSeriesView(root, seriesDataSource, translator, canvas, isAnimationEnabled) { var series, i, valueAxis, seriesList = seriesDataSource.getSeries(), ii = seriesList.length; seriesDataSource.adjustSeriesDimensions(); if (!seriesList.length) { return } valueAxis = seriesList[0].getValueAxis(); valueAxis.setBusinessRange(seriesDataSource.getBoundRange().val); valueAxis.updateCanvas({ top: canvas.top, bottom: 0, height: canvas.height + canvas.top }); for (i = 0; i < ii; ++i) { series = seriesList[i]; series._extGroups.seriesGroup = series._extGroups.labelsGroup = root; series.draw(isAnimationEnabled) } } function merge(a, b) { return void 0 !== a ? a : b } function RangeView(params) { this._params = params; this._clipRect = params.renderer.clipRect(); params.root.attr({ "clip-path": this._clipRect.id }) } RangeView.prototype = { constructor: RangeView, update: function(backgroundOption, backgroundTheme, canvas, isCompactMode, isAnimationEnabled, seriesDataSource) { var seriesGroup, renderer = this._params.renderer, root = this._params.root, canvasWidth = canvas.width - canvas.left; backgroundOption = backgroundOption || {}; root.clear(); this._clipRect.attr({ x: canvas.left, y: canvas.top, width: canvasWidth, height: canvas.height }); if (!isCompactMode) { if (merge(backgroundOption.visible, backgroundTheme.visible)) { if (backgroundOption.color) { renderer.rect(canvas.left, canvas.top, canvasWidth + 1, canvas.height).attr({ fill: merge(backgroundOption.color, backgroundTheme.color), "class": "dx-range-selector-background" }).append(root) } if (backgroundOption.image && backgroundOption.image.url) { renderer.image(canvas.left, canvas.top, canvasWidth + 1, canvas.height, backgroundOption.image.url, merge(backgroundOption.image.location, backgroundTheme.image.location)).append(root) } } if (seriesDataSource && seriesDataSource.isShowChart()) { seriesGroup = renderer.g().attr({ "class": "dxrs-series-group" }).append(root); drawSeriesView(seriesGroup, seriesDataSource, this._params.translator, canvas, isAnimationEnabled) } } } }; exports.RangeView = RangeView }, /*!*****************************************************!*\ !*** ./js/viz/range_selector/series_data_source.js ***! \*****************************************************/ function(module, exports, __webpack_require__) { var SeriesDataSource, $ = __webpack_require__( /*! ../../core/renderer */ 9), seriesModule = __webpack_require__( /*! ../series/base_series */ 525), seriesFamilyModule = __webpack_require__( /*! ../core/series_family */ 580), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, vizUtils = __webpack_require__( /*! ../core/utils */ 509), rangeModule = __webpack_require__( /*! ../translators/range */ 564), dataValidatorModule = __webpack_require__( /*! ../components/data_validator */ 523), ChartThemeManager = __webpack_require__( /*! ../components/chart_theme_manager */ 549).ThemeManager; var createThemeManager = function(chartOptions) { return new ChartThemeManager(chartOptions, "rangeSelector.chart") }; var processSeriesFamilies = function(series, equalBarWidth, minBubbleSize, maxBubbleSize, barWidth, negativesAsZeroes) { var families = [], types = []; $.each(series, function(i, item) { if (inArray(item.type, types) === -1) { types.push(item.type) } }); $.each(types, function(_, type) { var family = new seriesFamilyModule.SeriesFamily({ type: type, equalBarWidth: equalBarWidth, minBubbleSize: minBubbleSize, maxBubbleSize: maxBubbleSize, barWidth: barWidth, negativesAsZeroes: negativesAsZeroes }); family.add(series); family.adjustSeriesValues(); families.push(family) }); return families }; var isStickType = function(type) { var nonStickTypes = ["bar", "candlestick", "stock", "bubble"], stickType = true; type = vizUtils.normalizeEnum(type); $.each(nonStickTypes, function(_, item) { if (type.indexOf(item) !== -1) { stickType = false; return false } }); return stickType }; function setTemplateFields(data, templateData, series) { $.each(data, function(_, data) { $.each(series.getTemplateFields(), function(_, field) { data[field.templateField] = data[field.originalField] }); templateData.push(data) }); series.updateTemplateFieldNames() } SeriesDataSource = function(options) { var templatedSeries, seriesTemplate, topIndent, bottomIndent, negativesAsZeroes, negativesAsZeros, that = this, themeManager = that._themeManager = createThemeManager(options.chart); themeManager._fontFields = ["commonSeriesSettings.label.font"]; themeManager.setTheme(options.chart.theme); topIndent = themeManager.getOptions("topIndent"); bottomIndent = themeManager.getOptions("bottomIndent"); that._indent = { top: topIndent >= 0 && topIndent < 1 ? topIndent : 0, bottom: bottomIndent >= 0 && bottomIndent < 1 ? bottomIndent : 0 }; that._valueAxis = themeManager.getOptions("valueAxisRangeSelector") || {}; that._hideChart = false; seriesTemplate = themeManager.getOptions("seriesTemplate"); if (options.dataSource && seriesTemplate) { templatedSeries = vizUtils.processSeriesTemplate(seriesTemplate, options.dataSource) } that._useAggregation = options.chart.useAggregation; that._series = that._calculateSeries(options, templatedSeries); negativesAsZeroes = themeManager.getOptions("negativesAsZeroes"); negativesAsZeros = themeManager.getOptions("negativesAsZeros"); that._seriesFamilies = processSeriesFamilies(that._series, themeManager.getOptions("equalBarWidth"), themeManager.getOptions("minBubbleSize"), themeManager.getOptions("maxBubbleSize"), themeManager.getOptions("barWidth"), commonUtils.isDefined(negativesAsZeroes) ? negativesAsZeroes : negativesAsZeros) }; SeriesDataSource.prototype = { constructor: SeriesDataSource, _calculateSeries: function(options, templatedSeries) { var particularSeriesOptions, seriesTheme, data, parsedData, dataSourceField, i, newSeries, groupsData, that = this, series = [], chartThemeManager = that._themeManager, hasSeriesTemplate = !!chartThemeManager.getOptions("seriesTemplate"), allSeriesOptions = hasSeriesTemplate ? templatedSeries : options.chart.series, seriesValueType = options.chart.valueAxis && options.chart.valueAxis.valueType; that.templateData = []; if (options.dataSource && !allSeriesOptions) { dataSourceField = options.dataSourceField || "arg"; allSeriesOptions = { argumentField: dataSourceField, valueField: dataSourceField }; that._hideChart = true } allSeriesOptions = Array.isArray(allSeriesOptions) ? allSeriesOptions : allSeriesOptions ? [allSeriesOptions] : []; for (i = 0; i < allSeriesOptions.length; i++) { particularSeriesOptions = extend(true, { incidentOccurred: options.incidentOccurred }, allSeriesOptions[i]); particularSeriesOptions.rotated = false; data = particularSeriesOptions.data || options.dataSource; seriesTheme = chartThemeManager.getOptions("series", particularSeriesOptions); seriesTheme.argumentField = seriesTheme.argumentField || options.dataSourceField; if (data && data.length > 0) { newSeries = new seriesModule.Series({ renderer: options.renderer, argumentAxis: options.argumentAxis, valueAxis: options.valueAxis }, seriesTheme); series.push(newSeries) } if (hasSeriesTemplate) { setTemplateFields(data, that.templateData, newSeries) } } data = hasSeriesTemplate ? that.templateData : data; if (series.length) { groupsData = { groups: [{ series: series, valueOptions: { valueType: dataSourceField ? options.valueType : seriesValueType } }], argumentOptions: { categories: options.categories, argumentType: options.valueType, type: options.axisType } }; parsedData = dataValidatorModule.validateData(data, groupsData, options.incidentOccurred, chartThemeManager.getOptions("dataPrepareSettings")); that.argCategories = groupsData.categories; for (i = 0; i < series.length; i++) { series[i].updateData(parsedData[series[i].getArgumentField()]) } } return series }, adjustSeriesDimensions: function() { if (this._useAggregation) { $.each(this._series, function(_, s) { s.resamplePoints(s.getArgumentAxis().getTranslator().canvasLength) }) } $.each(this._seriesFamilies, function(_, family) { family.adjustSeriesDimensions() }) }, getBoundRange: function() { var rangeData, rangeYSize, rangeVisibleSizeY, minIndent, maxIndent, that = this, valueAxisMin = that._valueAxis.min, valueAxisMax = that._valueAxis.max, valRange = new rangeModule.Range({ min: valueAxisMin, minVisible: valueAxisMin, max: valueAxisMax, maxVisible: valueAxisMax, axisType: that._valueAxis.type, base: that._valueAxis.logarithmBase }), argRange = new rangeModule.Range({}); $.each(that._series, function(_, series) { rangeData = series.getRangeData(); valRange.addRange(rangeData.val); argRange.addRange(rangeData.arg); if (!isStickType(series.type)) { argRange.addRange({ stick: false }) } }); if (valRange.isDefined() && argRange.isDefined()) { minIndent = that._valueAxis.inverted ? that._indent.top : that._indent.bottom; maxIndent = that._valueAxis.inverted ? that._indent.bottom : that._indent.top; rangeYSize = valRange.max - valRange.min; rangeVisibleSizeY = (commonUtils.isNumeric(valRange.maxVisible) ? valRange.maxVisible : valRange.max) - (commonUtils.isNumeric(valRange.minVisible) ? valRange.minVisible : valRange.min); if (commonUtils.isDate(valRange.min)) { valRange.min = new Date(valRange.min.valueOf() - rangeYSize * minIndent) } else { valRange.min -= rangeYSize * minIndent } if (commonUtils.isDate(valRange.max)) { valRange.max = new Date(valRange.max.valueOf() + rangeYSize * maxIndent) } else { valRange.max += rangeYSize * maxIndent } if (commonUtils.isNumeric(rangeVisibleSizeY)) { valRange.maxVisible = valRange.maxVisible ? valRange.maxVisible + rangeVisibleSizeY * maxIndent : void 0; valRange.minVisible = valRange.minVisible ? valRange.minVisible - rangeVisibleSizeY * minIndent : void 0 } valRange.invert = that._valueAxis.inverted } return { arg: argRange, val: valRange } }, getSeries: function() { return this._series }, isEmpty: function() { return 0 === this.getSeries().length }, isShowChart: function() { return !this._hideChart }, getCalculatedValueType: function() { var series = this._series[0]; return series && series.argumentType }, getThemeManager: function() { return this._themeManager } }; exports.SeriesDataSource = SeriesDataSource }, /*!************************************************!*\ !*** ./js/viz/range_selector/theme_manager.js ***! \************************************************/ function(module, exports, __webpack_require__) { var BaseThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager; exports.ThemeManager = BaseThemeManager.inherit({ _themeSection: "rangeSelector", _fontFields: ["scale.label.font", "sliderMarker.font", "loadingIndicator.font", "export.font", "title.font", "title.subtitle.font"] }) }, /*!******************************!*\ !*** ./js/viz/vector_map.js ***! \******************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./vector_map/vector_map */ 614) }, /*!*****************************************!*\ !*** ./js/viz/vector_map/vector_map.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, _parseScalar = __webpack_require__( /*! ../core/utils */ 509).parseScalar, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, projectionModule = __webpack_require__( /*! ./projection.main */ 615), controlBarModule = __webpack_require__( /*! ./control_bar */ 617), gestureHandlerModule = __webpack_require__( /*! ./gesture_handler */ 618), trackerModule = __webpack_require__( /*! ./tracker */ 619), themeManagerModule = __webpack_require__( /*! ./theme_manager */ 620), dataExchangerModule = __webpack_require__( /*! ./data_exchanger */ 621), legendModule = __webpack_require__( /*! ./legend */ 622), layoutModule = __webpack_require__( /*! ./layout */ 623), mapLayerModule = __webpack_require__( /*! ./map_layer */ 624), tooltipViewerModule = __webpack_require__( /*! ./tooltip_viewer */ 625), _noop = noop, _extend = extend, DEFAULT_WIDTH = 800, DEFAULT_HEIGHT = 400, nextDataKey = 1, RE_STARTS_LAYERS = /^layers/, RE_ENDS_DATA_SOURCE = /\.(dataSource|data)$/; __webpack_require__( /*! ./projection */ 626); function generateDataKey() { return "vectormap-data-" + nextDataKey++ } var dxVectorMap = __webpack_require__( /*! ../core/base_widget */ 515).inherit({ _eventsMap: { onClick: { name: "click" }, onCenterChanged: { name: "centerChanged" }, onZoomFactorChanged: { name: "zoomFactorChanged" }, onAreaClick: { name: "areaClick" }, onAreaHoverChanged: { name: "areaHoverChanged" }, onAreaSelectionChanged: { name: "areaSelectionChanged" }, onMarkerClick: { name: "markerClick" }, onMarkerHoverChanged: { name: "markerHoverChanged" }, onMarkerSelectionChanged: { name: "markerSelectionChanged" }, onHoverChanged: { name: "hoverChanged" }, onSelectionChanged: { name: "selectionChanged" } }, _setDeprecatedOptions: function() { this.callBase.apply(this, arguments); _extend(this._deprecatedOptions, { areaSettings: { since: "15.2", message: "Use the 'layers' option instead" }, markerSettings: { since: "15.2", message: "Use the 'layers' option instead" }, mapData: { since: "15.2", message: "Use the 'layers' option instead" }, markers: { since: "15.2", message: "Use the 'layers' option instead" }, onAreaClick: { since: "15.2", message: "Use the 'onClick' option instead" }, onMarkerClick: { since: "15.2", message: "Use the 'onClick' option instead" }, onAreaHoverChanged: { since: "15.2", message: "Use the 'onHoverChanged' option instead" }, onMarkerHoverChanged: { since: "15.2", message: "Use the 'onHoverChanged' option instead" }, onAreaSelectionChanged: { since: "15.2", message: "Use the 'onSelectionChanged' option instead" }, onMarkerSelectionChanged: { since: "15.2", message: "Use the 'onSelectionChanged' option instead" }, "layers.data": { since: "15.2", message: "Use the 'layers.dataSource' option instead" } }) }, _rootClassPrefix: "dxm", _rootClass: "dxm-vector-map", _createThemeManager: function() { return new themeManagerModule.ThemeManager }, _initLayerCollection: function(dataKey) { var that = this; that._layerCollection = new mapLayerModule.MapLayerCollection({ renderer: that._renderer, projection: that._projection, themeManager: that._themeManager, tracker: that._tracker, dataKey: dataKey, eventTrigger: that._eventTrigger, dataExchanger: that._dataExchanger, tooltip: that._tooltip, notifyDirty: that._notifyDirty, notifyReady: that._notifyReady }); if (void 0 === that._options.layers && (that._options.mapData || that._options.markers)) { applyDeprecatedMode(that) } else { suspendLayersData(that._layerCollection, that._options.layers) } }, _initLegendsControl: function() { var that = this; that._legendsControl = new legendModule.LegendsControl({ renderer: that._renderer, container: that._root, layoutControl: that._layoutControl, themeManager: that._themeManager, dataExchanger: that._dataExchanger, notifyDirty: that._notifyDirty, notifyReady: that._notifyReady }) }, _initControlBar: function(dataKey) { var that = this; that._controlBar = new controlBarModule.ControlBar({ renderer: that._renderer, container: that._root, layoutControl: that._layoutControl, projection: that._projection, tracker: that._tracker, dataKey: dataKey }) }, _initElements: function() { var that = this, dataKey = generateDataKey(), notifyCounter = 0; that._notifyDirty = function() { that._resetIsReady(); ++notifyCounter }; that._notifyReady = function() { if (0 === --notifyCounter) { that._drawn() } }; that._dataExchanger = new dataExchangerModule.DataExchanger; that._projection = new projectionModule.Projection({ centerChanged: function(value) { if (that._initialized) { that._eventTrigger("centerChanged", { center: value }) } }, zoomChanged: function(value) { if (that._initialized) { that._eventTrigger("zoomFactorChanged", { zoomFactor: value }) } } }); that._tracker = new trackerModule.Tracker({ root: that._root, projection: that._projection, dataKey: dataKey }); that._gestureHandler = new gestureHandlerModule.GestureHandler({ projection: that._projection, renderer: that._renderer, tracker: that._tracker }); that._layoutControl = new layoutModule.LayoutControl; that._layoutControl.suspend(); that._initLayerCollection(dataKey); that._initControlBar(dataKey); that._initLegendsControl(); that._tooltipViewer = new tooltipViewerModule.TooltipViewer({ tracker: that._tracker, tooltip: that._tooltip, layerCollection: that._layerCollection }) }, _init: function() { this.callBase.apply(this, arguments); this._afterInit(); this._layoutControl.resume() }, _initialChanges: ["PROJECTION", "BOUNDS", "MAX_ZOOM_FACTOR", "ZOOM_FACTOR", "CENTER"], _afterInit: function() { resumeLayersData(this._layerCollection, this._options.layers, this._renderer) }, _initCore: function() { this._root = this._renderer.root.attr({ align: "center", cursor: "default" }); this._initElements() }, _disposeCore: function() { var that = this; that._controlBar.dispose(); that._gestureHandler.dispose(); that._tracker.dispose(); that._legendsControl.dispose(); that._layerCollection.dispose(); that._layoutControl.dispose(); that._tooltipViewer.dispose(); that._dataExchanger.dispose(); that._projection.dispose(); that._dataExchanger = that._gestureHandler = that._projection = that._tracker = that._layoutControl = that._root = that._layerCollection = that._controlBar = that._legendsControl = null }, _setupInteraction: function() { var options = { centeringEnabled: !!_parseScalar(this._getOption("panningEnabled", true), true), zoomingEnabled: !!_parseScalar(this._getOption("zoomingEnabled", true), true) }; this._gestureHandler.setInteraction(options); this._controlBar.setInteraction(options) }, _getDefaultSize: function() { return { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT } }, _applySize: function(rect) { var layout = { left: rect[0], top: rect[1], width: rect[2] - rect[0], height: rect[3] - rect[1], right: 0, bottom: 0 }; this._projection.setSize(layout); this._layoutControl.setSize(layout); this._layerCollection.setRect([layout.left, layout.top, layout.width, layout.height]) }, _optionChanging: function(name, currentValue, nextValue) { if (currentValue && nextValue) { if (RE_STARTS_LAYERS.test(name)) { if (currentValue.dataSource && nextValue.dataSource && currentValue !== nextValue) { currentValue.dataSource = null } else { if (currentValue.data && nextValue.data && currentValue !== nextValue) { currentValue.data = null } else { if (RE_ENDS_DATA_SOURCE.test(name)) { this.option(name, null) } } } } if ("mapData" === name) { this._options.mapData = null } if ("markers" === name) { this._options.markers = null } } }, _applyChanges: function() { this._notifyDirty(); this.callBase.apply(this, arguments); this._notifyReady() }, _optionChangesMap: { background: "BACKGROUND", layers: "LAYERS", areaSettings: "LAYERS", markerSettings: "LAYERS", mapData: "LAYERS", markers: "LAYERS", controlBar: "CONTROL_BAR", legends: "LEGENDS", touchEnabled: "TRACKER", wheelEnabled: "TRACKER", panningEnabled: "INTERACTION", zoomingEnabled: "INTERACTION", projection: "PROJECTION", bounds: "BOUNDS", maxZoomFactor: "MAX_ZOOM_FACTOR", zoomFactor: "ZOOM_FACTOR", center: "CENTER" }, _optionChangesOrder: ["PROJECTION", "BOUNDS", "MAX_ZOOM_FACTOR", "ZOOM_FACTOR", "CENTER", "BACKGROUND", "LAYERS", "CONTROL_BAR", "LEGENDS", "TRACKER", "INTERACTION"], _change_PROJECTION: function() { this._setProjection() }, _change_BOUNDS: function() { this._setBounds() }, _change_MAX_ZOOM_FACTOR: function() { this._setMaxZoom() }, _change_ZOOM_FACTOR: function() { this._setZoom() }, _change_CENTER: function() { this._setCenter() }, _change_BACKGROUND: function() { this._setBackgroundOptions() }, _change_LAYERS: function() { this._setLayerCollectionOptions() }, _change_CONTROL_BAR: function() { this._setControlBarOptions() }, _change_LEGENDS: function() { this._setLegendsOptions() }, _change_TRACKER: function() { this._setTrackerOptions() }, _change_INTERACTION: function() { this._setupInteraction() }, _themeDependentChanges: ["BACKGROUND", "LAYERS", "CONTROL_BAR", "LEGENDS", "TRACKER", "INTERACTION"], _setProjection: function() { this._projection.setEngine(this.option("projection")) }, _setBounds: function() { this._projection.setBounds(this.option("bounds")) }, _setMaxZoom: function() { this._projection.setMaxZoom(this.option("maxZoomFactor")) }, _setZoom: function() { this._projection.setZoom(this.option("zoomFactor")) }, _setCenter: function() { this._projection.setCenter(this.option("center")) }, _setBackgroundOptions: function() { this._layerCollection.setBackgroundOptions(this._getOption("background")) }, _setLayerCollectionOptions: function() { this._layerCollection.setOptions(this.option("layers")) }, _setControlBarOptions: function() { this._controlBar.setOptions(this._getOption("controlBar")) }, _setLegendsOptions: function() { this._legendsControl.setOptions(this.option("legends")) }, _setTrackerOptions: function() { this._tracker.setOptions({ touchEnabled: this._getOption("touchEnabled", true), wheelEnabled: this._getOption("wheelEnabled", true) }) }, getLayers: function() { var i, layers = this._layerCollection.items(), list = [], ii = list.length = layers.length; for (i = 0; i < ii; ++i) { list[i] = layers[i].proxy } return list }, getLayerByIndex: function(index) { var layer = this._layerCollection.byIndex(index); return layer ? layer.proxy : null }, getLayerByName: function(name) { var layer = this._layerCollection.byName(name); return layer ? layer.proxy : null }, clearSelection: function(_noEvent) { var i, layers = this._layerCollection.items(), ii = layers.length; for (i = 0; i < ii; ++i) { layers[i].clearSelection(_noEvent) } return this }, getAreas: _noop, getMarkers: _noop, clearAreaSelection: _noop, clearMarkerSelection: _noop, center: function(value) { var that = this; if (void 0 === value) { return that._projection.getCenter() } else { that._projection.setCenter(value); return that } }, zoomFactor: function(value) { var that = this; if (void 0 === value) { return that._projection.getZoom() } else { that._projection.setZoom(value); return that } }, viewport: function(value) { var that = this; if (void 0 === value) { return that._projection.getViewport() } else { that._projection.setViewport(value); return that } }, convertCoordinates: function(coordinates) { coordinates = coordinates && coordinates.length ? coordinates : [arguments[0], arguments[1]]; return this._projection.fromScreenPoint(coordinates) } }); function suspendLayersData(layerCollection, options) { if (options) { layerCollection.__data = options.length ? $.map(options, patch) : patch(options) } function patch(ops) { var result = {}; swapData(ops || {}, result); return result } } function resumeLayersData(layerCollection, options, renderer) { var data = layerCollection.__data; if (data) { layerCollection.__data = void 0; if (data.length) { $.each(data, function(i, item) { swapData(item, options[i]) }) } else { swapData(data, options) } renderer.lock(); layerCollection.setOptions(options); renderer.unlock() } } function swapData(source, target) { var name = !("dataSource" in source) && "data" in source ? "data" : "dataSource"; target[name] = source[name]; source[name] = void 0 } function applyDeprecatedMode(map) { var log = __webpack_require__( /*! ../../core/errors */ 7).log, mapData = map._options.mapData, markers = map._options.markers; map._options.mapData = map._options.markers = void 0; map._afterInit = function() { this._options.mapData = mapData; this._options.markers = markers; this._renderer.lock(); this._setLayerCollectionOptions(); this._renderer.unlock(); mapData = markers = void 0 }; map._setLayerCollectionOptions = function() { var options = this._options, mapData = options.mapData, markers = options.markers; mapData = mapData && mapData.features ? _extend({}, mapData) : mapData; markers = markers && markers.features ? _extend({}, markers) : markers; this._layerCollection.setOptions([_extend({}, options.areaSettings, { name: "areas", _deprecated: true, dataSource: mapData, type: "area" }), _extend({}, options.markerSettings, { name: "markers", _deprecated: true, dataSource: markers, type: "marker", elementType: options.markerSettings && options.markerSettings.type })]) }; map.getAreas = function() { log("W0002", this.NAME, "getAreas", "15.2", "Use the 'getLayerByName('areas').getElements()' instead"); return this.getLayerByName("areas").getElements() }; map.getMarkers = function() { log("W0002", this.NAME, "getMarkers", "15.2", "Use the 'getLayerByName('markers').getElements()' instead"); return this.getLayerByName("markers").getElements() }; map.clearAreaSelection = function(_noEvent) { log("W0002", this.NAME, "clearAreaSelection", "15.2", "Use the 'getLayerByName('areas').clearSelection()' instead"); this.getLayerByName("areas").clearSelection(_noEvent); return this }; map.clearMarkerSelection = function(_noEvent) { log("W0002", this.NAME, "clearMarkerSelection", "15.2", "Use the 'getLayerByName('markers').clearSelection()' instead"); this.getLayerByName("markers").clearSelection(_noEvent); return this }; var clickMap = { areas: "areaClick", markers: "markerClick" }, hoverChangedMap = { areas: "areaHoverChanged", markers: "markerHoverChanged" }, selectionChangedMap = { areas: "areaSelectionChanged", markers: "markerSelectionChanged" }; map.on("click", function(e) { if (e.target) { this._eventTrigger(clickMap[e.target.layer.name], e) } }); map.on("hoverChanged", function(e) { if (e.target) { this._eventTrigger(hoverChangedMap[e.target.layer.name], e) } }); map.on("selectionChanged", function(e) { if (e.target) { this._eventTrigger(selectionChangedMap[e.target.layer.name], e) } }) } __webpack_require__( /*! ../../core/component_registrator */ 57)("dxVectorMap", dxVectorMap); module.exports = dxVectorMap; module.exports._TESTS_resetDataKey = function() { nextDataKey = 1 }; dxVectorMap.addPlugin(__webpack_require__( /*! ../core/export */ 511).plugin); dxVectorMap.addPlugin(__webpack_require__( /*! ../core/title */ 558).plugin); dxVectorMap.addPlugin(__webpack_require__( /*! ../core/tooltip */ 559).plugin); dxVectorMap.addPlugin(__webpack_require__( /*! ../core/loading_indicator */ 560).plugin) }, /*!**********************************************!*\ !*** ./js/viz/vector_map/projection.main.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, eventEmitterModule = __webpack_require__( /*! ./event_emitter */ 616); var _Number = Number, _min = Math.min, _max = Math.max, _abs = Math.abs, _round = Math.round, _ln = Math.log, _pow = Math.pow, TWO_TO_LN2 = 2 / Math.LN2, MIN_BOUNDS_RANGE = 1 / 3600 / 180 / 10, DEFAULT_MIN_ZOOM = 1, DEFAULT_MAX_ZOOM = 256, DEFAULT_CENTER = [NaN, NaN], DEFAULT_ENGINE_NAME = "mercator"; function floatsEqual(f1, f2) { return _abs(f1 - f2) < 1e-8 } function arraysEqual(a1, a2) { return floatsEqual(a1[0], a2[0]) && floatsEqual(a1[1], a2[1]) } function parseAndClamp(value, minValue, maxValue, defaultValue) { var val = _Number(value); return isFinite(val) ? _min(_max(val, minValue), maxValue) : defaultValue } function parseAndClampArray(value, minValue, maxValue, defaultValue) { return [parseAndClamp(value[0], minValue[0], maxValue[0], defaultValue[0]), parseAndClamp(value[1], minValue[1], maxValue[1], defaultValue[1])] } function getEngine(engine) { return engine instanceof Engine && engine || projection.get(engine) || projection.get(DEFAULT_ENGINE_NAME) } function Projection(parameters) { var that = this; that._initEvents(); that._params = parameters; that._engine = getEngine(); that._center = that._engine.center(); that._adjustCenter() } Projection.prototype = { constructor: Projection, _minZoom: DEFAULT_MIN_ZOOM, _maxZoom: DEFAULT_MAX_ZOOM, _zoom: DEFAULT_MIN_ZOOM, _center: DEFAULT_CENTER, _canvas: {}, _scale: [], dispose: function() { this._disposeEvents() }, setEngine: function(value) { var that = this, engine = getEngine(value); if (that._engine !== engine) { that._engine = engine; that._fire("engine"); if (that._changeCenter(engine.center())) { that._triggerCenterChanged() } if (that._changeZoom(that._minZoom)) { that._triggerZoomChanged() } that._adjustCenter(); that._setupScreen() } }, setBounds: function(bounds) { if (void 0 !== bounds) { this.setEngine(this._engine.original().bounds(bounds)) } }, _setupScreen: function() { var that = this, canvas = that._canvas, width = canvas.width, height = canvas.height, aspectRatio = that._engine.ar(); that._x0 = canvas.left + width / 2; that._y0 = canvas.top + height / 2; if (width / height <= aspectRatio) { that._xRadius = width / 2; that._yRadius = width / 2 / aspectRatio } else { that._xRadius = height / 2 * aspectRatio; that._yRadius = height / 2 } that._fire("screen") }, setSize: function(canvas) { var that = this; that._canvas = canvas; that._setupScreen() }, _toScreen: function(coordinates) { return [this._x0 + this._xRadius * coordinates[0], this._y0 + this._yRadius * coordinates[1]] }, _fromScreen: function(coordinates) { return [(coordinates[0] - this._x0) / this._xRadius, (coordinates[1] - this._y0) / this._yRadius] }, _toTransformed: function(coordinates) { return [coordinates[0] * this._zoom + this._xCenter, coordinates[1] * this._zoom + this._yCenter] }, _toTransformedFast: function(coordinates) { return [coordinates[0] * this._zoom, coordinates[1] * this._zoom] }, _fromTransformed: function(coordinates) { return [(coordinates[0] - this._xCenter) / this._zoom, (coordinates[1] - this._yCenter) / this._zoom] }, _adjustCenter: function() { var that = this, center = that._engine.project(that._center); that._xCenter = -center[0] * that._zoom || 0; that._yCenter = -center[1] * that._zoom || 0 }, project: function(coordinates) { return this._engine.project(coordinates) }, transform: function(coordinates) { return this._toScreen(this._toTransformedFast(coordinates)) }, isInvertible: function() { return this._engine.isInvertible() }, getSquareSize: function(size) { return [size[0] * this._zoom * this._xRadius, size[1] * this._zoom * this._yRadius] }, getZoom: function() { return this._zoom }, _changeZoom: function(value) { var that = this, oldZoom = that._zoom, newZoom = that._zoom = parseAndClamp(value, that._minZoom, that._maxZoom, that._minZoom), isChanged = !floatsEqual(oldZoom, newZoom); if (isChanged) { that._adjustCenter(); that._fire("zoom") } return isChanged }, setZoom: function(value) { if (this._engine.isInvertible() && this._changeZoom(value)) { this._triggerZoomChanged() } }, getScaledZoom: function() { return _round((this._scale.length - 1) * _ln(this._zoom) / _ln(this._maxZoom)) }, setScaledZoom: function(scaledZoom) { this.setZoom(this._scale[_round(scaledZoom)]) }, changeScaledZoom: function(deltaZoom) { this.setZoom(this._scale[_max(_min(_round(this.getScaledZoom() + deltaZoom), this._scale.length - 1), 0)]) }, getZoomScalePartition: function() { return this._scale.length - 1 }, _setupScaling: function() { var step, zoom, that = this, k = _round(TWO_TO_LN2 * _ln(that._maxZoom)), i = 1; k = k > 4 ? k : 4; step = _pow(that._maxZoom, 1 / k); zoom = that._minZoom; that._scale = [zoom]; for (; i <= k; ++i) { that._scale.push(zoom *= step) } }, setMaxZoom: function(maxZoom) { var that = this; that._minZoom = DEFAULT_MIN_ZOOM; that._maxZoom = parseAndClamp(maxZoom, that._minZoom, _Number.MAX_VALUE, DEFAULT_MAX_ZOOM); that._setupScaling(); if (that._zoom > that._maxZoom) { that.setZoom(that._maxZoom) } that._fire("max-zoom") }, getCenter: function() { return this._center.slice() }, setCenter: function(value) { if (this._engine.isInvertible() && this._changeCenter(value || [])) { this._triggerCenterChanged() } }, _changeCenter: function(value) { var that = this, engine = that._engine, oldCenter = that._center, newCenter = that._center = parseAndClampArray(value, engine.min(), engine.max(), engine.center()), isChanged = !arraysEqual(oldCenter, newCenter); if (isChanged) { that._adjustCenter(); that._fire("center") } return isChanged }, _triggerCenterChanged: function() { this._params.centerChanged(this.getCenter()) }, _triggerZoomChanged: function() { this._params.zoomChanged(this.getZoom()) }, setCenterByPoint: function(coordinates, screenPosition) { var that = this, p = that._engine.project(coordinates), q = that._fromScreen(screenPosition); that.setCenter(that._engine.unproject([-q[0] / that._zoom + p[0], -q[1] / that._zoom + p[1]])) }, beginMoveCenter: function() { if (this._engine.isInvertible()) { this._moveCenter = this._center } }, endMoveCenter: function() { var that = this; if (that._moveCenter) { if (!arraysEqual(that._moveCenter, that._center)) { that._triggerCenterChanged() } that._moveCenter = null } }, moveCenter: function(shift) { var current, center, that = this; if (that._moveCenter) { current = that._toScreen(that._toTransformed(that._engine.project(that._center))); center = that._engine.unproject(that._fromTransformed(that._fromScreen([current[0] + shift[0], current[1] + shift[1]]))); that._changeCenter(center) } }, getViewport: function() { var that = this, unproject = that._engine.unproject, lt = unproject(that._fromTransformed([-1, -1])), lb = unproject(that._fromTransformed([-1, 1])), rt = unproject(that._fromTransformed([1, -1])), rb = unproject(that._fromTransformed([1, 1])), minMax = findMinMax([selectFarthestPoint(lt[0], lb[0], rt[0], rb[0]), selectFarthestPoint(lt[1], rt[1], lb[1], rb[1])], [selectFarthestPoint(rt[0], rb[0], lt[0], lb[0]), selectFarthestPoint(lb[1], rb[1], lt[1], rt[1])]); return [].concat(minMax.min, minMax.max) }, setViewport: function(viewport) { var engine = this._engine, data = viewport ? getZoomAndCenterFromViewport(engine.project, engine.unproject, viewport) : [this._minZoom, engine.center()]; this.setZoom(data[0]); this.setCenter(data[1]) }, getTransform: function() { return { translateX: this._xCenter * this._xRadius, translateY: this._yCenter * this._yRadius } }, fromScreenPoint: function(coordinates) { return this._engine.unproject(this._fromTransformed(this._fromScreen(coordinates))) }, _eventNames: ["engine", "screen", "center", "zoom", "max-zoom"] }; eventEmitterModule.makeEventEmitter(Projection); function selectFarthestPoint(point1, point2, basePoint1, basePoint2) { var basePoint = (basePoint1 + basePoint2) / 2; return _abs(point1 - basePoint) > _abs(point2 - basePoint) ? point1 : point2 } function selectClosestPoint(point1, point2, basePoint1, basePoint2) { var basePoint = (basePoint1 + basePoint2) / 2; return _abs(point1 - basePoint) < _abs(point2 - basePoint) ? point1 : point2 } function getZoomAndCenterFromViewport(project, unproject, viewport) { var lt = project([viewport[0], viewport[3]]), lb = project([viewport[0], viewport[1]]), rt = project([viewport[2], viewport[3]]), rb = project([viewport[2], viewport[1]]), l = selectClosestPoint(lt[0], lb[0], rt[0], rb[0]), r = selectClosestPoint(rt[0], rb[0], lt[0], lb[0]), t = selectClosestPoint(lt[1], rt[1], lb[1], rb[1]), b = selectClosestPoint(lb[1], rb[1], lt[1], rt[1]); return [2 / _max(_abs(l - r), _abs(t - b)), unproject([(l + r) / 2, (t + b) / 2])] } function setMinMax(engine, p1, p2) { var minMax = findMinMax(p1, p2); engine.min = returnArray(minMax.min); engine.max = returnArray(minMax.max) } function Engine(parameters) { var that = this, project = createProjectMethod(parameters.to), unproject = parameters.from ? createUnprojectMethod(parameters.from) : returnValue(DEFAULT_CENTER); that.project = project; that.unproject = unproject; that.original = returnValue(that); that.source = function() { return extend({}, parameters) }; that.isInvertible = returnValue(!!parameters.from); that.ar = returnValue(parameters.aspectRatio > 0 ? _Number(parameters.aspectRatio) : 1); that.center = returnArray(unproject([0, 0])); setMinMax(that, [unproject([-1, 0])[0], unproject([0, 1])[1]], [unproject([1, 0])[0], unproject([0, -1])[1]]) } Engine.prototype.aspectRatio = function(aspectRatio) { var engine = new Engine(extend(this.source(), { aspectRatio: aspectRatio })); engine.original = this.original; engine.min = this.min; engine.max = this.max; return engine }; Engine.prototype.bounds = function(bounds) { bounds = bounds || []; var engine, parameters = this.source(), min = this.min(), max = this.max(), b1 = parseAndClampArray([bounds[0], bounds[1]], min, max, min), b2 = parseAndClampArray([bounds[2], bounds[3]], min, max, max), p1 = parameters.to(b1), p2 = parameters.to(b2), delta = _min(_abs(p2[0] - p1[0]) > MIN_BOUNDS_RANGE ? _abs(p2[0] - p1[0]) : 2, _abs(p2[1] - p1[1]) > MIN_BOUNDS_RANGE ? _abs(p2[1] - p1[1]) : 2); if (delta < 2) { extend(parameters, createProjectUnprojectMethods(parameters.to, parameters.from, p1, p2, delta)) } engine = new Engine(parameters); engine.original = this.original; setMinMax(engine, b1, b2); return engine }; function isEngine(engine) { return engine instanceof Engine } function invertVerticalAxis(pair) { return [pair[0], -pair[1]] } function createProjectMethod(method) { return function(arg) { return invertVerticalAxis(method(arg)) } } function createUnprojectMethod(method) { return function(arg) { return method(invertVerticalAxis(arg)) } } function returnValue(value) { return function() { return value } } function returnArray(value) { return function() { return value.slice() } } function projection(parameters) { return parameters && parameters.to ? new Engine(parameters) : null } function findMinMax(p1, p2) { return { min: [_min(p1[0], p2[0]), _min(p1[1], p2[1])], max: [_max(p1[0], p2[0]), _max(p1[1], p2[1])] } } var projectionsCache = {}; projection.get = function(name) { return projectionsCache[name] || null }; projection.add = function(name, engine) { if (!projectionsCache[name] && isEngine(engine)) { projectionsCache[name] = engine } return projection }; function createProjectUnprojectMethods(project, unproject, p1, p2, delta) { var x0 = (p1[0] + p2[0]) / 2 - delta / 2, y0 = (p1[1] + p2[1]) / 2 - delta / 2, k = 2 / delta; return { to: function(coordinates) { var p = project(coordinates); return [-1 + (p[0] - x0) * k, -1 + (p[1] - y0) * k] }, from: function(coordinates) { var p = [x0 + (coordinates[0] + 1) / k, y0 + (coordinates[1] + 1) / k]; return unproject(p) } } } exports.Projection = Projection; exports.projection = projection; exports._TESTS_Engine = Engine }, /*!********************************************!*\ !*** ./js/viz/vector_map/event_emitter.js ***! \********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9); var eventEmitterMethods = { _initEvents: function() { var i, names = this._eventNames, ii = names.length, events = this._events = {}; for (i = 0; i < ii; ++i) { events[names[i]] = $.Callbacks() } }, _disposeEvents: function() { var name, events = this._events; for (name in events) { events[name].empty() } this._events = null }, on: function(handlers) { var name, events = this._events; for (name in handlers) { events[name].add(handlers[name]) } return dispose; function dispose() { for (name in handlers) { events[name].remove(handlers[name]) } } }, _fire: function(name, arg) { this._events[name].fire(arg) } }; exports.makeEventEmitter = function(target) { var name, proto = target.prototype; for (name in eventEmitterMethods) { proto[name] = eventEmitterMethods[name] } }; exports._TESTS_eventEmitterMethods = eventEmitterMethods }, /*!******************************************!*\ !*** ./js/viz/vector_map/control_bar.js ***! \******************************************/ function(module, exports, __webpack_require__) { var _math = Math, _min = _math.min, _max = _math.max, _round = _math.round, _floor = _math.floor, _sqrt = _math.sqrt, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _parseScalar = vizUtils.parseScalar, parseHorizontalAlignment = vizUtils.enumParser(["left", "center", "right"]), parseVerticalAlignment = vizUtils.enumParser(["top", "bottom"]), COMMAND_RESET = "command-reset", COMMAND_MOVE_UP = "command-move-up", COMMAND_MOVE_RIGHT = "command-move-right", COMMAND_MOVE_DOWN = "command-move-down", COMMAND_MOVE_LEFT = "command-move-left", COMMAND_ZOOM_IN = "command-zoom-in", COMMAND_ZOOM_OUT = "command-zoom-out", COMMAND_ZOOM_DRAG_LINE = "command-zoom-drag-line", COMMAND_ZOOM_DRAG = "command-zoom-drag", EVENT_TARGET_TYPE = "control-bar", FLAG_CENTERING = 1, FLAG_ZOOMING = 2, SIZE_OPTIONS = { bigCircleSize: 58, smallCircleSize: 28, buttonSize: 10, arrowButtonOffset: 20, incDecButtonSize: 11, incButtonOffset: 66, decButtonOffset: 227, sliderLineStartOffset: 88.5, sliderLineEndOffset: 205.5, sliderLength: 20, sliderWidth: 8, trackerGap: 4 }, OFFSET_X = 30.5, OFFSET_Y = 30.5, TOTAL_WIDTH = 61, TOTAL_HEIGHT = 274, COMMAND_TO_TYPE_MAP = {}; COMMAND_TO_TYPE_MAP[COMMAND_RESET] = ResetCommand; COMMAND_TO_TYPE_MAP[COMMAND_MOVE_UP] = COMMAND_TO_TYPE_MAP[COMMAND_MOVE_RIGHT] = COMMAND_TO_TYPE_MAP[COMMAND_MOVE_DOWN] = COMMAND_TO_TYPE_MAP[COMMAND_MOVE_LEFT] = MoveCommand; COMMAND_TO_TYPE_MAP[COMMAND_ZOOM_IN] = COMMAND_TO_TYPE_MAP[COMMAND_ZOOM_OUT] = ZoomCommand; COMMAND_TO_TYPE_MAP[COMMAND_ZOOM_DRAG] = ZoomDragCommand; function ControlBar(parameters) { var that = this; that._params = parameters; that._createElements(parameters.renderer, parameters.container, parameters.dataKey); parameters.layoutControl.addItem(that); that._subscribeToProjection(parameters.projection); that._subscribeToTracker(parameters.tracker); that._createCallbacks(parameters.projection) } ControlBar.prototype = { constructor: ControlBar, _flags: 0, dispose: function() { var that = this; that._params.layoutControl.removeItem(that); that._root.linkRemove().linkOff(); that._offProjection(); that._offTracker(); that._params = that._root = that._offProjection = that._offTracker = that._callbacks = null }, _subscribeToProjection: function(projection) { var that = this; that._offProjection = projection.on({ engine: function() { that._update() }, zoom: updateZoom, "max-zoom": function() { that._zoomPartition = projection.getZoomScalePartition(); that._sliderUnitLength = that._sliderLineLength / that._zoomPartition; updateZoom() } }); function updateZoom() { that._adjustZoom(projection.getScaledZoom()) } }, _subscribeToTracker: function(tracker) { var that = this, isActive = false; that._offTracker = tracker.on({ start: function(arg) { isActive = arg.data.name === EVENT_TARGET_TYPE; if (isActive) { that._processStart(arg.data.index, arg) } }, move: function(arg) { if (isActive) { that._processMove(arg.data.index, arg) } }, end: function() { if (isActive) { that._processEnd(); isActive = false } } }) }, _createCallbacks: function(projection) { var that = this; that._callbacks = { reset: function(isCenter, isZoom) { if (isCenter) { projection.setCenter(null) } if (isZoom) { projection.setZoom(null) } }, beginMove: function() { projection.beginMoveCenter() }, endMove: function() { projection.endMoveCenter() }, move: function(shift) { projection.moveCenter(shift) }, zoom: function(zoom) { projection.setScaledZoom(zoom) } } }, _createElements: function(renderer, container, dataKey) { var buttonsGroups, trackersGroup, that = this; that._root = renderer.g().attr({ "class": "dxm-control-bar" }).linkOn(container, "control-bar"); buttonsGroups = that._buttonsGroup = renderer.g().attr({ "class": "dxm-control-buttons" }).append(that._root); trackersGroup = renderer.g().attr({ stroke: "none", "stroke-width": 0, fill: "#000000", opacity: 1e-4 }).css({ cursor: "pointer" }).append(that._root); that._createButtons(renderer, dataKey, buttonsGroups); that._createTrackers(renderer, dataKey, trackersGroup) }, _createButtons: function(renderer, dataKey, group) { var that = this, options = SIZE_OPTIONS, size = options.buttonSize / 2, offset1 = options.arrowButtonOffset - size, offset2 = options.arrowButtonOffset, incDecButtonSize = options.incDecButtonSize / 2, directionOptions = { "stroke-linecap": "square", fill: "none" }, line = "line"; renderer.circle(0, 0, options.bigCircleSize / 2).append(group); renderer.circle(0, 0, size).attr({ fill: "none" }).append(group); renderer.path([-size, -offset1, 0, -offset2, size, -offset1], line).attr(directionOptions).append(group); renderer.path([offset1, -size, offset2, 0, offset1, size], line).attr(directionOptions).append(group); renderer.path([size, offset1, 0, offset2, -size, offset1], line).attr(directionOptions).append(group); renderer.path([-offset1, size, -offset2, 0, -offset1, -size], line).attr(directionOptions).append(group); renderer.circle(0, options.incButtonOffset, options.smallCircleSize / 2).append(group); renderer.path([ [-incDecButtonSize, options.incButtonOffset, incDecButtonSize, options.incButtonOffset], [0, options.incButtonOffset - incDecButtonSize, 0, options.incButtonOffset + incDecButtonSize] ], "area").append(group); renderer.circle(0, options.decButtonOffset, options.smallCircleSize / 2).append(group); renderer.path([-incDecButtonSize, options.decButtonOffset, incDecButtonSize, options.decButtonOffset], "area").append(group); that._zoomLine = renderer.path([], "line").append(group); that._zoomDrag = renderer.rect(_floor(-options.sliderLength / 2), _floor(options.sliderLineEndOffset - options.sliderWidth / 2), options.sliderLength, options.sliderWidth).append(group); that._sliderLineLength = options.sliderLineEndOffset - options.sliderLineStartOffset }, _createTrackers: function(renderer, dataKey, group) { var options = SIZE_OPTIONS, size = _round((options.arrowButtonOffset - options.trackerGap) / 2), offset1 = options.arrowButtonOffset - size, offset2 = _round(_sqrt(options.bigCircleSize * options.bigCircleSize / 4 - size * size)), size2 = offset2 - offset1; renderer.rect(-size, -size, 2 * size, 2 * size).data(dataKey, { index: COMMAND_RESET, name: EVENT_TARGET_TYPE }).append(group); renderer.rect(-size, -offset2, 2 * size, size2).data(dataKey, { index: COMMAND_MOVE_UP, name: EVENT_TARGET_TYPE }).append(group); renderer.rect(offset1, -size, size2, 2 * size).data(dataKey, { index: COMMAND_MOVE_RIGHT, name: EVENT_TARGET_TYPE }).append(group); renderer.rect(-size, offset1, 2 * size, size2).data(dataKey, { index: COMMAND_MOVE_DOWN, name: EVENT_TARGET_TYPE }).append(group); renderer.rect(-offset2, -size, size2, 2 * size).data(dataKey, { index: COMMAND_MOVE_LEFT, name: EVENT_TARGET_TYPE }).append(group); renderer.circle(0, options.incButtonOffset, options.smallCircleSize / 2).data(dataKey, { index: COMMAND_ZOOM_IN, name: EVENT_TARGET_TYPE }).append(group); renderer.circle(0, options.decButtonOffset, options.smallCircleSize / 2).data(dataKey, { index: COMMAND_ZOOM_OUT, name: EVENT_TARGET_TYPE }).append(group); renderer.rect(-2, options.sliderLineStartOffset - 2, 4, options.sliderLineEndOffset - options.sliderLineStartOffset + 4).css({ cursor: "default" }).data(dataKey, { index: COMMAND_ZOOM_DRAG_LINE, name: EVENT_TARGET_TYPE }).append(group); this._zoomDragTracker = renderer.rect(-options.sliderLength / 2, options.sliderLineEndOffset - options.sliderWidth / 2, options.sliderLength, options.sliderWidth).data(dataKey, { index: COMMAND_ZOOM_DRAG, name: EVENT_TARGET_TYPE }).append(group) }, resize: function(size) { if (this._isActive) { this._root.attr({ visibility: null !== size ? null : "hidden" }) } }, getLayoutOptions: function() { return this._isActive ? this._layoutOptions : null }, locate: function(x, y) { this._root.attr({ translateX: x + this._margin + OFFSET_X, translateY: y + this._margin + OFFSET_Y }) }, _update: function() { var that = this; that._isActive = that._isEnabled && that._flags && that._params.projection.isInvertible(); if (that._isActive) { that._root.linkAppend() } else { that._root.linkRemove() } that._processEnd(); that.updateLayout() }, setInteraction: function(interaction) { var that = this; if (_parseScalar(interaction.centeringEnabled, true)) { that._flags |= FLAG_CENTERING } else { that._flags &= ~FLAG_CENTERING } if (_parseScalar(interaction.zoomingEnabled, true)) { that._flags |= FLAG_ZOOMING } else { that._flags &= ~FLAG_ZOOMING } that._update() }, setOptions: function(options) { var that = this; that._isEnabled = !!_parseScalar(options.enabled, true); that._margin = options.margin || 0; that._layoutOptions = { width: 2 * that._margin + TOTAL_WIDTH, height: 2 * that._margin + TOTAL_HEIGHT, horizontalAlignment: parseHorizontalAlignment(options.horizontalAlignment, "left"), verticalAlignment: parseVerticalAlignment(options.verticalAlignment, "top") }; that._buttonsGroup.attr({ "stroke-width": options.borderWidth, stroke: options.borderColor, fill: options.color, "fill-opacity": options.opacity }); that._update() }, _adjustZoom: function(zoom) { var transform, y, that = this, start = SIZE_OPTIONS.sliderLineStartOffset, end = SIZE_OPTIONS.sliderLineEndOffset, h = SIZE_OPTIONS.sliderWidth; that._zoomFactor = _max(_min(_round(zoom), that._zoomPartition), 0); transform = { translateY: -_round(that._zoomFactor * that._sliderUnitLength) }; y = end - h / 2 + transform.translateY; that._zoomLine.attr({ points: [ [0, start, 0, _max(start, y)], [0, _min(end, y + h), 0, end] ] }); that._zoomDrag.attr(transform); that._zoomDragTracker.attr(transform) }, _applyZoom: function() { this._callbacks.zoom(this._zoomFactor) }, _processStart: function(command, arg) { var commandType; if (this._isActive) { commandType = COMMAND_TO_TYPE_MAP[command]; this._command = commandType && commandType.flags & this._flags ? new commandType(this, command, arg) : null } }, _processMove: function(command, arg) { this._command && this._command.update(command, arg) }, _processEnd: function() { this._command && this._command.finish(); this._command = null } }; function disposeCommand(command) { delete command._owner; command.update = function() {}; command.finish = function() {} } function ResetCommand(owner, command) { this._owner = owner; this._command = command } ResetCommand.flags = FLAG_CENTERING | FLAG_ZOOMING; ResetCommand.prototype.update = function(command) { command !== this._command && disposeCommand(this) }; ResetCommand.prototype.finish = function() { var flags = this._owner._flags; this._owner._callbacks.reset(!!(flags & FLAG_CENTERING), !!(flags & FLAG_ZOOMING)); disposeCommand(this) }; function MoveCommand(owner, command, arg) { this._command = command; var timeout = null, interval = 100, dx = 0, dy = 0; switch (this._command) { case COMMAND_MOVE_UP: dy = -10; break; case COMMAND_MOVE_RIGHT: dx = 10; break; case COMMAND_MOVE_DOWN: dy = 10; break; case COMMAND_MOVE_LEFT: dx = -10 } function callback() { owner._callbacks.move([dx, dy]); timeout = setTimeout(callback, interval) } this._stop = function() { clearTimeout(timeout); owner._callbacks.endMove(); this._stop = owner = null; return this }; arg = null; owner._callbacks.beginMove(); callback() } MoveCommand.flags = FLAG_CENTERING; MoveCommand.prototype.update = function(command) { this._command !== command && this.finish() }; MoveCommand.prototype.finish = function() { disposeCommand(this._stop()) }; function ZoomCommand(owner, command) { this._owner = owner; this._command = command; var timeout = null, interval = 150, dZoom = this._command === COMMAND_ZOOM_IN ? 1 : -1; function callback() { owner._adjustZoom(owner._zoomFactor + dZoom); timeout = setTimeout(callback, interval) } this._stop = function() { clearTimeout(timeout); this._stop = owner = null; return this }; callback() } ZoomCommand.flags = FLAG_ZOOMING; ZoomCommand.prototype.update = function(command) { this._command !== command && this.finish() }; ZoomCommand.prototype.finish = function() { this._owner._applyZoom(); disposeCommand(this._stop()) }; function ZoomDragCommand(owner, command, arg) { this._owner = owner; this._zoomFactor = owner._zoomFactor; this._pos = arg.y } ZoomDragCommand.flags = FLAG_ZOOMING; ZoomDragCommand.prototype.update = function(command, arg) { var owner = this._owner; owner._adjustZoom(this._zoomFactor + owner._zoomPartition * (this._pos - arg.y) / owner._sliderLineLength) }; ZoomDragCommand.prototype.finish = function() { this._owner._applyZoom(); disposeCommand(this) }; exports.ControlBar = ControlBar; var COMMAND_TO_TYPE_MAP__ORIGINAL = COMMAND_TO_TYPE_MAP; exports._TESTS_stubCommandToTypeMap = function(map) { COMMAND_TO_TYPE_MAP = map }; exports._TESTS_restoreCommandToTypeMap = function() { COMMAND_TO_TYPE_MAP = COMMAND_TO_TYPE_MAP__ORIGINAL } }, /*!**********************************************!*\ !*** ./js/viz/vector_map/gesture_handler.js ***! \**********************************************/ function(module, exports) { var _ln = Math.log, _LN2 = Math.LN2; function GestureHandler(params) { var that = this; that._projection = params.projection; that._renderer = params.renderer; that._x = that._y = 0; that._subscribeToTracker(params.tracker) } GestureHandler.prototype = { constructor: GestureHandler, dispose: function() { this._offTracker(); this._offTracker = null }, _subscribeToTracker: function(tracker) { var that = this, isActive = false; that._offTracker = tracker.on({ start: function(arg) { isActive = "control-bar" !== arg.data.name; if (isActive) { that._processStart(arg) } }, move: function(arg) { if (isActive) { that._processMove(arg) } }, end: function() { if (isActive) { that._processEnd() } }, zoom: function(arg) { that._processZoom(arg) } }) }, setInteraction: function(options) { this._processEnd(); this._centeringEnabled = options.centeringEnabled; this._zoomingEnabled = options.zoomingEnabled }, _processStart: function(arg) { if (this._centeringEnabled) { this._x = arg.x; this._y = arg.y; this._projection.beginMoveCenter() } }, _processMove: function(arg) { var that = this; if (that._centeringEnabled) { that._renderer.root.attr({ cursor: "move" }); that._projection.moveCenter([that._x - arg.x, that._y - arg.y]); that._x = arg.x; that._y = arg.y } }, _processEnd: function() { if (this._centeringEnabled) { this._renderer.root.attr({ cursor: "default" }); this._projection.endMoveCenter() } }, _processZoom: function(arg) { var delta, screenPosition, coords, that = this; if (that._zoomingEnabled) { if (arg.delta) { delta = arg.delta } else { if (arg.ratio) { delta = _ln(arg.ratio) / _LN2 } } if (that._centeringEnabled) { screenPosition = that._renderer.getRootOffset(); screenPosition = [arg.x - screenPosition.left, arg.y - screenPosition.top]; coords = that._projection.fromScreenPoint(screenPosition) } that._projection.changeScaledZoom(delta); if (that._centeringEnabled) { that._projection.setCenterByPoint(coords, screenPosition) } } } }; exports.GestureHandler = GestureHandler }, /*!**************************************!*\ !*** ./js/viz/vector_map/tracker.js ***! \**************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), _math = Math, _abs = _math.abs, _sqrt = _math.sqrt, _round = _math.round, eventEmitterModule = __webpack_require__( /*! ./event_emitter */ 616), eventUtils = __webpack_require__( /*! ../../events/utils */ 71), wheelEventName = __webpack_require__( /*! ../../events/core/wheel */ 85).name, _addNamespace = eventUtils.addNamespace, _parseScalar = __webpack_require__( /*! ../core/utils */ 509).parseScalar, _now = $.now, _NAME = "dxVectorMap", EVENTS = {}; setupEvents(); var EVENT_START = "start", EVENT_MOVE = "move", EVENT_END = "end", EVENT_ZOOM = "zoom", EVENT_HOVER_ON = "hover-on", EVENT_HOVER_OFF = "hover-off", EVENT_CLICK = "click", EVENT_FOCUS_ON = "focus-on", EVENT_FOCUS_MOVE = "focus-move", EVENT_FOCUS_OFF = "focus-off", CLICK_TIME_THRESHOLD = 500, CLICK_COORD_THRESHOLD_MOUSE = 5, CLICK_COORD_THRESHOLD_TOUCH = 20, DRAG_COORD_THRESHOLD_MOUSE = 5, DRAG_COORD_THRESHOLD_TOUCH = 10, FOCUS_ON_DELAY_MOUSE = 300, FOCUS_OFF_DELAY_MOUSE = 300, FOCUS_ON_DELAY_TOUCH = 300, FOCUS_OFF_DELAY_TOUCH = 400, FOCUS_COORD_THRESHOLD_MOUSE = 5, WHEEL_COOLDOWN = 50, WHEEL_DIRECTION_COOLDOWN = 300; function Tracker(parameters) { var that = this; that._root = parameters.root; that._createEventHandlers(parameters.dataKey); that._createProjectionHandlers(parameters.projection); that._initEvents(); that._focus = new Focus(function(name, arg) { that._fire(name, arg) }); that._attachHandlers() } Tracker.prototype = { constructor: Tracker, dispose: function() { var that = this; that._detachHandlers(); that._disposeEvents(); that._focus.dispose(); that._root = that._focus = that._docHandlers = that._rootHandlers = null }, _eventNames: [EVENT_START, EVENT_MOVE, EVENT_END, EVENT_ZOOM, EVENT_CLICK, EVENT_HOVER_ON, EVENT_HOVER_OFF, EVENT_FOCUS_ON, EVENT_FOCUS_OFF, EVENT_FOCUS_MOVE], _startClick: function(event, data) { if (!data) { return } var coords = getEventCoords(event); this._clickState = { x: coords.x, y: coords.y, threshold: isTouchEvent(event) ? CLICK_COORD_THRESHOLD_TOUCH : CLICK_COORD_THRESHOLD_MOUSE, time: _now() } }, _endClick: function(event, data) { var threshold, coords, state = this._clickState; if (!state) { return } if (data && _now() - state.time <= CLICK_TIME_THRESHOLD) { threshold = state.threshold; coords = getEventCoords(event); if (_abs(coords.x - state.x) <= threshold && _abs(coords.y - state.y) <= threshold) { this._fire(EVENT_CLICK, { data: data, x: coords.x, y: coords.y, $event: event }) } } this._clickState = null }, _startDrag: function(event, data) { if (!data) { return } var coords = getEventCoords(event), state = this._dragState = { x: coords.x, y: coords.y, data: data }; this._fire(EVENT_START, { x: state.x, y: state.y, data: state.data }) }, _moveDrag: function(event, data) { var coords, threshold, state = this._dragState; if (!state) { return } coords = getEventCoords(event); threshold = isTouchEvent(event) ? DRAG_COORD_THRESHOLD_TOUCH : DRAG_COORD_THRESHOLD_MOUSE; if (state.active || _abs(coords.x - state.x) > threshold || _abs(coords.y - state.y) > threshold) { state.x = coords.x; state.y = coords.y; state.active = true; state.data = data || {}; this._fire(EVENT_MOVE, { x: state.x, y: state.y, data: state.data }) } }, _endDrag: function() { var state = this._dragState; if (!state) { return } this._dragState = null; this._fire(EVENT_END, { x: state.x, y: state.y, data: state.data }) }, _wheelZoom: function(event, data) { if (!data) { return } var delta, coords, that = this, lock = that._wheelLock, time = _now(); if (time - lock.time <= WHEEL_COOLDOWN) { return } if (time - lock.dirTime > WHEEL_DIRECTION_COOLDOWN) { lock.dir = 0 } delta = adjustWheelDelta(event.delta / 120 || 0, lock); if (0 === delta) { return } coords = getEventCoords(event); that._fire(EVENT_ZOOM, { delta: delta, x: coords.x, y: coords.y }); lock.time = lock.dirTime = time }, _startZoom: function(event, data) { if (!isTouchEvent(event) || !data) { return } var coords, pointer2, state = this._zoomState = this._zoomState || {}; if (state.pointer1 && state.pointer2) { return } if (void 0 === state.pointer1) { state.pointer1 = getPointerId(event) || 0; coords = getMultitouchEventCoords(event, state.pointer1); state.x1 = state.x1_0 = coords.x; state.y1 = state.y1_0 = coords.y } if (void 0 === state.pointer2) { pointer2 = getPointerId(event) || 1; if (pointer2 !== state.pointer1) { coords = getMultitouchEventCoords(event, pointer2); if (coords) { state.x2 = state.x2_0 = coords.x; state.y2 = state.y2_0 = coords.y; state.pointer2 = pointer2; state.ready = true; this._endDrag() } } } }, _moveZoom: function(event) { var coords, state = this._zoomState; if (!state || !isTouchEvent(event)) { return } if (void 0 !== state.pointer1) { coords = getMultitouchEventCoords(event, state.pointer1); if (coords) { state.x1 = coords.x; state.y1 = coords.y } } if (void 0 !== state.pointer2) { coords = getMultitouchEventCoords(event, state.pointer2); if (coords) { state.x2 = coords.x; state.y2 = coords.y } } }, _endZoom: function(event) { var startDistance, currentDistance, state = this._zoomState; if (!state || !isTouchEvent(event)) { return } if (state.ready) { startDistance = getDistance(state.x1_0, state.y1_0, state.x2_0, state.y2_0); currentDistance = getDistance(state.x1, state.y1, state.x2, state.y2); this._fire(EVENT_ZOOM, { ratio: currentDistance / startDistance, x: (state.x1_0 + state.x2_0) / 2, y: (state.y1_0 + state.y2_0) / 2 }) } this._zoomState = null }, _startHover: function(event, data) { this._doHover(event, data, true) }, _moveHover: function(event, data) { this._doHover(event, data, false) }, _doHover: function(event, data, isTouch) { var that = this; if (that._dragState && that._dragState.active || that._zoomState && that._zoomState.ready) { that._cancelHover(); return } if (isTouchEvent(event) !== isTouch || that._hoverTarget === event.target || that._hoverState && that._hoverState.data === data) { return } that._cancelHover(); if (data) { that._hoverState = { data: data }; that._fire(EVENT_HOVER_ON, { data: data }) } that._hoverTarget = event.target }, _cancelHover: function() { var state = this._hoverState; this._hoverState = this._hoverTarget = null; if (state) { this._fire(EVENT_HOVER_OFF, { data: state.data }) } }, _startFocus: function(event, data) { this._doFocus(event, data, true) }, _moveFocus: function(event, data) { this._doFocus(event, data, false) }, _doFocus: function(event, data, isTouch) { var that = this; if (that._dragState && that._dragState.active || that._zoomState && that._zoomState.ready) { that._cancelFocus(); return } if (isTouchEvent(event) !== isTouch) { return } that._focus.turnOff(isTouch ? FOCUS_OFF_DELAY_TOUCH : FOCUS_OFF_DELAY_MOUSE); data && that._focus.turnOn(data, getEventCoords(event), isTouch ? FOCUS_ON_DELAY_TOUCH : FOCUS_ON_DELAY_MOUSE, isTouch) }, _endFocus: function(event) { if (!isTouchEvent(event)) { return } this._focus.cancelOn() }, _cancelFocus: function() { this._focus.cancel() }, _createEventHandlers: function(DATA_KEY) { var that = this; that._docHandlers = {}; that._rootHandlers = {}; that._rootHandlers[EVENTS.start] = that._docHandlers[EVENTS.start] = function(event) { var isTouch = isTouchEvent(event), data = getData(event); if (isTouch && !that._isTouchEnabled) { return } if (data) { event.preventDefault(); event.stopPropagation() } that._startClick(event, data); that._startDrag(event, data); that._startZoom(event, data); that._startHover(event, data); that._startFocus(event, data) }; that._docHandlers[EVENTS.move] = function(event) { var isTouch = isTouchEvent(event), data = getData(event); if (isTouch && !that._isTouchEnabled) { return } that._moveDrag(event, data); that._moveZoom(event, data); that._moveHover(event, data); that._moveFocus(event, data) }; that._docHandlers[EVENTS.end] = function(event) { var isTouch = isTouchEvent(event), data = getData(event); if (isTouch && !that._isTouchEnabled) { return } that._endClick(event, data); that._endDrag(event, data); that._endZoom(event, data); that._endFocus(event, data) }; that._rootHandlers[EVENTS.wheel] = function(event) { that._cancelFocus(); if (!that._isWheelEnabled) { return } var data = getData(event); if (data) { event.preventDefault(); event.stopPropagation(); that._wheelZoom(event, data) } }; that._wheelLock = { dir: 0 }; function getData(event) { var target = event.target; return ("tspan" === target.tagName ? target.parentNode : target)[DATA_KEY] } }, _createProjectionHandlers: function(projection) { var that = this; projection.on({ center: handler, zoom: handler }); function handler() { that._cancelFocus() } }, reset: function() { var that = this; that._clickState = null; that._endDrag(); that._cancelHover(); that._cancelFocus() }, setOptions: function(options) { var that = this; that.reset(); that._detachHandlers(); that._isTouchEnabled = !!_parseScalar(options.touchEnabled, true); that._isWheelEnabled = !!_parseScalar(options.wheelEnabled, true); that._attachHandlers() }, _detachHandlers: function() { var that = this; if (that._isTouchEnabled) { that._root.css({ "touch-action": "", "-ms-touch-action": "", "-webkit-user-select": "" }).off(_addNamespace("MSHoldVisual", _NAME)).off(_addNamespace("contextmenu", _NAME)) } $(document).off(that._docHandlers); that._root.off(that._rootHandlers) }, _attachHandlers: function() { var that = this; if (that._isTouchEnabled) { that._root.css({ "touch-action": "none", "-ms-touch-action": "none", "-webkit-user-select": "none" }).on(_addNamespace("MSHoldVisual", _NAME), function(event) { event.preventDefault() }).on(_addNamespace("contextmenu", _NAME), function(event) { isTouchEvent(event) && event.preventDefault() }) } $(document).on(that._docHandlers); that._root.on(that._rootHandlers) } }; var Focus = function(fire) { var _x, _y, that = this, _activeData = null, _data = null, _disabled = false, _onTimer = null, _offTimer = null; that.dispose = function() { clearTimeout(_onTimer); clearTimeout(_offTimer); that.turnOn = that.turnOff = that.cancel = that.cancelOn = that.dispose = that = fire = _activeData = _data = _onTimer = _offTimer = null }; that.turnOn = function(data, coords, timeout, forceTimeout) { if (data === _data && _disabled) { return } _disabled = false; _data = data; if (_activeData) { _x = coords.x; _y = coords.y; clearTimeout(_onTimer); _onTimer = setTimeout(function() { _onTimer = null; if (_data === _activeData) { fire(EVENT_FOCUS_MOVE, { data: _data, x: _x, y: _y }); onCheck(true) } else { fire(EVENT_FOCUS_ON, { data: _data, x: _x, y: _y, done: onCheck }) } }, forceTimeout ? timeout : 0) } else { if (!_onTimer || _abs(coords.x - _x) > FOCUS_COORD_THRESHOLD_MOUSE || _abs(coords.y - _y) > FOCUS_COORD_THRESHOLD_MOUSE || forceTimeout) { _x = coords.x; _y = coords.y; clearTimeout(_onTimer); _onTimer = setTimeout(function() { _onTimer = null; fire(EVENT_FOCUS_ON, { data: _data, x: _x, y: _y, done: onCheck }) }, timeout) } } function onCheck(result) { _disabled = !result; if (result) { _activeData = _data; clearTimeout(_offTimer); _offTimer = null } } }; that.turnOff = function(timeout) { clearTimeout(_onTimer); _onTimer = null; _data = null; if (_activeData && !_disabled) { _offTimer = _offTimer || setTimeout(function() { _offTimer = null; fire(EVENT_FOCUS_OFF, { data: _activeData }); _activeData = null }, timeout) } }; that.cancel = function() { clearTimeout(_onTimer); clearTimeout(_offTimer); if (_activeData) { fire(EVENT_FOCUS_OFF, { data: _activeData }) } _activeData = _data = _onTimer = _offTimer = null }; that.cancelOn = function() { clearTimeout(_onTimer); _onTimer = null } }; eventEmitterModule.makeEventEmitter(Tracker); exports.Tracker = Tracker; var originFocus = Focus; exports._DEBUG_forceEventMode = function(mode) { setupEvents(mode) }; exports.Focus = Focus; exports._DEBUG_stubFocusType = function(focusType) { Focus = focusType }; exports._DEBUG_restoreFocusType = function() { Focus = originFocus }; function getDistance(x1, y1, x2, y2) { return _sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) } function isTouchEvent(event) { var type = event.originalEvent.type, pointerType = event.originalEvent.pointerType; return /^touch/.test(type) || /^MSPointer/.test(type) && 4 !== pointerType || /^pointer/.test(type) && "mouse" !== pointerType } function selectItem(flags, items) { var item, i = 0, ii = flags.length; for (; i < ii; ++i) { if (flags[i]) { item = items[i]; break } } return _addNamespace(item || items[i], _NAME) } function setupEvents() { var flags = [navigator.pointerEnabled, navigator.msPointerEnabled, "ontouchstart" in window]; if (arguments.length) { flags = ["pointer" === arguments[0], "MSPointer" === arguments[0], "touch" === arguments[0]] } EVENTS = { start: selectItem(flags, ["pointerdown", "MSPointerDown", "touchstart mousedown", "mousedown"]), move: selectItem(flags, ["pointermove", "MSPointerMove", "touchmove mousemove", "mousemove"]), end: selectItem(flags, ["pointerup", "MSPointerUp", "touchend mouseup", "mouseup"]), wheel: _addNamespace(wheelEventName, _NAME) } } function getEventCoords(event) { var originalEvent = event.originalEvent, touch = originalEvent.touches && originalEvent.touches[0] || {}; return { x: touch.pageX || originalEvent.pageX || event.pageX, y: touch.pageY || originalEvent.pageY || event.pageY } } function getPointerId(event) { return event.originalEvent.pointerId } function getMultitouchEventCoords(event, pointerId) { var originalEvent = event.originalEvent; if (void 0 !== originalEvent.pointerId) { originalEvent = originalEvent.pointerId === pointerId ? originalEvent : null } else { originalEvent = originalEvent.touches[pointerId] } return originalEvent ? { x: originalEvent.pageX || event.pageX, y: originalEvent.pageY || event.pageY } : null } function adjustWheelDelta(delta, lock) { if (0 === delta) { return 0 } var _delta = _abs(delta), sign = _round(delta / _delta); if (lock.dir && sign !== lock.dir) { return 0 } lock.dir = sign; if (_delta < .1) { _delta = 0 } else { if (_delta < 1) { _delta = 1 } else { if (_delta > 4) { _delta = 4 } else { _delta = _round(_delta) } } } return sign * _delta } }, /*!********************************************!*\ !*** ./js/viz/vector_map/theme_manager.js ***! \********************************************/ function(module, exports, __webpack_require__) { var BaseThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager; exports.ThemeManager = BaseThemeManager.inherit({ _themeSection: "map", _fontFields: ["layer:area.label.font", "layer:marker:dot.label.font", "layer:marker:bubble.label.font", "layer:marker:pie.label.font", "layer:marker:image.label.font", "tooltip.font", "legend.font", "title.font", "title.subtitle.font", "loadingIndicator.font", "export.font"] }) }, /*!*********************************************!*\ !*** ./js/viz/vector_map/data_exchanger.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var _Callbacks = __webpack_require__( /*! ../../core/renderer */ 9).Callbacks; function DataExchanger() { this._store = {} } DataExchanger.prototype = { constructor: DataExchanger, dispose: function() { this._store = null; return this }, _get: function(category, name) { var store = this._store[category] || (this._store[category] = {}); return store[name] || (store[name] = { callbacks: _Callbacks() }) }, set: function(category, name, data) { var item = this._get(category, name); item.data = data; item.callbacks.fire(data); return this }, bind: function(category, name, callback) { var item = this._get(category, name); item.callbacks.add(callback); item.data && callback(item.data); return this }, unbind: function(category, name, callback) { var item = this._get(category, name); item.callbacks.remove(callback); return this } }; exports.DataExchanger = DataExchanger }, /*!*************************************!*\ !*** ./js/viz/vector_map/legend.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _extend = extend, _each = $.each, legendModule = __webpack_require__( /*! ../components/legend */ 521), _BaseLegend = legendModule.Legend; var sourceMap = { areacolorgroups: { category: "areas", name: "color" }, markercolorgroups: { category: "markers", name: "color" }, markersizegroups: { category: "markers", name: "size" } }; var unknownSource = { category: "UNKNOWN", name: "UNKNOWN" }; function parseSource(source) { var result; if ("string" === typeof source) { result = sourceMap[source.toLowerCase()] || unknownSource } else { result = { category: source.layer, name: source.grouping } } return result } function buildData(partition, values, field) { var i, item, ii = values.length, list = []; for (i = 0; i < ii; ++i) { list[i] = item = { start: partition[i], end: partition[i + 1], index: i }; item[field] = values[i]; item.states = { normal: { fill: item.color } } } return list } var Legend = function(parameters) { var that = this; that._params = parameters; that._root = parameters.renderer.g().attr({ "class": "dxm-legend" }).linkOn(parameters.container, { name: "legend", after: "legend-base" }).linkAppend(); parameters.layoutControl.addItem(that); _BaseLegend.call(that, { renderer: parameters.renderer, group: that._root, backgroundClass: null, itemsGroupClass: null, textField: "text", getFormatObject: function(data) { return data } }); that._onDataChanged = function(data) { that._updateData(data) } }; Legend.prototype = _extend(__webpack_require__( /*! ../../core/utils/object */ 27).clone(_BaseLegend.prototype), { constructor: Legend, dispose: function() { var that = this; that._params.layoutControl.removeItem(that); that._unbindData(); that._root.linkRemove().linkOff(); that._params = that._root = that._onDataChanged = null; return _BaseLegend.prototype.dispose.apply(that, arguments) }, resize: function(size) { this._params.notifyDirty(); if (null === size) { this.erase() } else { this.draw(size.width, size.height) } this._params.notifyReady() }, locate: _BaseLegend.prototype.shift, _updateData: function(data) { this.update(data ? buildData(data.partition, data.values, this._dataName) : [], this._options); this.updateLayout() }, _unbindData: function() { if (this._dataCategory) { this._params.dataExchanger.unbind(this._dataCategory, this._dataName, this._onDataChanged) } }, _bindData: function(arg) { this._params.dataExchanger.bind(this._dataCategory = arg.category, this._dataName = arg.name, this._onDataChanged) }, setOptions: function(options) { var that = this; that.update(that._data, options); that._unbindData(); that._bindData(options.source && parseSource(options.source) || unknownSource); that.updateLayout(); return that } }); function LegendsControl(parameters) { this._params = parameters; this._items = []; parameters.container.virtualLink("legend-base") } LegendsControl.prototype = { constructor: LegendsControl, dispose: function() { _each(this._items, function(_, item) { item.dispose() }); this._params = this._items = null }, setOptions: function(options) { var i, optionList = options && options.length ? options : [], items = this._items, ii = optionList.length, params = this._params, theme = params.themeManager.theme("legend"); for (i = items.length; i < ii; ++i) { items[i] = new Legend(params) } for (i = items.length - 1; i >= ii; --i) { items[i].dispose(); items.splice(i, 1) } params.layoutControl.suspend(); for (i = 0; i < ii; ++i) { items[i].setOptions(_extend(true, {}, theme, optionList[i])) } params.layoutControl.resume() } }; exports.LegendsControl = LegendsControl; var originalLegend = Legend; exports._TESTS_Legend = Legend; exports._TESTS_stubLegendType = function(stub) { Legend = stub }; exports._TESTS_restoreLegendType = function() { Legend = originalLegend } }, /*!*************************************!*\ !*** ./js/viz/vector_map/layout.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, _round = Math.round, _min = Math.min, _max = Math.max, _each = $.each, _inArray = inArray, horizontalAlignmentMap = { left: 0, center: 1, right: 2 }, verticalAlignmentMap = { top: 0, bottom: 1 }; function getCellIndex(options) { return 3 * verticalAlignmentMap[options.verticalAlignment] + horizontalAlignmentMap[options.horizontalAlignment] } function createCells(canvas, items) { var hStep = (canvas.right - canvas.left) / 3, vStep = (canvas.bottom - canvas.top) / 2, h1 = canvas.left, h2 = _round(h1 + hStep), h3 = _round(h1 + hStep + hStep), h4 = canvas.right, v1 = canvas.top, v2 = _round(v1 + vStep), v3 = canvas.bottom, cells = [{ rect: [h1, v1, h2, v2] }, { rect: [h2, v1, h3, v2], center: true }, { rect: [h3, v1, h4, v2], horInversion: true }, { rect: [h1, v2, h2, v3], verInversion: true }, { rect: [h2, v2, h3, v3], center: true, verInversion: true }, { rect: [h3, v2, h4, v3], horInversion: true, verInversion: true }], itemsList = [ [], [], [], [], [], [] ]; _each(items, function(_, item) { var options = item.getLayoutOptions(); if (options) { itemsList[getCellIndex(options)].push({ item: item, width: options.width, height: options.height }) } }); _each(cells, function(i, cell) { if (itemsList[i].length) { cell.items = itemsList[i] } else { if (cell.center) { cell.rect[0] = cell.rect[2] = (cell.rect[0] + cell.rect[2]) / 2 } else { cell.rect[cell.horInversion ? 0 : 2] = cell.rect[cell.horInversion ? 2 : 0] } cell.rect[cell.verInversion ? 1 : 3] = cell.rect[cell.verInversion ? 3 : 1] } }); return cells } function adjustCellSizes(cells) { _each([0, 1, 2, 3, 4, 5], function(_, index) { var cell = cells[index], otherCell = cells[(index + 3) % 6]; if (cell.items) { if (!otherCell.items) { cell.rect[1] = _min(cell.rect[1], otherCell.rect[3]); cell.rect[3] = _max(cell.rect[3], otherCell.rect[1]) } } }); _each([1, 4], function(_, index) { var size1, size2, cell = cells[index], otherCell1 = cells[index - 1], otherCell2 = cells[index + 1]; if (cell.items) { if (!otherCell1.items && !otherCell2.items) { size1 = cell.rect[0] - otherCell1.rect[2]; size2 = otherCell2.rect[0] - cell.rect[2]; if (size1 > size2) { if (size1 / size2 >= 2) { cell.rect[0] -= size1; cell.right = true } else { cell.rect[0] -= size2; cell.rect[2] += size2 } } else { if (size2 / size1 >= 2) { cell.rect[2] += size2; cell.center = null } else { cell.rect[0] -= size1; cell.rect[2] += size1 } } } } else { if (otherCell1.items) { otherCell1.rect[2] = (cell.rect[0] + cell.rect[2]) / 2 } if (otherCell2.items) { otherCell2.rect[0] = (cell.rect[0] + cell.rect[2]) / 2 } } }) } function adjustCellsAndApplyLayout(cells, forceMode) { var hasHiddenItems = false; adjustCellSizes(cells); _each(cells, function(_, cell) { if (cell.items) { hasHiddenItems = applyCellLayout(cell, forceMode) || hasHiddenItems } }); return hasHiddenItems } function applyCellLayout(cell, forceMode) { var cellRect = cell.rect, cellWidth = cellRect[2] - cellRect[0], cellHeight = cellRect[3] - cellRect[1], xOffset = 0, yOffset = 0, currentHeight = 0, totalL = cellRect[2], totalT = cellRect[3], totalR = cellRect[0], totalB = cellRect[1], moves = [], hasHiddenItems = false; _each(cell.items, function(_, item) { if (item.width > cellWidth || item.height > cellHeight) { moves.push(null); hasHiddenItems = true; return forceMode || false } if (xOffset + item.width > cellWidth) { yOffset += currentHeight; xOffset = currentHeight = 0 } if (yOffset + item.height > cellHeight) { moves.push(null); hasHiddenItems = true; return forceMode || false } currentHeight = _max(currentHeight, item.height); var dx = cell.horInversion ? cellRect[2] - item.width - xOffset : cellRect[0] + xOffset, dy = cell.verInversion ? cellRect[3] - item.height - yOffset : cellRect[1] + yOffset; xOffset += item.width; totalL = _min(totalL, dx); totalT = _min(totalT, dy); totalR = _max(totalR, dx + item.width); totalB = _max(totalB, dy + item.height); moves.push([dx, dy]) }); if (forceMode || !hasHiddenItems) { xOffset = 0; if (cell.right) { xOffset = cellRect[2] - cellRect[0] - totalR + totalL } else { if (cell.center) { xOffset = _round((cellRect[2] - cellRect[0] - totalR + totalL) / 2) } } _each(cell.items, function(i, item) { var move = moves[i]; if (move) { item.item.locate(move[0] + xOffset, move[1]) } else { item.item.resize(null) } }); cell.rect = [totalL, totalT, totalR, totalB]; cell.items = null } return hasHiddenItems } function applyLayout(canvas, items) { var cells = createCells(canvas, items); if (adjustCellsAndApplyLayout(cells)) { adjustCellsAndApplyLayout(cells, true) } } function LayoutControl() { var that = this; that._items = []; that._suspended = 0; that._updateLayout = function() { that._update() } } LayoutControl.prototype = { constructor: LayoutControl, dispose: function() { this._items = this._updateLayout = null }, setSize: function(canvas) { this._canvas = canvas; this._update() }, suspend: function() { ++this._suspended }, resume: function() { if (0 === --this._suspended) { this._update() } }, addItem: function(item) { this._items.push(item); item.updateLayout = this._updateLayout }, removeItem: function(item) { this._items.splice(_inArray(item, this._items), 1); item.updateLayout = null }, _update: function() { var canvas; if (0 === this._suspended) { canvas = this._canvas; _each(this._items, function(_, item) { item.resize(canvas) }); applyLayout({ left: canvas.left, top: canvas.top, right: canvas.width + canvas.left, bottom: canvas.height + canvas.top }, this._items) } } }; exports.LayoutControl = LayoutControl }, /*!****************************************!*\ !*** ./js/viz/vector_map/map_layer.js ***! \****************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _Number = Number, _String = String, _abs = Math.abs, _round = Math.round, _min = Math.min, _max = Math.max, _sqrt = Math.sqrt, _utils = __webpack_require__( /*! ../../core/utils/common */ 14), DataHelperMixin = __webpack_require__( /*! ../../data_helper */ 152), _isFunction = _utils.isFunction, _isArray = Array.isArray, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _parseScalar = vizUtils.parseScalar, _patchFontOptions = vizUtils.patchFontOptions, _normalizeEnum = vizUtils.normalizeEnum, _noop = noop, _extend = extend, _each = $.each, _concat = Array.prototype.concat, TYPE_AREA = "area", TYPE_LINE = "line", TYPE_MARKER = "marker", STATE_DEFAULT = 0, STATE_HOVERED = 1, STATE_SELECTED = 2, STATE_TO_INDEX = [0, 1, 2, 2], TOLERANCE = 1, SELECTIONS = { none: null, single: -1, multiple: NaN }; function getSelection(selectionMode) { var selection = _normalizeEnum(selectionMode); selection = selection in SELECTIONS ? SELECTIONS[selection] : SELECTIONS.single; if (null !== selection) { selection = { state: {}, single: selection } } return selection } function EmptySource() {} EmptySource.prototype.count = function() { return 0 }; function ArraySource(raw) { this.raw = raw } ArraySource.prototype = { constructor: ArraySource, count: function() { return this.raw.length }, item: function(index) { return this.raw[index] }, geometry: function(item) { return { coordinates: item.coordinates } }, attributes: function(item) { return item.attributes } }; function GeoJsonSource(raw) { this.raw = raw } GeoJsonSource.prototype = { constructor: GeoJsonSource, count: function() { return this.raw.features.length }, item: function(index) { return this.raw.features[index] }, geometry: function(item) { return item.geometry }, attributes: function(item) { return item.properties } }; function isGeoJsonObject(obj) { return _isArray(obj.features) } function unwrapFromDataSource(source) { var sourceType; if (source) { if (isGeoJsonObject(source)) { sourceType = GeoJsonSource } else { if (1 === source.length && source[0] && isGeoJsonObject(source[0])) { sourceType = GeoJsonSource; source = source[0] } else { if (_isArray(source)) { sourceType = ArraySource } } } } sourceType = sourceType || EmptySource; return new sourceType(source) } function wrapToDataSource(option) { return option ? isGeoJsonObject(option) ? [option] : option : [] } function customizeHandles(proxies, callback, widget) { callback.call(widget, proxies) } function customizeHandles_deprecated(proxies, callback) { var i, proxy, settings, ii = proxies.length; for (i = 0; i < ii; ++i) { proxy = proxies[i]; settings = callback.call(proxy, proxy) || {}; proxy.applySettings(settings); if (settings.isSelected) { proxy.selected(true) } } } function patchProxies(handles, name, data) { var i, dataItem, type = { areas: "area", markers: "marker" }[name], ii = handles.length; for (i = 0; i < ii; ++i) { handles[i].proxy.type = type } if ("marker" === type) { for (i = 0; i < ii; ++i) { dataItem = data.item(i); _extend(handles[i].proxy, { text: dataItem.text, value: dataItem.value, values: dataItem.values, url: dataItem.url }) } } } function setAreaLabelVisibility(label) { label.text.attr({ visibility: label.size[0] / label.spaceSize[0] < TOLERANCE && label.size[1] / label.spaceSize[1] < TOLERANCE ? null : "hidden" }) } function setLineLabelVisibility(label) { label.text.attr({ visibility: label.size[0] / label.spaceSize[0] < TOLERANCE || label.size[1] / label.spaceSize[1] < TOLERANCE ? null : "hidden" }) } function getDataValue(proxy, dataField, deprecatedField) { return proxy.attribute(dataField) || proxy[deprecatedField] } var TYPE_TO_TYPE_MAP = { Point: TYPE_MARKER, MultiPoint: TYPE_LINE, LineString: TYPE_LINE, MultiLineString: TYPE_LINE, Polygon: TYPE_AREA, MultiPolygon: TYPE_AREA }; function pick(a, b) { return void 0 !== a ? a : b } function guessTypeByData(sample) { var type = TYPE_TO_TYPE_MAP[sample.type], coordinates = sample.coordinates; if (!type) { if ("number" === typeof coordinates[0]) { type = TYPE_MARKER } else { if ("number" === typeof coordinates[0][0]) { type = TYPE_LINE } else { type = TYPE_AREA } } } return type } var selectStrategy = function(options, data) { var sample, type = _normalizeEnum(options.type), elementType = _normalizeEnum(options.elementType), strategy = _extend({}, emptyStrategy); if (data.count() > 0) { sample = data.geometry(data.item(0)); type = strategiesByType[type] ? type : guessTypeByData(sample); _extend(strategy, strategiesByType[type]); strategy.fullType = strategy.type = type; if (strategiesByGeometry[type]) { _extend(strategy, strategiesByGeometry[type](sample)) } if (strategiesByElementType[type]) { elementType = strategiesByElementType[type][elementType] ? elementType : strategiesByElementType[type]._default; _extend(strategy, strategiesByElementType[type][elementType]); strategy.elementType = elementType; strategy.fullType += ":" + elementType } } return strategy }; function applyElementState(figure, styles, state, field) { figure[field].attr(styles[field][state]) } var emptyStrategy = { setup: _noop, reset: _noop, arrange: _noop, updateGrouping: _noop }; var strategiesByType = {}; strategiesByType[TYPE_AREA] = { projectLabel: projectAreaLabel, transform: transformPointList, transformLabel: transformAreaLabel, draw: function(context, figure, data) { figure.root = context.renderer.path([], "area").data(context.dataKey, data) }, refresh: _noop, getLabelOffset: function(label) { setAreaLabelVisibility(label); return [0, 0] }, getStyles: function(settings) { var color = settings.color || null, borderColor = settings.borderColor || null, borderWidth = pick(settings.borderWidth, null), opacity = pick(settings.opacity, null); return { root: [{ "class": "dxm-area", stroke: borderColor, "stroke-width": borderWidth, fill: color, opacity: opacity }, { "class": "dxm-area dxm-area-hovered", stroke: settings.hoveredBorderColor || borderColor, "stroke-width": pick(settings.hoveredBorderWidth, borderWidth), fill: settings.hoveredColor || color, opacity: pick(settings.hoveredOpacity, opacity) }, { "class": "dxm-area dxm-area-selected", stroke: settings.selectedBorderColor || borderColor, "stroke-width": pick(settings.selectedBorderWidth, borderWidth), fill: settings.selectedColor || color, opacity: pick(settings.selectedOpacity, opacity) }] } }, setState: function(figure, styles, state) { applyElementState(figure, styles, state, "root") }, hasLabelsGroup: true, updateGrouping: function(context) { groupByColor(context) } }; strategiesByType[TYPE_LINE] = { projectLabel: projectLineLabel, transform: transformPointList, transformLabel: transformLineLabel, draw: function(context, figure, data) { figure.root = context.renderer.path([], "line").data(context.dataKey, data) }, refresh: _noop, getLabelOffset: function(label) { setLineLabelVisibility(label); return [0, 0] }, getStyles: function(settings) { var color = settings.color || settings.borderColor || null, width = pick(settings.borderWidth, null), opacity = pick(settings.opacity, null); return { root: [{ "class": "dxm-line", stroke: color, "stroke-width": width, opacity: opacity }, { "class": "dxm-line dxm-line-hovered", stroke: settings.hoveredColor || settings.hoveredBorderColor || color, "stroke-width": pick(settings.hoveredBorderWidth, width), opacity: pick(settings.hoveredOpacity, opacity) }, { "class": "dxm-line dxm-line-selected", stroke: settings.selectedColor || settings.selectedBorderColor || color, "stroke-width": pick(settings.selectedBorderWidth, width), opacity: pick(settings.selectedOpacity, opacity) }] } }, setState: function(figure, styles, state) { applyElementState(figure, styles, state, "root") }, hasLabelsGroup: true, updateGrouping: function(context) { groupByColor(context) } }; strategiesByType[TYPE_MARKER] = { project: projectPoint, transform: transformPoint, draw: function(context, figure, data) { figure.root = context.renderer.g(); this._draw(context, figure, data) }, refresh: _noop, hasLabelsGroup: false, getLabelOffset: function(label, settings) { return [_round((label.size[0] + _max(settings.size || 0, 0)) / 2) + 2, 0] }, getStyles: function(settings) { var styles = { root: [{ "class": "dxm-marker" }, { "class": "dxm-marker dxm-marker-hovered" }, { "class": "dxm-marker dxm-marker-selected" }] }; this._getStyles(styles, settings); return styles }, setState: function(figure, styles, state) { applyElementState(figure, styles, state, "root"); this._setState(figure, styles, state) }, updateGrouping: function(context) { groupByColor(context); groupBySize(context) } }; var strategiesByGeometry = {}; strategiesByGeometry[TYPE_AREA] = function(sample) { var coordinates = sample.coordinates; return { project: coordinates[0] && coordinates[0][0] && coordinates[0][0][0] && "number" === typeof coordinates[0][0][0][0] ? projectMultiPolygon : projectPolygon } }; strategiesByGeometry[TYPE_LINE] = function(sample) { var coordinates = sample.coordinates; return { project: coordinates[0] && coordinates[0][0] && "number" === typeof coordinates[0][0][0] ? projectPolygon : projectLineString } }; var strategiesByElementType = {}; strategiesByElementType[TYPE_MARKER] = { _default: "dot", dot: { setup: function(context) { context.filter = context.renderer.shadowFilter("-40%", "-40%", "180%", "200%", 0, 1, 1, "#000000", .2) }, reset: function(context) { context.filter.dispose(); context.filter = null }, _draw: function(ctx, figure, data) { figure.back = ctx.renderer.circle().sharp().data(ctx.dataKey, data).append(figure.root); figure.dot = ctx.renderer.circle().sharp().data(ctx.dataKey, data).append(figure.root) }, refresh: function(ctx, figure, data, proxy, settings) { figure.dot.attr({ filter: settings.shadow ? ctx.filter.id : null }) }, _getStyles: function(styles, style) { var size = style.size > 0 ? _Number(style.size) : 0, hoveredSize = size, selectedSize = size + (style.selectedStep > 0 ? _Number(style.selectedStep) : 0), hoveredBackSize = hoveredSize + (style.backStep > 0 ? _Number(style.backStep) : 0), selectedBackSize = selectedSize + (style.backStep > 0 ? _Number(style.backStep) : 0), color = style.color || null, borderColor = style.borderColor || null, borderWidth = pick(style.borderWidth, null), opacity = pick(style.opacity, null), backColor = style.backColor || null, backOpacity = pick(style.backOpacity, null); styles.dot = [{ r: size / 2, stroke: borderColor, "stroke-width": borderWidth, fill: color, opacity: opacity }, { r: hoveredSize / 2, stroke: style.hoveredBorderColor || borderColor, "stroke-width": pick(style.hoveredBorderWidth, borderWidth), fill: style.hoveredColor || color, opacity: pick(style.hoveredOpacity, opacity) }, { r: selectedSize / 2, stroke: style.selectedBorderColor || borderColor, "stroke-width": pick(style.selectedBorderWidth, borderWidth), fill: style.selectedColor || color, opacity: pick(style.selectedOpacity, opacity) }]; styles.back = [{ r: size / 2, stroke: "none", "stroke-width": 0, fill: backColor, opacity: backOpacity }, { r: hoveredBackSize / 2, stroke: "none", "stroke-width": 0, fill: backColor, opacity: backOpacity }, { r: selectedBackSize / 2, stroke: "none", "stroke-width": 0, fill: backColor, opacity: backOpacity }] }, _setState: function(figure, styles, state) { applyElementState(figure, styles, state, "dot"); applyElementState(figure, styles, state, "back") } }, bubble: { _draw: function(ctx, figure, data) { figure.bubble = ctx.renderer.circle().sharp().data(ctx.dataKey, data).append(figure.root) }, refresh: function(ctx, figure, data, proxy, settings) { figure.bubble.attr({ r: settings.size / 2 }) }, _getStyles: function(styles, style) { var color = style.color || null, borderColor = style.borderColor || null, borderWidth = pick(style.borderWidth, null), opacity = pick(style.opacity, null); styles.bubble = [{ stroke: borderColor, "stroke-width": borderWidth, fill: color, opacity: opacity }, { stroke: style.hoveredBorderColor || borderColor, "stroke-width": pick(style.hoveredBorderWidth, borderWidth), fill: style.hoveredColor || style.color, opacity: pick(style.hoveredOpacity, opacity) }, { stroke: style.selectedBorderColor || borderColor, "stroke-width": pick(style.selectedBorderWidth, borderWidth), fill: style.selectedColor || style.color, opacity: pick(style.selectedOpacity, opacity) }] }, _setState: function(figure, styles, state) { applyElementState(figure, styles, state, "bubble") }, arrange: function(context, handles) { var i, minValue, maxValue, deltaValue, deltaSize, values = [], ii = values.length = handles.length, settings = context.settings, dataField = settings.dataField, minSize = settings.minSize > 0 ? _Number(settings.minSize) : 0, maxSize = settings.maxSize > minSize ? _Number(settings.maxSize) : minSize; if (settings.sizeGroups) { return } for (i = 0; i < ii; ++i) { values[i] = _max(getDataValue(handles[i].proxy, dataField, "value") || 0, 0) } minValue = _min.apply(null, values); maxValue = _max.apply(null, values); deltaValue = maxValue - minValue || 1; deltaSize = maxSize - minSize; for (i = 0; i < ii; ++i) { handles[i]._settings.size = minSize + deltaSize * (values[i] - minValue) / deltaValue } }, updateGrouping: function(context) { var dataField = context.settings.dataField; strategiesByType[TYPE_MARKER].updateGrouping(context); groupBySize(context, function(proxy) { return getDataValue(proxy, dataField, "value") }) } }, pie: { _draw: function(ctx, figure, data) { figure.pie = ctx.renderer.g().append(figure.root); figure.border = ctx.renderer.circle().sharp().data(ctx.dataKey, data).append(figure.root) }, refresh: function(ctx, figure, data, proxy, settings) { var i, values = getDataValue(proxy, ctx.settings.dataField, "values") || [], ii = values.length || 0, colors = settings._colors, sum = 0, pie = figure.pie, renderer = ctx.renderer, dataKey = ctx.dataKey, r = (settings.size > 0 ? _Number(settings.size) : 0) / 2, start = 90, end = start; for (i = 0; i < ii; ++i) { sum += values[i] || 0 } for (i = 0; i < ii; ++i) { start = end; end += (values[i] || 0) / sum * 360; renderer.arc(0, 0, 0, r, start, end).attr({ "stroke-linejoin": "round", fill: colors[i] }).data(dataKey, data).append(pie) } figure.border.attr({ r: r }) }, _getStyles: function(styles, style) { var opacity = pick(style.opacity, null), borderColor = style.borderColor || null, borderWidth = pick(style.borderWidth, null); styles.pie = [{ opacity: opacity }, { opacity: pick(style.hoveredOpacity, opacity) }, { opacity: pick(style.selectedOpacity, opacity) }]; styles.border = [{ stroke: borderColor, "stroke-width": borderWidth }, { stroke: style.hoveredBorderColor || borderColor, "stroke-width": pick(style.hoveredBorderWidth, borderWidth) }, { stroke: style.selectedBorderColor || borderColor, "stroke-width": pick(style.selectedBorderWidth, borderWidth) }] }, _setState: function(figure, styles, state) { applyElementState(figure, styles, state, "pie"); applyElementState(figure, styles, state, "border") }, arrange: function(context, handles) { var i, values, palette, ii = handles.length, dataField = context.settings.dataField, count = 0; for (i = 0; i < ii; ++i) { values = getDataValue(handles[i].proxy, dataField, "values"); if (values && values.length > count) { count = values.length } } if (count > 0) { values = []; palette = context.params.themeManager.createPalette(context.settings.palette, { useHighlight: true }); for (i = 0; i < count; ++i) { values.push(palette.getNextColor()) } context.settings._colors = values; context.grouping.color = { callback: _noop, field: "", partition: [], values: [] }; context.params.dataExchanger.set(context.name, "color", { partition: [], values: values }) } } }, image: { _draw: function(ctx, figure, data) { figure.image = ctx.renderer.image().attr({ location: "center" }).data(ctx.dataKey, data).append(figure.root) }, refresh: function(ctx, figure, data, proxy) { figure.image.attr({ href: getDataValue(proxy, ctx.settings.dataField, "url") }) }, _getStyles: function(styles, style) { var size = style.size > 0 ? _Number(style.size) : 0, hoveredSize = size + (style.hoveredStep > 0 ? _Number(style.hoveredStep) : 0), selectedSize = size + (style.selectedStep > 0 ? _Number(style.selectedStep) : 0), opacity = pick(style.opacity, null); styles.image = [{ x: -size / 2, y: -size / 2, width: size, height: size, opacity: opacity }, { x: -hoveredSize / 2, y: -hoveredSize / 2, width: hoveredSize, height: hoveredSize, opacity: pick(style.hoveredOpacity, opacity) }, { x: -selectedSize / 2, y: -selectedSize / 2, width: selectedSize, height: selectedSize, opacity: pick(style.selectedOpacity, opacity) }] }, _setState: function(figure, styles, state) { applyElementState(figure, styles, state, "image") } } }; function projectPoint(projection, coordinates) { return projection.project(coordinates) } function projectPointList(projection, coordinates) { var i, output = [], ii = output.length = coordinates.length; for (i = 0; i < ii; ++i) { output[i] = projection.project(coordinates[i]) } return output } function projectLineString(projection, coordinates) { return [projectPointList(projection, coordinates)] } function projectPolygon(projection, coordinates) { var i, output = [], ii = output.length = coordinates.length; for (i = 0; i < ii; ++i) { output[i] = projectPointList(projection, coordinates[i]) } return output } function projectMultiPolygon(projection, coordinates) { var i, output = [], ii = output.length = coordinates.length; for (i = 0; i < ii; ++i) { output[i] = projectPolygon(projection, coordinates[i]) } return _concat.apply([], output) } function transformPoint(content, projection, coordinates) { var data = projection.transform(coordinates); content.root.attr({ translateX: data[0], translateY: data[1] }) } function transformList(projection, coordinates) { var i, item, output = [], ii = coordinates.length, k = 0; output.length = 2 * ii; for (i = 0; i < ii; ++i) { item = projection.transform(coordinates[i]); output[k++] = item[0]; output[k++] = item[1] } return output } function transformPointList(content, projection, coordinates) { var i, output = [], ii = output.length = coordinates.length; for (i = 0; i < ii; ++i) { output[i] = transformList(projection, coordinates[i]) } content.root.attr({ points: output }) } function transformAreaLabel(label, projection, coordinates) { var data = projection.transform(coordinates[0]); label.spaceSize = projection.getSquareSize(coordinates[1]); label.text.attr({ translateX: data[0], translateY: data[1] }); setAreaLabelVisibility(label) } function transformLineLabel(label, projection, coordinates) { var data = projection.transform(coordinates[0]); label.spaceSize = projection.getSquareSize(coordinates[1]); label.text.attr({ translateX: data[0], translateY: data[1] }); setLineLabelVisibility(label) } function getItemSettings(context, proxy, settings) { var result = combineSettings(context.settings, settings); proxy.text = proxy.text || settings.text; applyGrouping(context.grouping, proxy, result); if (void 0 === settings.color && settings.paletteIndex >= 0) { result.color = result._colors[settings.paletteIndex] } return result } function applyGrouping(grouping, proxy, settings) { _each(grouping, function(name, data) { var index = findGroupingIndex(data.callback(proxy, data.field), data.partition); if (index >= 0) { settings[name] = data.values[index] } }) } function findGroupingIndex(value, partition) { var middle, start = 0, end = partition.length - 1, index = -1; if (partition[start] <= value && value <= partition[end]) { if (value === partition[end]) { index = end - 1 } else { while (end - start > 1) { middle = start + end >> 1; if (value < partition[middle]) { end = middle } else { start = middle } } index = start } } return index } function raiseChanged(context, handle, state, name) { context.params.eventTrigger(name, { target: handle.proxy, state: state }) } function combineSettings(common, partial) { var obj = _extend({}, common, partial); obj.label = _extend({}, common.label, obj.label); obj.label.font = _extend({}, common.label.font, obj.label.font); return obj } function processCommonSettings(type, options, themeManager) { var colors, i, palette, settings = combineSettings(themeManager.theme("layer:" + type) || { label: {} }, options); if (settings.paletteSize > 0) { palette = themeManager.createDiscretePalette(settings.palette, settings.paletteSize); for (i = 0, colors = []; i < settings.paletteSize; ++i) { colors.push(palette.getColor(i)) } settings._colors = colors } return settings } function valueCallback(proxy, dataField) { return proxy.attribute(dataField) } var performGrouping = function(context, partition, settingField, dataField, valuesCallback) { var values; if (dataField && partition && partition.length > 1) { values = valuesCallback(partition.length - 1); context.grouping[settingField] = { callback: _isFunction(dataField) ? dataField : valueCallback, field: dataField, partition: partition, values: values }; context.params.dataExchanger.set(context.name, settingField, { partition: partition, values: values }) } }; function dropGrouping(context) { var name = context.name, dataExchanger = context.params.dataExchanger; _each(context.grouping, function(field) { dataExchanger.set(name, field, null) }); context.grouping = {} } var groupByColor = function(context) { performGrouping(context, context.settings.colorGroups, "color", context.settings.colorGroupingField, function(count) { var i, _palette = context.params.themeManager.createDiscretePalette(context.settings.palette, count), list = []; for (i = 0; i < count; ++i) { list.push(_palette.getColor(i)) } return list }) }; var groupBySize = function(context, valueCallback) { var settings = context.settings; performGrouping(context, settings.sizeGroups, "size", valueCallback || settings.sizeGroupingField, function(count) { var minSize = settings.minSize > 0 ? _Number(settings.minSize) : 0, maxSize = settings.maxSize >= minSize ? _Number(settings.maxSize) : 0, i = 0, sizes = []; if (count > 1) { for (i = 0; i < count; ++i) { sizes.push((minSize * (count - i - 1) + maxSize * i) / (count - 1)) } } else { if (1 === count) { sizes.push((minSize + maxSize) / 2) } } return sizes }) }; function setFlag(flags, flag, state) { if (state) { flags |= flag } else { flags &= ~flag } return flags } function hasFlag(flags, flag) { return !!(flags & flag) } function createLayerProxy(layer, name, index) { var proxy = { index: index, name: name, getElements: function() { return layer.getProxies() }, clearSelection: function(_noEvent) { layer.clearSelection(_noEvent); return proxy }, getDataSource: function() { return layer.getDataSource() } }; return proxy } var MapLayer = function(params, container, name, index) { var that = this; that._params = params; that._onProjection(); that.proxy = createLayerProxy(that, name, index); that._context = { name: name, layer: that.proxy, renderer: params.renderer, projection: params.projection, params: params, dataKey: params.dataKey, str: emptyStrategy, hover: false, selection: null, grouping: {}, root: params.renderer.g().attr({ "class": "dxm-layer" }).linkOn(container, name).linkAppend() }; that._container = container; that._options = {}; that._handles = []; that._data = new EmptySource }; MapLayer.prototype = _extend({ constructor: MapLayer, _onProjection: function() { var that = this; that._removeHandlers = that._params.projection.on({ engine: function() { that._project() }, screen: function() { that._transform() }, center: function() { that._transformCore() }, zoom: function() { that._transform() } }) }, _dataSourceLoadErrorHandler: function() { this._dataSourceChangedHandler() }, _dataSourceChangedHandler: function() { var that = this; that._data = unwrapFromDataSource(that._dataSource && that._dataSource.items()); that._update(true) }, _dataSourceOptions: function() { return { paginate: false } }, _getSpecificDataSourceOption: function() { return this._specificDataSourceOption }, _offProjection: function() { this._removeHandlers(); this._removeHandlers = null }, dispose: function() { var that = this; that._disposeDataSource(); that._destroyHandles(); dropGrouping(that._context); that._context.root.linkRemove().linkOff(); that._context.labelRoot && that._context.labelRoot.linkRemove().linkOff(); that._context.str.reset(that._context); that._offProjection(); that._params = that._container = that._context = that.proxy = null; return that }, TESTS_getContext: function() { return this._context }, setOptions: function(options) { var name, that = this; options = that._options = options || {}; name = !("dataSource" in options) && "data" in options ? "data" : "dataSource"; if (name in options && options[name] !== that._options_dataSource) { that._options_dataSource = options[name]; that._params.notifyDirty(); that._specificDataSourceOption = wrapToDataSource(options[name]); that._refreshDataSource() } else { if (that._data.count() > 0) { that._params.notifyDirty(); that._update(void 0 !== options.type && options.type !== that._context.str.type || void 0 !== options.elementType && options.elementType !== that._context.str.elementType) } } }, _update: function(isContextChanged) { var that = this, context = that._context; if (isContextChanged) { context.str.reset(context); context.root.clear(); context.labelRoot && context.labelRoot.clear(); that._params.tracker.reset(); that._destroyHandles(); context.str = selectStrategy(that._options, that._data); context.str.setup(context); that.proxy.type = context.str.type; that.proxy.elementType = context.str.elementType } context.settings = processCommonSettings(context.str.fullType, that._options, that._params.themeManager); context.hasSeparateLabel = !!(context.settings.label.enabled && context.str.hasLabelsGroup); context.hover = !!_parseScalar(context.settings.hoverEnabled, true); if (context.selection) { _each(context.selection.state, function(_, handle) { handle && handle.resetSelected() }) } context.selection = getSelection(context.settings.selectionMode); if (context.hasSeparateLabel) { if (!context.labelRoot) { context.labelRoot = context.renderer.g().attr({ "class": "dxm-layer-labels" }).linkOn(that._container, { name: context.name + "-labels", after: context.name }).linkAppend(); that._transformCore() } } else { if (context.labelRoot) { context.labelRoot.linkRemove().linkOff(); context.labelRoot = null } } if (isContextChanged) { that._createHandles() } dropGrouping(context); context.str.arrange(context, that._handles); context.str.updateGrouping(context); that._updateHandles(); that._params.notifyReady() }, _destroyHandles: function() { var i, handles = this._handles, ii = handles.length; for (i = 0; i < ii; ++i) { handles[i].dispose() } if (this._context.selection) { this._context.selection.state = {} } this._handles = [] }, _createHandles: function() { var i, handle, dataItem, that = this, handles = that._handles = [], data = that._data, ii = handles.length = data.count(), context = that._context, geometry = data.geometry, attributes = data.attributes; for (i = 0; i < ii; ++i) { dataItem = data.item(i); handles[i] = new MapLayerElement(context, i, geometry(dataItem), attributes(dataItem)) } if (_isFunction(that._options.customize)) { (that._options._deprecated ? customizeHandles_deprecated : customizeHandles)(that.getProxies(), that._options.customize, that._params.widget) } if (that._options._deprecated) { patchProxies(handles, context.name, data) } for (i = 0; i < ii; ++i) { handle = handles[i]; handle.project(); handle.draw(); handle.transform() } if (context.selection) { _each(context.selection.state, function(_, handle) { handle && handle.restoreSelected() }) } }, _updateHandles: function() { var i, handles = this._handles, ii = handles.length; for (i = 0; i < ii; ++i) { handles[i].refresh() } if (this._context.settings.label.enabled) { for (i = 0; i < ii; ++i) { handles[i].measureLabel() } for (i = 0; i < ii; ++i) { handles[i].adjustLabel() } } }, _transformCore: function() { var transform = this._params.projection.getTransform(); this._context.root.attr(transform); this._context.labelRoot && this._context.labelRoot.attr(transform) }, _project: function() { var i, handles = this._handles, ii = handles.length; for (i = 0; i < ii; ++i) { handles[i].project() } }, _transform: function() { var i, handles = this._handles, ii = handles.length; this._transformCore(); for (i = 0; i < ii; ++i) { handles[i].transform() } }, getProxies: function() { var i, handles = this._handles, proxies = [], ii = proxies.length = handles.length; for (i = 0; i < ii; ++i) { proxies[i] = handles[i].proxy } return proxies }, getProxy: function(index) { return this._handles[index].proxy }, raiseClick: function(i, jQueryEvent) { this._params.eventTrigger("click", { target: this._handles[i].proxy, jQueryEvent: jQueryEvent }) }, hoverItem: function(i, state) { this._handles[i].setHovered(state) }, selectItem: function(i, state, _noEvent) { this._handles[i].setSelected(state, _noEvent) }, clearSelection: function() { var selection = this._context.selection; if (selection) { _each(selection.state, function(_, handle) { handle && handle.setSelected(false) }); selection.state = {} } } }, DataHelperMixin); function createProxy(handle, coords, attrs) { var proxy = { coordinates: function() { return coords }, attribute: function(name, value) { if (arguments.length > 1) { attrs[name] = value; return proxy } else { return arguments.length > 0 ? attrs[name] : attrs } }, selected: function(state, _noEvent) { if (arguments.length > 0) { handle.setSelected(state, _noEvent); return proxy } else { return handle.isSelected() } }, applySettings: function(settings) { handle.update(settings); return proxy } }; return proxy } var MapLayerElement = function(context, index, geometry, attributes) { var that = this, proxy = that.proxy = createProxy(that, geometry.coordinates, _extend({}, attributes)); that._ctx = context; that._index = index; that._fig = that._label = null; that._state = STATE_DEFAULT; that._coordinates = geometry.coordinates; that._settings = { label: {} }; proxy.index = index; proxy.layer = context.layer; that._data = { name: context.name, index: index } }; MapLayerElement.prototype = { constructor: MapLayerElement, dispose: function() { var that = this; that._ctx = that.proxy = that._settings = that._fig = that._label = that.data = null; return that }, project: function() { var context = this._ctx; this._projection = context.str.project(context.projection, this._coordinates); if (context.hasSeparateLabel && this._label) { this._projectLabel() } }, _projectLabel: function() { this._labelProjection = this._ctx.str.projectLabel(this._projection) }, draw: function() { var that = this, context = this._ctx; context.str.draw(context, that._fig = {}, that._data); that._fig.root.append(context.root) }, transform: function() { var that = this, context = that._ctx; context.str.transform(that._fig, context.projection, that._projection); if (context.hasSeparateLabel && that._label) { that._transformLabel() } }, _transformLabel: function() { this._ctx.str.transformLabel(this._label, this._ctx.projection, this._labelProjection) }, refresh: function() { var that = this, strategy = that._ctx.str, settings = getItemSettings(that._ctx, that.proxy, that._settings); that._styles = strategy.getStyles(settings); strategy.refresh(that._ctx, that._fig, that._data, that.proxy, settings); that._refreshLabel(settings); that._setState() }, _refreshLabel: function(settings) { var that = this, context = that._ctx, labelSettings = settings.label, label = that._label; if (context.settings.label.enabled) { if (!label) { label = that._label = { root: context.labelRoot || that._fig.root, text: context.renderer.text().attr({ "class": "dxm-label" }), size: [0, 0] }; if (context.hasSeparateLabel) { that._projectLabel(); that._transformLabel() } } label.value = _String(that.proxy.text || that.proxy.attribute(labelSettings.dataField) || ""); if (label.value) { label.text.attr({ text: label.value, x: 0, y: 0 }).css(_patchFontOptions(labelSettings.font)).attr({ align: "center", stroke: labelSettings.stroke, "stroke-width": labelSettings["stroke-width"], "stroke-opacity": labelSettings["stroke-opacity"] }).data(context.dataKey, that._data).append(label.root); label.settings = settings } } else { if (label) { label.text.remove(); that._label = null } } }, measureLabel: function() { var bBox, label = this._label; if (label.value) { bBox = label.text.getBBox(); label.size = [bBox.width, bBox.height, -bBox.y - bBox.height / 2] } }, adjustLabel: function() { var offset, label = this._label; if (label.value) { offset = this._ctx.str.getLabelOffset(label, label.settings); label.settings = null; label.text.attr({ x: offset[0], y: offset[1] + label.size[2] }) } }, update: function(settings) { var that = this; that._settings = combineSettings(that._settings, settings); if (that._fig) { that.refresh(); if (that._label && that._label.value) { that.measureLabel(); that.adjustLabel() } } }, _setState: function() { this._ctx.str.setState(this._fig, this._styles, STATE_TO_INDEX[this._state]) }, _setForeground: function() { var root = this._fig.root; this._state ? root.toForeground() : root.toBackground() }, setHovered: function(state) { var that = this, currentState = hasFlag(that._state, STATE_HOVERED), newState = !!state; if (that._ctx.hover && currentState !== newState) { that._state = setFlag(that._state, STATE_HOVERED, newState); that._setState(); that._setForeground(); raiseChanged(that._ctx, that, newState, "hoverChanged") } return that }, setSelected: function(state, _noEvent) { var tmp, that = this, currentState = hasFlag(that._state, STATE_SELECTED), newState = !!state, selection = that._ctx.selection; if (selection && currentState !== newState) { that._state = setFlag(that._state, STATE_SELECTED, newState); tmp = selection.state[selection.single]; selection.state[selection.single] = null; if (tmp) { tmp.setSelected(false) } selection.state[selection.single || that._index] = state ? that : null; if (that._fig) { that._setState(); that._setForeground(); if (!_noEvent) { raiseChanged(that._ctx, that, newState, "selectionChanged") } } } }, isSelected: function() { return hasFlag(this._state, STATE_SELECTED) }, resetSelected: function() { this._state = setFlag(this._state, STATE_SELECTED, false) }, restoreSelected: function() { this._fig.root.toForeground() } }; function calculatePolygonCentroid(coordinates) { var i, v1, cross, length = coordinates.length, v2 = coordinates[length - 1], cx = 0, cy = 0, area = 0, minX = 1 / 0, maxX = -(1 / 0), minY = 1 / 0, maxY = -(1 / 0); for (i = 0; i < length; ++i) { v1 = v2; v2 = coordinates[i]; cross = v1[0] * v2[1] - v2[0] * v1[1]; area += cross; cx += (v1[0] + v2[0]) * cross; cy += (v1[1] + v2[1]) * cross; minX = _min(minX, v2[0]); maxX = _max(maxX, v2[0]); minY = _min(minY, v2[1]); maxY = _max(maxY, v2[1]) } return { area: _abs(area) / 2, center: [2 * cx / 3 / area - (minX + maxX) / 2, 2 * cy / 3 / area - (minY + maxY) / 2] } } function calculateLineStringData(coordinates) { var i, v1, t, ii = coordinates.length, v2 = coordinates[0] || [], totalLength = 0, items = [0], min0 = v2[0], max0 = v2[0], min1 = v2[1], max1 = v2[1]; for (i = 1; i < ii; ++i) { v1 = v2; v2 = coordinates[i]; totalLength += _sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1])); items[i] = totalLength; min0 = _min(min0, v2[0]); max0 = _max(max0, v2[0]); min1 = _min(min1, v2[1]); max1 = _max(max1, v2[1]) } i = findGroupingIndex(totalLength / 2, items); v1 = coordinates[i]; v2 = coordinates[i + 1]; t = (totalLength / 2 - items[i]) / (items[i + 1] - items[i]); return ii ? [ [v1[0] * (1 - t) + v2[0] * t, v1[1] * (1 - t) + v2[1] * t], [max0 - min0, max1 - min1], totalLength ] : [] } function projectAreaLabel(coordinates) { var i, centroid, resultCentroid, ii = coordinates.length, maxArea = 0; for (i = 0; i < ii; ++i) { centroid = calculatePolygonCentroid(coordinates[i]); if (centroid.area > maxArea) { maxArea = centroid.area; resultCentroid = centroid } } return resultCentroid ? [resultCentroid.center, [_sqrt(resultCentroid.area), _sqrt(resultCentroid.area)]] : [ [], [] ] } function projectLineLabel(coordinates) { var i, data, resultData, ii = coordinates.length, maxLength = 0; for (i = 0; i < ii; ++i) { data = calculateLineStringData(coordinates[i]); if (data[2] > maxLength) { maxLength = data[2]; resultData = data } } return resultData || [ [], [] ] } function MapLayerCollection(params) { var that = this, renderer = params.renderer; that._params = params; that._layers = []; that._layerByName = {}; that._rect = [0, 0, 0, 0]; that._clip = renderer.clipRect(); that._background = renderer.rect().attr({ "class": "dxm-background" }).data(params.dataKey, { name: "background" }).append(renderer.root); that._container = renderer.g().attr({ "class": "dxm-layers", "clip-path": that._clip.id }).append(renderer.root).enableLinks(); that._subscribeToTracker(params.tracker, renderer, params.eventTrigger) } MapLayerCollection.prototype = { constructor: MapLayerCollection, dispose: function() { var that = this; that._clip.dispose(); that._offTracker(); that._params = that._offTracker = that._layers = that._layerByName = that._clip = that._background = that._container = null }, _subscribeToTracker: function(tracker, renderer, eventTrigger) { var that = this; that._offTracker = tracker.on({ click: function(arg) { var offset = renderer.getRootOffset(), layer = that.byName(arg.data.name); arg.$event.x = arg.x - offset.left; arg.$event.y = arg.y - offset.top; if (layer) { layer.raiseClick(arg.data.index, arg.$event) } else { if ("background" === arg.data.name) { eventTrigger("click", { jQueryEvent: arg.$event }) } } }, "hover-on": function(arg) { var layer = that.byName(arg.data.name); if (layer) { layer.hoverItem(arg.data.index, true) } }, "hover-off": function(arg) { var layer = that.byName(arg.data.name); if (layer) { layer.hoverItem(arg.data.index, false) } } }) }, setOptions: function(options) { var name, layer, i, ii, optionList = options ? options.length ? options : [options] : [], layers = this._layers, layerByName = this._layerByName, params = this._params, container = this._container; for (i = optionList.length, ii = layers.length; i < ii; ++i) { layer = layers[i]; delete layerByName[layer.proxy.name]; layer.dispose() } layers.splice(optionList.length, layers.length - optionList.length); for (i = layers.length, ii = optionList.length; i < ii; ++i) { name = (optionList[i] || {}).name || "map-layer-" + i; layer = layers[i] = new MapLayer(params, container, name, i); layerByName[name] = layer } for (i = 0, ii = optionList.length; i < ii; ++i) { name = optionList[i] && optionList[i].name; layer = layers[i]; if (name && name !== layer.proxy.name) { delete layerByName[layer.proxy.name]; layer.dispose(); layer = layers[i] = new MapLayer(params, container, name, i); layerByName[name] = layer } layer.setOptions(optionList[i]) } }, _updateClip: function() { var rect = this._rect, bw = this._borderWidth; this._clip.attr({ x: rect[0] + bw, y: rect[1] + bw, width: _max(rect[2] - 2 * bw, 0), height: _max(rect[3] - 2 * bw, 0) }) }, setBackgroundOptions: function(options) { this._background.attr({ stroke: options.borderColor, "stroke-width": options.borderWidth, fill: options.color }); this._borderWidth = _max(options.borderWidth, 0); this._updateClip() }, setRect: function(rect) { this._rect = rect; this._background.attr({ x: rect[0], y: rect[1], width: rect[2], height: rect[3] }); this._updateClip() }, byIndex: function(index) { return this._layers[index] }, byName: function(name) { return this._layerByName[name] }, items: function() { return this._layers } }; exports.MapLayerCollection = MapLayerCollection; exports._TESTS_MapLayer = MapLayer; exports._TESTS_stub_MapLayer = function(stub) { MapLayer = stub }; exports._TESTS_selectStrategy = selectStrategy; exports._TESTS_stub_selectStrategy = function(stub) { selectStrategy = stub }; exports._TESTS_MapLayerElement = MapLayerElement; exports._TESTS_stub_MapLayerElement = function(stub) { MapLayerElement = stub }; exports._TESTS_createProxy = createProxy; exports._TESTS_stub_performGrouping = function(stub) { performGrouping = stub }; exports._TESTS_performGrouping = performGrouping; exports._TESTS_stub_groupByColor = function(stub) { groupByColor = stub }; exports._TESTS_groupByColor = groupByColor; exports._TESTS_stub_groupBySize = function(stub) { groupBySize = stub }; exports._TESTS_groupBySize = groupBySize; exports._TESTS_findGroupingIndex = findGroupingIndex }, /*!*********************************************!*\ !*** ./js/viz/vector_map/tooltip_viewer.js ***! \*********************************************/ function(module, exports) { var TOOLTIP_OFFSET = 12; function TooltipViewer(params) { this._subscribeToTracker(params.tracker, params.tooltip, params.layerCollection) } TooltipViewer.prototype = { constructor: TooltipViewer, dispose: function() { this._offTracker(); this._offTracker = null }, _subscribeToTracker: function(tracker, tooltip, layerCollection) { this._offTracker = tracker.on({ "focus-on": function(arg) { var layer, proxy, result = false; if (tooltip.isEnabled()) { layer = layerCollection.byName(arg.data.name); proxy = layer && layer.getProxy(arg.data.index); if (proxy && tooltip.show(proxy, { x: 0, y: 0, offset: 0 }, { target: proxy })) { tooltip.move(arg.x, arg.y, TOOLTIP_OFFSET); result = true } } arg.done(result) }, "focus-move": function(arg) { tooltip.move(arg.x, arg.y, TOOLTIP_OFFSET) }, "focus-off": function() { tooltip.hide() } }) } }; exports.TooltipViewer = TooltipViewer }, /*!*****************************************!*\ !*** ./js/viz/vector_map/projection.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var projectionModule = __webpack_require__( /*! ./projection.main */ 615), projection = projectionModule.projection, _min = Math.min, _max = Math.max, _sin = Math.sin, _asin = Math.asin, _tan = Math.tan, _atan = Math.atan, _exp = Math.exp, _log = Math.log, PI = Math.PI, PI_DIV_4 = PI / 4, GEO_LON_BOUND = 180, GEO_LAT_BOUND = 90, RADIANS = PI / 180, MERCATOR_LAT_BOUND = (2 * _atan(_exp(PI)) - PI / 2) / RADIANS, MILLER_LAT_BOUND = (2.5 * _atan(_exp(.8 * PI)) - .625 * PI) / RADIANS; function clamp(value, threshold) { return _max(_min(value, +threshold), -threshold) } projection.add("mercator", projection({ aspectRatio: 1, to: function(coordinates) { return [coordinates[0] / GEO_LON_BOUND, _log(_tan(PI_DIV_4 + clamp(coordinates[1], MERCATOR_LAT_BOUND) * RADIANS / 2)) / PI] }, from: function(coordinates) { return [coordinates[0] * GEO_LON_BOUND, (2 * _atan(_exp(coordinates[1] * PI)) - PI / 2) / RADIANS] } })); projection.add("equirectangular", projection({ aspectRatio: 2, to: function(coordinates) { return [coordinates[0] / GEO_LON_BOUND, coordinates[1] / GEO_LAT_BOUND] }, from: function(coordinates) { return [coordinates[0] * GEO_LON_BOUND, coordinates[1] * GEO_LAT_BOUND] } })); projection.add("lambert", projection({ aspectRatio: 2, to: function(coordinates) { return [coordinates[0] / GEO_LON_BOUND, _sin(clamp(coordinates[1], GEO_LAT_BOUND) * RADIANS)] }, from: function(coordinates) { return [coordinates[0] * GEO_LON_BOUND, _asin(clamp(coordinates[1], 1)) / RADIANS] } })); projection.add("miller", projection({ aspectRatio: 1, to: function(coordinates) { return [coordinates[0] / GEO_LON_BOUND, 1.25 * _log(_tan(PI_DIV_4 + clamp(coordinates[1], MILLER_LAT_BOUND) * RADIANS * .4)) / PI] }, from: function(coordinates) { return [coordinates[0] * GEO_LON_BOUND, (2.5 * _atan(_exp(.8 * coordinates[1] * PI)) - .625 * PI) / RADIANS] } })); exports.projection = projection }, /*!*****************************!*\ !*** ./js/viz/sparkline.js ***! \*****************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./sparklines/sparkline */ 628) }, /*!****************************************!*\ !*** ./js/viz/sparklines/sparkline.js ***! \****************************************/ function(module, exports, __webpack_require__) { var BaseSparkline = __webpack_require__( /*! ./base_sparkline */ 629), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), dataValidatorModule = __webpack_require__( /*! ../components/data_validator */ 523), seriesModule = __webpack_require__( /*! ../series/base_series */ 525), MIN_BAR_WIDTH = 1, MAX_BAR_WIDTH = 50, DEFAULT_BAR_INTERVAL = 4, DEFAULT_CANVAS_WIDTH = 250, DEFAULT_CANVAS_HEIGHT = 30, DEFAULT_HORIZONTAL_MARGIN = 5, DEFAULT_VERTICAL_MARGIN = 3, ALLOWED_TYPES = { line: true, spline: true, stepline: true, area: true, steparea: true, splinearea: true, bar: true, winloss: true }, _math = Math, _abs = _math.abs, _round = _math.round, _max = _math.max, _min = _math.min, _isFinite = isFinite, vizUtils = __webpack_require__( /*! ../core/utils */ 509), _map = vizUtils.map, _normalizeEnum = vizUtils.normalizeEnum, _isDefined = commonUtils.isDefined, _Number = Number, _String = String; var dxSparkline = BaseSparkline.inherit({ _rootClassPrefix: "dxsl", _rootClass: "dxsl-sparkline", _widgetType: "sparkline", _defaultSize: { width: DEFAULT_CANVAS_WIDTH, height: DEFAULT_CANVAS_HEIGHT, left: DEFAULT_HORIZONTAL_MARGIN, right: DEFAULT_HORIZONTAL_MARGIN, top: DEFAULT_VERTICAL_MARGIN, bottom: DEFAULT_VERTICAL_MARGIN }, _initCore: function() { this.callBase(); this._createSeries() }, _initialChanges: ["DATA_SOURCE"], _dataSourceChangedHandler: function() { this._requestChange(["UPDATE"]) }, _updateWidgetElements: function() { this._updateSeries(); this.callBase() }, _disposeWidgetElements: function() { var that = this; that._series && that._series.dispose(); that._series = that._seriesGroup = that._seriesLabelGroup = null }, _cleanWidgetElements: function() { this._seriesGroup.remove(); this._seriesLabelGroup.remove(); this._seriesGroup.clear(); this._seriesLabelGroup.clear() }, _drawWidgetElements: function() { if (this._dataIsLoaded()) { this._drawSeries(); this._drawn() } }, _prepareOptions: function() { var that = this; that._allOptions = that.callBase(); that._allOptions.type = _normalizeEnum(that._allOptions.type); if (!ALLOWED_TYPES[that._allOptions.type]) { that._allOptions.type = "line" } }, _createHtmlElements: function() { this._seriesGroup = this._renderer.g().attr({ "class": "dxsl-series" }); this._seriesLabelGroup = this._renderer.g().attr({ "class": "dxsl-series-labels" }) }, _createSeries: function() { this._series = new seriesModule.Series({ renderer: this._renderer, seriesGroup: this._seriesGroup, labelsGroup: this._seriesLabelGroup, argumentAxis: this._argumentAxis, valueAxis: this._valueAxis }, { widgetType: "chart", type: "line" }) }, getSeriesOptions: function() { return this._series.getOptions() }, _updateSeries: function() { var groupsData, seriesOptions, that = this, singleSeries = that._series; that._prepareDataSource(); seriesOptions = that._prepareSeriesOptions(); singleSeries.updateOptions(seriesOptions); groupsData = { groups: [{ series: [singleSeries] }] }; groupsData.argumentOptions = { type: "bar" === seriesOptions.type ? "discrete" : void 0 }; that._simpleDataSource = dataValidatorModule.validateData(that._simpleDataSource, groupsData, that._incidentOccurred, { checkTypeForAllData: false, convertToAxisDataType: true, sortingMethod: true })[singleSeries.getArgumentField()]; singleSeries.updateData(that._simpleDataSource); that._groupsDataCategories = groupsData.categories }, _optionChangesMap: { dataSource: "DATA_SOURCE" }, _optionChangesOrder: ["DATA_SOURCE"], _change_DATA_SOURCE: function() { this._updateDataSource() }, _parseNumericDataSource: function(data, argField, valField) { var ignoreEmptyPoints = this.option("ignoreEmptyPoints"); return _map(data, function(dataItem, index) { var isDataNumber, value, item = null; if (void 0 !== dataItem) { item = {}; isDataNumber = _isFinite(dataItem); item[argField] = isDataNumber ? _String(index) : dataItem[argField]; value = isDataNumber ? dataItem : dataItem[valField]; item[valField] = null === value ? ignoreEmptyPoints ? void 0 : value : _Number(value); item = void 0 !== item[argField] && void 0 !== item[valField] ? item : null } return item }) }, _parseWinlossDataSource: function(data, argField, valField) { var lowBarValue = -1, zeroBarValue = 0, highBarValue = 1, delta = 1e-4, target = this._allOptions.winlossThreshold; return _map(data, function(dataItem) { var item = {}; item[argField] = dataItem[argField]; if (_abs(dataItem[valField] - target) < delta) { item[valField] = zeroBarValue } else { if (dataItem[valField] > target) { item[valField] = highBarValue } else { item[valField] = lowBarValue } } return item }) }, _prepareDataSource: function() { var that = this, options = that._allOptions, argField = options.argumentField, valField = options.valueField, dataSource = that._dataSourceItems() || [], data = that._parseNumericDataSource(dataSource, argField, valField); if ("winloss" === options.type) { that._winlossDataSource = data; that._simpleDataSource = that._parseWinlossDataSource(data, argField, valField) } else { that._simpleDataSource = data } }, _prepareSeriesOptions: function() { var that = this, options = that._allOptions, type = "winloss" === options.type ? "bar" : options.type; return { visible: true, argumentField: options.argumentField, valueField: options.valueField, color: options.lineColor, width: options.lineWidth, widgetType: "chart", type: type, opacity: type.indexOf("area") !== -1 ? that._allOptions.areaOpacity : void 0, customizePoint: that._getCustomizeFunction(), point: { size: options.pointSize, symbol: options.pointSymbol, border: { visible: true, width: 2 }, color: options.pointColor, visible: false, hoverStyle: { border: {} }, selectionStyle: { border: {} } }, border: { color: options.lineColor, width: options.lineWidth, visible: "bar" !== type } } }, _createBarCustomizeFunction: function(pointIndexes) { var that = this, options = that._allOptions, winlossData = that._winlossDataSource; return function() { var color, index = this.index, isWinloss = "winloss" === options.type, target = isWinloss ? options.winlossThreshold : 0, value = isWinloss ? winlossData[index][options.valueField] : this.value, positiveColor = isWinloss ? options.winColor : options.barPositiveColor, negativeColor = isWinloss ? options.lossColor : options.barNegativeColor; if (value >= target) { color = positiveColor } else { color = negativeColor } if (index === pointIndexes.first || index === pointIndexes.last) { color = options.firstLastColor } if (index === pointIndexes.min) { color = options.minColor } if (index === pointIndexes.max) { color = options.maxColor } return { color: color } } }, _createLineCustomizeFunction: function(pointIndexes) { var that = this, options = that._allOptions; return function() { var color, index = this.index; if (index === pointIndexes.first || index === pointIndexes.last) { color = options.firstLastColor } if (index === pointIndexes.min) { color = options.minColor } if (index === pointIndexes.max) { color = options.maxColor } return color ? { visible: true, border: { color: color } } : {} } }, _getCustomizeFunction: function() { var customizeFunction, that = this, options = that._allOptions, dataSource = that._winlossDataSource || that._simpleDataSource, drawnPointIndexes = that._getExtremumPointsIndexes(dataSource); if ("winloss" === options.type || "bar" === options.type) { customizeFunction = that._createBarCustomizeFunction(drawnPointIndexes) } else { customizeFunction = that._createLineCustomizeFunction(drawnPointIndexes) } return customizeFunction }, _getExtremumPointsIndexes: function(data) { var that = this, options = that._allOptions, lastIndex = data.length - 1, indexes = {}; that._minMaxIndexes = that._findMinMax(data); if (options.showFirstLast) { indexes.first = 0; indexes.last = lastIndex } if (options.showMinMax) { indexes.min = that._minMaxIndexes.minIndex; indexes.max = that._minMaxIndexes.maxIndex } return indexes }, _findMinMax: function(data) { var value, i, that = this, valField = that._allOptions.valueField, firstItem = data[0] || {}, firstValue = firstItem[valField] || 0, min = firstValue, max = firstValue, minIndex = 0, maxIndex = 0, dataLength = data.length; for (i = 1; i < dataLength; i++) { value = data[i][valField]; if (value < min) { min = value; minIndex = i } if (value > max) { max = value; maxIndex = i } } return { minIndex: minIndex, maxIndex: maxIndex } }, _updateRange: function() { var valCoef, argCoef, that = this, series = that._series, type = series.type, isBarType = "bar" === type, isWinlossType = "winloss" === type, DEFAULT_VALUE_RANGE_MARGIN = .15, DEFAULT_ARGUMENT_RANGE_MARGIN = .1, WINLOSS_MAX_RANGE = 1, WINLOSS_MIN_RANGE = -1, rangeData = series.getRangeData(), minValue = that._allOptions.minValue, hasMinY = _isDefined(minValue) && _isFinite(minValue), maxValue = that._allOptions.maxValue, hasMaxY = _isDefined(maxValue) && _isFinite(maxValue); valCoef = (rangeData.val.max - rangeData.val.min) * DEFAULT_VALUE_RANGE_MARGIN; if (isBarType || isWinlossType || "area" === type) { if (0 !== rangeData.val.min) { rangeData.val.min -= valCoef } if (0 !== rangeData.val.max) { rangeData.val.max += valCoef } } else { rangeData.val.min -= valCoef; rangeData.val.max += valCoef } if (hasMinY || hasMaxY) { if (hasMinY && hasMaxY) { rangeData.val.minVisible = _min(minValue, maxValue); rangeData.val.maxVisible = _max(minValue, maxValue) } else { rangeData.val.minVisible = hasMinY ? _Number(minValue) : void 0; rangeData.val.maxVisible = hasMaxY ? _Number(maxValue) : void 0 } if (isWinlossType) { rangeData.val.minVisible = hasMinY ? _max(rangeData.val.minVisible, WINLOSS_MIN_RANGE) : void 0; rangeData.val.maxVisible = hasMaxY ? _min(rangeData.val.maxVisible, WINLOSS_MAX_RANGE) : void 0 } } if (series.getPoints().length > 1) { if (isBarType) { argCoef = (rangeData.arg.max - rangeData.arg.min) * DEFAULT_ARGUMENT_RANGE_MARGIN; rangeData.arg.min = rangeData.arg.min - argCoef; rangeData.arg.max = rangeData.arg.max + argCoef } else { rangeData.arg.stick = true } } rangeData.arg.categories = that._groupsDataCategories; that._ranges = rangeData }, _getBarWidth: function(pointsCount) { var that = this, canvas = that._canvas, intervalWidth = pointsCount * DEFAULT_BAR_INTERVAL, rangeWidth = canvas.width - canvas.left - canvas.right - intervalWidth, width = _round(rangeWidth / pointsCount); if (width < MIN_BAR_WIDTH) { width = MIN_BAR_WIDTH } if (width > MAX_BAR_WIDTH) { width = MAX_BAR_WIDTH } return width }, _correctPoints: function() { var barWidth, i, that = this, seriesType = that._allOptions.type, seriesPoints = that._series.getPoints(), pointsLength = seriesPoints.length; if ("bar" === seriesType || "winloss" === seriesType) { barWidth = that._getBarWidth(pointsLength); for (i = 0; i < pointsLength; i++) { seriesPoints[i].correctCoordinates({ width: barWidth, offset: 0 }) } } }, _drawSeries: function() { var that = this; if (that._simpleDataSource.length > 0) { that._correctPoints(); that._series.draw(); that._seriesGroup.append(that._renderer.root) } }, _isTooltipEnabled: function() { return !!this._simpleDataSource.length }, _getTooltipData: function() { var that = this, options = that._allOptions, dataSource = that._winlossDataSource || that._simpleDataSource, tooltip = that._tooltip; if (0 === dataSource.length) { return {} } var minMax = that._minMaxIndexes, valueField = options.valueField, first = dataSource[0][valueField], last = dataSource[dataSource.length - 1][valueField], min = dataSource[minMax.minIndex][valueField], max = dataSource[minMax.maxIndex][valueField], formattedFirst = tooltip.formatValue(first), formattedLast = tooltip.formatValue(last), formattedMin = tooltip.formatValue(min), formattedMax = tooltip.formatValue(max), customizeObject = { firstValue: formattedFirst, lastValue: formattedLast, minValue: formattedMin, maxValue: formattedMax, originalFirstValue: first, originalLastValue: last, originalMinValue: min, originalMaxValue: max, valueText: ["Start:", formattedFirst, "End:", formattedLast, "Min:", formattedMin, "Max:", formattedMax] }; if ("winloss" === options.type) { customizeObject.originalThresholdValue = options.winlossThreshold; customizeObject.thresholdValue = tooltip.formatValue(options.winlossThreshold) } return customizeObject } }); _map(["lineColor", "lineWidth", "areaOpacity", "minColor", "maxColor", "barPositiveColor", "barNegativeColor", "winColor", "lessColor", "firstLastColor", "pointSymbol", "pointColor", "pointSize", "type", "argumentField", "valueField", "winlossThreshold", "showFirstLast", "showMinMax", "ignoreEmptyPoints", "minValue", "maxValue"], function(name) { dxSparkline.prototype._optionChangesMap[name] = "OPTIONS" }); __webpack_require__( /*! ../../core/component_registrator */ 57)("dxSparkline", dxSparkline); module.exports = dxSparkline; dxSparkline.addPlugin(__webpack_require__( /*! ../core/data_source */ 561).plugin) }, /*!*********************************************!*\ !*** ./js/viz/sparklines/base_sparkline.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), commonUtils = __webpack_require__( /*! ../../core/utils/common */ 14), BaseWidget = __webpack_require__( /*! ../core/base_widget */ 515), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, DEFAULT_LINE_SPACING = 2, DEFAULT_EVENTS_DELAY = 200, TOUCH_EVENTS_DELAY = 1e3, eventUtils = __webpack_require__( /*! ../../events/utils */ 71), wheelEvent = __webpack_require__( /*! ../../events/core/wheel */ 85), baseThemeManagerModule = __webpack_require__( /*! ../core/base_theme_manager */ 550), translator2DModule = __webpack_require__( /*! ../translators/translator2d */ 571), _abs = Math.abs, _extend = extend, _noop = commonUtils.noop; function generateDefaultCustomizeTooltipCallback(fontOptions, rtlEnabled) { var lineSpacing = fontOptions.lineSpacing, lineHeight = (void 0 !== lineSpacing && null !== lineSpacing ? lineSpacing : DEFAULT_LINE_SPACING) + fontOptions.size; return function(customizeObject) { var html = "", vt = customizeObject.valueText; for (var i = 0; i < vt.length; i += 2) { html += "<tr><td>" + vt[i] + "</td><td style='width: 15px'></td><td style='text-align: " + (rtlEnabled ? "left" : "right") + "'>" + vt[i + 1] + "</td></tr>" } return { html: "<table style='border-spacing:0px; line-height: " + lineHeight + "px'>" + html + "</table>" } } } function generateCustomizeTooltipCallback(customizeTooltip, fontOptions, rtlEnabled) { var defaultCustomizeTooltip = generateDefaultCustomizeTooltipCallback(fontOptions, rtlEnabled); if (commonUtils.isFunction(customizeTooltip)) { return function(customizeObject) { var res = customizeTooltip.call(customizeObject, customizeObject); if (!("html" in res) && !("text" in res)) { _extend(res, defaultCustomizeTooltip.call(customizeObject, customizeObject)) } return res } } else { return defaultCustomizeTooltip } } function createAxis(isHorizontal) { var translator = new translator2DModule.Translator2D({}, {}, { isHorizontal: !!isHorizontal }); return { getTranslator: function() { return translator }, update: function(range, canvas) { translator.update(range, canvas) }, getViewport: function() { return } } } var BaseSparkline = BaseWidget.inherit({ _setDeprecatedOptions: function() { this.callBase(); _extend(this._deprecatedOptions, { "tooltip.verticalAlignment": { since: "15.1", message: "Now tooltips are aligned automatically" }, "tooltip.horizontalAlignment": { since: "15.1", message: "Now tooltips are aligned automatically" } }) }, _getLayoutItems: _noop, _useLinks: false, _themeDependentChanges: ["OPTIONS"], _initCore: function() { var that = this; that._tooltipTracker = that._renderer.root; that._tooltipTracker.attr({ "pointer-events": "visible" }); that._createHtmlElements(); that._initTooltipEvents(); that._argumentAxis = createAxis(true); that._valueAxis = createAxis() }, _getDefaultSize: function() { return this._defaultSize }, _disposeCore: function() { this._disposeWidgetElements(); this._disposeTooltipEvents(); this._ranges = null }, _optionChangesOrder: ["OPTIONS"], _change_OPTIONS: function() { this._prepareOptions(); this._change(["UPDATE"]) }, _customChangesOrder: ["UPDATE"], _change_UPDATE: function() { this._update() }, _update: function() { var that = this; if (that._tooltipShown) { that._tooltipShown = false; that._tooltip.hide() } that._cleanWidgetElements(); that._updateWidgetElements(); that._drawWidgetElements() }, _updateWidgetElements: function() { this._updateRange(); this._argumentAxis.update(this._ranges.arg, this._canvas); this._valueAxis.update(this._ranges.val, this._canvas) }, _applySize: function(rect) { this._allOptions.size = { width: rect[2] - rect[0], height: rect[3] - rect[1] }; this._change(["UPDATE"]) }, _setupResizeHandler: _noop, _prepareOptions: function() { return _extend(true, {}, this._themeManager.theme(), this.option()) }, _createThemeManager: function() { var themeManager = new baseThemeManagerModule.BaseThemeManager; themeManager._themeSection = this._widgetType; themeManager._fontFields = ["tooltip.font"]; return themeManager }, _getTooltipCoords: function() { var canvas = this._canvas, rootOffset = this._renderer.getRootOffset(); return { x: canvas.width / 2 + rootOffset.left, y: canvas.height / 2 + rootOffset.top } }, _initTooltipEvents: function() { var that = this, data = { widget: that }; that._showTooltipCallback = function() { var tooltip; that._showTooltipTimeout = null; if (!that._tooltipShown) { that._tooltipShown = true; tooltip = that._getTooltip(); tooltip.isEnabled() && that._tooltip.show(that._getTooltipData(), that._getTooltipCoords(), {}) } that._DEBUG_showCallback && that._DEBUG_showCallback() }; that._hideTooltipCallback = function() { var tooltipWasShown = that._tooltipShown; that._hideTooltipTimeout = null; if (that._tooltipShown) { that._tooltipShown = false; that._tooltip.hide() } that._DEBUG_hideCallback && that._DEBUG_hideCallback(tooltipWasShown) }; that._disposeCallbacks = function() { that = that._showTooltipCallback = that._hideTooltipCallback = that._disposeCallbacks = null }; that._tooltipTracker.on(mouseEvents, data).on(touchEvents, data).on(mouseWheelEvents, data); that._tooltipTracker.on(menuEvents) }, _disposeTooltipEvents: function() { var that = this; clearTimeout(that._showTooltipTimeout); clearTimeout(that._hideTooltipTimeout); that._tooltipTracker.off(); that._disposeCallbacks() }, _getTooltip: function() { var that = this; if (!that._tooltip) { _initTooltip.apply(this, arguments); that._setTooltipRendererOptions(that._tooltipRendererOptions); that._tooltipRendererOptions = null; that._setTooltipOptions() } return that._tooltip } }); var menuEvents = { "contextmenu.sparkline-tooltip": function(event) { if (eventUtils.isTouchEvent(event) || eventUtils.isPointerEvent(event)) { event.preventDefault() } }, "MSHoldVisual.sparkline-tooltip": function(event) { event.preventDefault() } }; var mouseEvents = { "mouseover.sparkline-tooltip": function(event) { isPointerDownCalled = false; var widget = event.data.widget; widget._x = event.pageX; widget._y = event.pageY; widget._tooltipTracker.off(mouseMoveEvents).on(mouseMoveEvents, event.data); widget._showTooltip(DEFAULT_EVENTS_DELAY) }, "mouseout.sparkline-tooltip": function(event) { if (isPointerDownCalled) { return } var widget = event.data.widget; widget._tooltipTracker.off(mouseMoveEvents); widget._hideTooltip(DEFAULT_EVENTS_DELAY) } }; var mouseWheelEvents = {}; mouseWheelEvents[wheelEvent.name + ".sparkline-tooltip"] = function(event) { event.data.widget._hideTooltip() }; var mouseMoveEvents = { "mousemove.sparkline-tooltip": function(event) { var widget = event.data.widget; if (widget._showTooltipTimeout && (_abs(widget._x - event.pageX) > 3 || _abs(widget._y - event.pageY) > 3)) { widget._x = event.pageX; widget._y = event.pageY; widget._showTooltip(DEFAULT_EVENTS_DELAY) } } }; var active_touch_tooltip_widget = null, touchStartTooltipProcessing = function(event) { event.preventDefault(); var widget = active_touch_tooltip_widget; if (widget && widget !== event.data.widget) { widget._hideTooltip(DEFAULT_EVENTS_DELAY) } widget = active_touch_tooltip_widget = event.data.widget; widget._showTooltip(TOUCH_EVENTS_DELAY); widget._touch = true }, touchStartDocumentProcessing = function() { var widget = active_touch_tooltip_widget; if (widget) { if (!widget._touch) { widget._hideTooltip(DEFAULT_EVENTS_DELAY); active_touch_tooltip_widget = null } widget._touch = null } }, touchEndDocumentProcessing = function() { var widget = active_touch_tooltip_widget; if (widget) { if (widget._showTooltipTimeout) { widget._hideTooltip(DEFAULT_EVENTS_DELAY); active_touch_tooltip_widget = null } } }, isPointerDownCalled = false; var touchEvents = { "pointerdown.sparkline-tooltip": touchStartTooltipProcessing, "touchstart.sparkline-tooltip": touchStartTooltipProcessing }; $(document).on({ "pointerdown.sparkline-tooltip": function() { isPointerDownCalled = true; touchStartDocumentProcessing() }, "touchstart.sparkline-tooltip": touchStartDocumentProcessing, "pointerup.sparkline-tooltip": touchEndDocumentProcessing, "touchend.sparkline-tooltip": touchEndDocumentProcessing }); module.exports = BaseSparkline; module.exports._DEBUG_reset = function() { active_touch_tooltip_widget = null }; BaseSparkline.addPlugin(__webpack_require__( /*! ../core/tooltip */ 559).plugin); var _initTooltip = BaseSparkline.prototype._initTooltip; BaseSparkline.prototype._initTooltip = _noop; var _disposeTooltip = BaseSparkline.prototype._disposeTooltip; BaseSparkline.prototype._disposeTooltip = function() { if (this._tooltip) { _disposeTooltip.apply(this, arguments) } }; BaseSparkline.prototype._setTooltipRendererOptions = function() { var options = this._getRendererOptions(); if (this._tooltip) { this._tooltip.setRendererOptions(options) } else { this._tooltipRendererOptions = options } }; BaseSparkline.prototype._setTooltipOptions = function() { var tooltip = this._tooltip, options = tooltip && this._getOption("tooltip"); tooltip && tooltip.update(_extend({}, options, { customizeTooltip: generateCustomizeTooltipCallback(options.customizeTooltip, options.font, this.option("rtlEnabled")), enabled: options.enabled && this._isTooltipEnabled() })) }; BaseSparkline.prototype._showTooltip = function(delay) { var that = this; ++that._DEBUG_clearHideTooltipTimeout; clearTimeout(that._hideTooltipTimeout); that._hideTooltipTimeout = null; clearTimeout(that._showTooltipTimeout); ++that._DEBUG_showTooltipTimeoutSet; that._showTooltipTimeout = setTimeout(that._showTooltipCallback, delay) }; BaseSparkline.prototype._hideTooltip = function(delay) { var that = this; ++that._DEBUG_clearShowTooltipTimeout; clearTimeout(that._showTooltipTimeout); that._showTooltipTimeout = null; clearTimeout(that._hideTooltipTimeout); if (delay) { ++that._DEBUG_hideTooltipTimeoutSet; that._hideTooltipTimeout = setTimeout(that._hideTooltipCallback, delay) } else { that._hideTooltipCallback() } }; var exportPlugin = extend(true, {}, __webpack_require__( /*! ../core/export */ 511).plugin, { init: _noop, dispose: _noop, customize: null, members: { _getExportMenuOptions: null } }); BaseSparkline.addPlugin(exportPlugin) }, /*!**************************!*\ !*** ./js/viz/bullet.js ***! \**************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./sparklines/bullet */ 631) }, /*!*************************************!*\ !*** ./js/viz/sparklines/bullet.js ***! \*************************************/ function(module, exports, __webpack_require__) { var $ = __webpack_require__( /*! ../../core/renderer */ 9), BaseSparkline = __webpack_require__( /*! ./base_sparkline */ 629), TARGET_MIN_Y = .02, TARGET_MAX_Y = .98, BAR_VALUE_MIN_Y = .1, BAR_VALUE_MAX_Y = .9, DEFAULT_CANVAS_WIDTH = 300, DEFAULT_CANVAS_HEIGHT = 30, DEFAULT_HORIZONTAL_MARGIN = 1, DEFAULT_VERTICAL_MARGIN = 2, _Number = Number, _isFinite = isFinite; var dxBullet = BaseSparkline.inherit({ _rootClassPrefix: "dxb", _rootClass: "dxb-bullet", _widgetType: "bullet", _defaultSize: { width: DEFAULT_CANVAS_WIDTH, height: DEFAULT_CANVAS_HEIGHT, left: DEFAULT_HORIZONTAL_MARGIN, right: DEFAULT_HORIZONTAL_MARGIN, top: DEFAULT_VERTICAL_MARGIN, bottom: DEFAULT_VERTICAL_MARGIN }, _disposeWidgetElements: function() { delete this._zeroLevelPath; delete this._targetPath; delete this._barValuePath }, _cleanWidgetElements: function() { this._zeroLevelPath.remove(); this._targetPath.remove(); this._barValuePath.remove() }, _drawWidgetElements: function() { this._drawBullet(); this._drawn() }, _createHtmlElements: function() { var renderer = this._renderer; this._zeroLevelPath = renderer.path(void 0, "line").attr({ "class": "dxb-zero-level", "stroke-linecap": "square" }); this._targetPath = renderer.path(void 0, "line").attr({ "class": "dxb-target", "stroke-linecap": "square" }); this._barValuePath = renderer.path(void 0, "line").attr({ "class": "dxb-bar-value", "stroke-linecap": "square" }) }, _prepareOptions: function() { var options, startScaleValue, endScaleValue, level, value, target, isValueUndefined, isTargetUndefined, that = this; that._allOptions = options = that.callBase(); isValueUndefined = void 0 === that._allOptions.value; isTargetUndefined = void 0 === that._allOptions.target; that._tooltipEnabled = !(isValueUndefined && isTargetUndefined); if (isValueUndefined) { that._allOptions.value = 0 } if (isTargetUndefined) { that._allOptions.target = 0 } options.value = value = _Number(options.value); options.target = target = _Number(options.target); if (void 0 === that._allOptions.startScaleValue) { that._allOptions.startScaleValue = target < value ? target : value; that._allOptions.startScaleValue = that._allOptions.startScaleValue < 0 ? that._allOptions.startScaleValue : 0 } if (void 0 === that._allOptions.endScaleValue) { that._allOptions.endScaleValue = target > value ? target : value } options.startScaleValue = startScaleValue = _Number(options.startScaleValue); options.endScaleValue = endScaleValue = _Number(options.endScaleValue); if (endScaleValue < startScaleValue) { level = endScaleValue; that._allOptions.endScaleValue = startScaleValue; that._allOptions.startScaleValue = level; that._allOptions.inverted = true } }, _updateRange: function() { var that = this, options = that._allOptions; that._ranges = { arg: { invert: options.inverted, min: options.startScaleValue, max: options.endScaleValue, axisType: "continuous", dataType: "numeric" }, val: { min: 0, max: 1, axisType: "continuous", dataType: "numeric" } } }, _drawBullet: function() { var that = this, options = that._allOptions, isValidBounds = options.startScaleValue !== options.endScaleValue, isValidMin = _isFinite(options.startScaleValue), isValidMax = _isFinite(options.endScaleValue), isValidValue = _isFinite(options.value), isValidTarget = _isFinite(options.target); if (isValidBounds && isValidMax && isValidMin && isValidTarget && isValidValue) { this._drawBarValue(); this._drawTarget(); this._drawZeroLevel() } }, _getTargetParams: function() { var that = this, options = that._allOptions, translatorY = that._valueAxis.getTranslator(), x = that._argumentAxis.getTranslator().translate(options.target); return { points: [x, translatorY.translate(TARGET_MIN_Y), x, translatorY.translate(TARGET_MAX_Y)], stroke: options.targetColor, "stroke-width": options.targetWidth } }, _getBarValueParams: function() { var x1, x2, that = this, options = that._allOptions, translatorX = that._argumentAxis.getTranslator(), translatorY = that._valueAxis.getTranslator(), startLevel = options.startScaleValue, endLevel = options.endScaleValue, value = options.value, y2 = translatorY.translate(BAR_VALUE_MIN_Y), y1 = translatorY.translate(BAR_VALUE_MAX_Y); if (value > 0) { x1 = startLevel <= 0 ? 0 : startLevel; x2 = value >= endLevel ? endLevel : value < x1 ? x1 : value } else { x1 = endLevel >= 0 ? 0 : endLevel; x2 = value < startLevel ? startLevel : value > x1 ? x1 : value } x1 = translatorX.translate(x1); x2 = translatorX.translate(x2); return { points: [x1, y1, x2, y1, x2, y2, x1, y2], fill: options.color } }, _getZeroLevelParams: function() { var that = this, translatorY = that._valueAxis.getTranslator(), x = that._argumentAxis.getTranslator().translate(0); return { points: [x, translatorY.translate(TARGET_MIN_Y), x, translatorY.translate(TARGET_MAX_Y)], stroke: that._allOptions.targetColor, "stroke-width": 1 } }, _drawZeroLevel: function() { var that = this, options = that._allOptions; if (0 > options.endScaleValue || 0 < options.startScaleValue || !options.showZeroLevel) { return } that._zeroLevelPath.attr(that._getZeroLevelParams()).sharp().append(that._renderer.root) }, _drawTarget: function() { var that = this, options = that._allOptions, target = options.target; if (target > options.endScaleValue || target < options.startScaleValue || !options.showTarget) { return } that._targetPath.attr(that._getTargetParams()).sharp().append(that._renderer.root) }, _drawBarValue: function() { this._barValuePath.attr(this._getBarValueParams()).append(this._renderer.root) }, _getTooltipCoords: function() { var canvas = this._canvas, rootOffset = this._renderer.getRootOffset(), bBox = this._barValuePath.getBBox(); return { x: bBox.x + bBox.width / 2 + rootOffset.left, y: canvas.height / 2 + rootOffset.top } }, _getTooltipData: function() { var that = this, tooltip = that._tooltip, options = that._allOptions, value = options.value, target = options.target, valueText = tooltip.formatValue(value), targetText = tooltip.formatValue(target); return { originalValue: value, originalTarget: target, value: valueText, target: targetText, valueText: ["Actual Value:", valueText, "Target Value:", targetText] } }, _isTooltipEnabled: function() { return this._tooltipEnabled } }); $.each(["color", "targetColor", "targetWidth", "showTarget", "showZeroLevel", "value", "target", "startScaleValue", "endScaleValue"], function(_, name) { dxBullet.prototype._optionChangesMap[name] = "OPTIONS" }); __webpack_require__( /*! ../../core/component_registrator */ 57)("dxBullet", dxBullet); module.exports = dxBullet }, /*!****************************!*\ !*** ./js/viz/tree_map.js ***! \****************************/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__( /*! ./tree_map/tree_map */ 633) }, /*!*************************************!*\ !*** ./js/viz/tree_map/tree_map.js ***! \*************************************/ function(module, exports, __webpack_require__) { var dxTreeMap = module.exports = __webpack_require__( /*! ./tree_map.base */ 634); __webpack_require__( /*! ./tiling.squarified */ 639); __webpack_require__( /*! ./tiling.strip */ 642); __webpack_require__( /*! ./tiling.slice_and_dice */ 643); __webpack_require__( /*! ./tiling.rotated_slice_and_dice */ 644); __webpack_require__( /*! ./colorizing.discrete */ 641); __webpack_require__( /*! ./colorizing.gradient */ 645); __webpack_require__( /*! ./colorizing.range */ 646); __webpack_require__( /*! ./api */ 647); __webpack_require__( /*! ./hover */ 648); __webpack_require__( /*! ./selection */ 650); __webpack_require__( /*! ./tooltip */ 651); __webpack_require__( /*! ./tracker */ 652); __webpack_require__( /*! ./drilldown */ 653); __webpack_require__( /*! ./plain_data_source */ 654); dxTreeMap.addPlugin(__webpack_require__( /*! ../core/export */ 511).plugin); dxTreeMap.addPlugin(__webpack_require__( /*! ../core/title */ 558).plugin); dxTreeMap.addPlugin(__webpack_require__( /*! ../core/loading_indicator */ 560).plugin) }, /*!******************************************!*\ !*** ./js/viz/tree_map/tree_map.base.js ***! \******************************************/ function(module, exports, __webpack_require__) { var common = __webpack_require__( /*! ./common */ 635), Node = __webpack_require__( /*! ./node */ 636), _getTilingAlgorithm = __webpack_require__( /*! ./tiling */ 637).getAlgorithm, _getColorizer = __webpack_require__( /*! ./colorizing */ 638).getColorizer, _patchFontOptions = __webpack_require__( /*! ../core/utils */ 509).patchFontOptions, _buildRectAppearance = common.buildRectAppearance, _buildTextAppearance = common.buildTextAppearance, _noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, _max = Math.max, directions = { lefttoprightbottom: [1, 1], leftbottomrighttop: [1, -1], righttopleftbottom: [-1, 1], rightbottomlefttop: [-1, -1] }; __webpack_require__( /*! ./tiling.squarified */ 639); __webpack_require__( /*! ./tiling */ 637).setDefaultAlgorithm("squarified"); __webpack_require__( /*! ./colorizing.discrete */ 641); __webpack_require__( /*! ./colorizing */ 638).setDefaultColorizer("discrete"); function pickPositiveInteger(val) { return val > 0 ? Math.round(val) : 0 } var dxTreeMap = __webpack_require__( /*! ../core/base_widget */ 515).inherit({ _handlers: { beginBuildNodes: _noop, buildNode: _noop, endBuildNodes: _noop, setTrackerData: _noop, calculateState: function(options) { return _buildRectAppearance(options) } }, _rootClass: "dxtm-tree-map", _rootClassPrefix: "dxtm", _getDefaultSize: function() { return { width: 400, height: 400 } }, _createThemeManager: function() { return new ThemeManager }, _init: function() { var that = this; that._rectOffsets = {}; that._handlers = Object.create(that._handlers); that._context = { suspend: function() { if (!that._applyingChanges) { that._suspendChanges() } }, resume: function() { if (!that._applyingChanges) { that._resumeChanges() } }, change: function(codes) { that._change(codes) }, settings: [{}, {}], calculateState: that._handlers.calculateState, calculateLabelState: _buildTextAppearance }; that._root = that._topNode = { nodes: [] }; that.callBase.apply(that, arguments) }, _initialChanges: ["DATA_SOURCE"], _initCore: function() { var that = this, renderer = that._renderer; that._createProxyType(); that._tilesGroup = renderer.g().linkOn(renderer.root, "tiles").linkAppend(); that._labelsGroup = renderer.g().attr({ align: "left" }).linkOn(renderer.root, "labels").linkAppend() }, _createProxyType: _noop, _disposeCore: function() { var that = this; that._filter && that._filter.dispose(); that._labelsGroup.linkOff(); that._tilesGroup.linkOff() }, _applySize: function(rect) { this._tilingRect = rect.slice(); this._change(["TILING"]) }, _optionChangesMap: { dataSource: "DATA_SOURCE", valueField: "NODES_CREATE", childrenField: "NODES_CREATE", colorField: "TILES", colorizer: "TILES", labelField: "LABELS", tile: "TILE_SETTINGS", group: "GROUP_SETTINGS", maxDepth: "MAX_DEPTH", layoutAlgorithm: "TILING", layoutDirection: "TILING", resolveLabelOverflow: "LABEL_OVERFLOW" }, _themeDependentChanges: ["TILE_SETTINGS", "GROUP_SETTINGS", "MAX_DEPTH"], _changeDataSource: function() { var that = this; that._isDataExpected = that._isSyncData = true; that._updateDataSource(); that._isSyncData = false; if (that._isDataExpected) { that._suspendChanges() } }, _dataSourceChangedHandler: function() { var that = this; if (that._isDataExpected) { that._isDataExpected = false; that._change(["NODES_CREATE"]); if (!that._isSyncData) { that._resumeChanges() } } else { that._requestChange(["NODES_CREATE"]) } }, _optionChangesOrder: ["DATA_SOURCE", "TILE_SETTINGS", "GROUP_SETTINGS", "MAX_DEPTH", "LABEL_OVERFLOW"], _change_DATA_SOURCE: function() { this._changeDataSource() }, _change_TILE_SETTINGS: function() { this._changeTileSettings() }, _change_GROUP_SETTINGS: function() { this._changeGroupSettings() }, _change_LABEL_OVERFLOW: function() { this._changeTileSettings(); this._changeGroupSettings() }, _change_MAX_DEPTH: function() { this._changeMaxDepth() }, _customChangesOrder: ["NODES_CREATE", "NODES_RESET", "TILES", "LABELS", "TILING", "LABELS_LAYOUT"], _change_NODES_CREATE: function() { this._buildNodes() }, _change_NODES_RESET: function() { this._resetNodes() }, _change_TILES: function() { this._applyTilesAppearance() }, _change_LABELS: function() { this._applyLabelsAppearance() }, _change_TILING: function() { this._performTiling() }, _change_LABELS_LAYOUT: function() { this._performLabelsLayout() }, _applyChanges: function() { var that = this; that.callBase.apply(that, arguments); if (!that._isDataExpected) { that._drawn() } that._context.forceReset = false }, _buildNodes: function() { var processedData, that = this, root = that._root = that._topNode = new Node; root._id = 0; root.parent = {}; root.data = {}; root.level = root.index = -1; root.ctx = that._context; root.label = null; that._nodes = [root]; that._handlers.beginBuildNodes(); processedData = that._processDataSourceItems(that._dataSourceItems() || []); traverseDataItems(root, processedData.items, 0, { itemsField: !processedData.isPlain && that._getOption("childrenField", true) || "items", valueField: that._getOption("valueField", true) || "value", buildNode: that._handlers.buildNode, ctx: that._context, nodes: that._nodes }); that._onNodesCreated(); that._handlers.endBuildNodes(); that._change(["NODES_RESET"]) }, _onNodesCreated: common.empty, _processDataSourceItems: function(items) { return { items: items, isPlain: false } }, _changeTileSettings: function() { var that = this, options = that._getOption("tile"), offsets = that._rectOffsets, borderWidth = pickPositiveInteger(options.border.width), edgeOffset = borderWidth / 2, innerOffset = 1 & borderWidth ? .5 : 0, labelOptions = options.label, settings = that._context.settings[0]; that._change(["TILES", "LABELS"]); settings.state = that._handlers.calculateState(options); that._filter = that._filter || that._renderer.shadowFilter("-50%", "-50%", "200%", "200%"); that._filter.attr(labelOptions.shadow); that._calculateLabelSettings(settings, labelOptions, that._filter.id); if (offsets.tileEdge !== edgeOffset || offsets.tileInner !== innerOffset) { offsets.tileEdge = edgeOffset; offsets.tileInner = innerOffset; that._change(["TILING"]) } }, _changeGroupSettings: function() { var that = this, options = that._getOption("group"), labelOptions = options.label, offsets = that._rectOffsets, borderWidth = pickPositiveInteger(options.border.width), edgeOffset = borderWidth / 2, innerOffset = 1 & borderWidth ? .5 : 0, headerHeight = 0, groupPadding = pickPositiveInteger(options.padding), settings = that._context.settings[1]; that._change(["TILES", "LABELS"]); settings.state = that._handlers.calculateState(options); that._calculateLabelSettings(settings, labelOptions); if (options.headerHeight >= 0) { headerHeight = pickPositiveInteger(options.headerHeight) } else { headerHeight = settings.labelParams.height + 2 * pickPositiveInteger(labelOptions.paddingTopBottom) } if (that._headerHeight !== headerHeight) { that._headerHeight = headerHeight; that._change(["TILING"]) } if (that._groupPadding !== groupPadding) { that._groupPadding = groupPadding; that._change(["TILING"]) } if (offsets.headerEdge !== edgeOffset || offsets.headerInner !== innerOffset) { offsets.headerEdge = edgeOffset; offsets.headerInner = innerOffset; that._change(["TILING"]) } }, _calculateLabelSettings: function(settings, options, filter) { var bBox = this._getTextBBox(options.font), paddingLeftRight = pickPositiveInteger(options.paddingLeftRight), paddingTopBottom = pickPositiveInteger(options.paddingTopBottom); settings.labelState = _buildTextAppearance(options, filter); settings.labelState.visible = !("visible" in options) || !!options.visible; settings.labelParams = { unitWidth: bBox.width, height: bBox.height, hOffset: paddingLeftRight, vOffset: -bBox.y + paddingTopBottom, rtlEnabled: this._getOption("rtlEnabled", true), paddingTopBottom: paddingTopBottom, paddingLeftRight: paddingLeftRight, resolveLabelOverflow: this._getOption("resolveLabelOverflow", true) } }, _changeMaxDepth: function() { var maxDepth = this._getOption("maxDepth", true); maxDepth = maxDepth >= 1 ? Math.round(maxDepth) : 1 / 0; if (this._maxDepth !== maxDepth) { this._maxDepth = maxDepth; this._change(["NODES_RESET"]) } }, _resetNodes: function() { var that = this; that._tilesGroup.clear(); that._renderer.initHatching(); that._context.forceReset = true; that._context.minLevel = that._topNode.level + 1; that._context.maxLevel = that._context.minLevel + that._maxDepth - 1; that._change(["TILES", "LABELS", "TILING"]) }, _processNodes: function(context, process) { processNodes(context, this._topNode, process) }, _applyTilesAppearance: function() { var that = this, colorizer = _getColorizer(that._getOption("colorizer"), that._themeManager, that._topNode); that._processNodes({ renderer: that._renderer, group: that._tilesGroup, setTrackerData: that._handlers.setTrackerData, colorField: that._getOption("colorField", true) || "color", getColor: colorizer }, processTileAppearance) }, _applyLabelsAppearance: function() { var that = this; that._labelsGroup.clear(); that._processNodes({ renderer: that._renderer, group: that._labelsGroup, setTrackerData: that._handlers.setTrackerData, labelField: that._getOption("labelField", true) || "name" }, processLabelAppearance); that._change(["LABELS_LAYOUT"]) }, _performTiling: function() { var that = this, context = { algorithm: _getTilingAlgorithm(that._getOption("layoutAlgorithm", true)), directions: directions[String(that._getOption("layoutDirection", true)).toLowerCase()] || directions.lefttoprightbottom, headerHeight: that._headerHeight, groupPadding: that._groupPadding, rectOffsets: that._rectOffsets }; that._topNode.innerRect = that._tilingRect; calculateRects(context, that._topNode); that._processNodes(context, processTiling); that._change(["LABELS_LAYOUT"]); that._onTilingPerformed() }, _onTilingPerformed: common.empty, _performLabelsLayout: function() { this._processNodes(null, processLabelsLayout) }, _getTextBBox: function(fontOptions) { var bBox, renderer = this._renderer, text = this._textForCalculations || renderer.text("0", 0, 0); this._textForCalculations = text; text.css(_patchFontOptions(fontOptions)).append(renderer.root); bBox = text.getBBox(); text.remove(); return bBox } }); function traverseDataItems(root, dataItems, level, params) { var node, i, dataItem, items, nodes = [], allNodes = params.nodes, ii = dataItems.length, totalValue = 0; for (i = 0; i < ii; ++i) { dataItem = dataItems[i]; node = new Node; node._id = allNodes.length; node.ctx = params.ctx; node.parent = root; node.level = level; node.index = nodes.length; node.data = dataItem; params.buildNode(node); allNodes.push(node); nodes.push(node); items = dataItem[params.itemsField]; if (items && items.length) { traverseDataItems(node, items, level + 1, params) } if (dataItem[params.valueField] > 0) { node.value = Number(dataItem[params.valueField]) } totalValue += node.value } root.nodes = nodes; root.value = totalValue } function processNodes(context, root, process) { var node, i, nodes = root.nodes, ii = nodes.length; for (i = 0; i < ii; ++i) { node = nodes[i]; process(context, node); if (node.isNode()) { processNodes(context, node, process) } } } function processTileAppearance(context, node) { node.color = node.data[context.colorField] || context.getColor(node) || node.parent.color; node.updateStyles(); node.tile = !node.ctx.forceReset && node.tile || createTile[Number(node.isNode())](context, node); node.applyState() } var createTile = [createLeaf, createGroup]; function createLeaf(context, node) { var tile = context.renderer.simpleRect().append(context.group); context.setTrackerData(node, tile); return tile } function createGroup(context, node) { var outer = context.renderer.simpleRect().append(context.group), inner = context.renderer.simpleRect().append(context.group); context.setTrackerData(node, inner); return { outer: outer, inner: inner } } function processLabelAppearance(context, node) { node.updateLabelStyle(); if (node.labelState.visible) { createLabel(context, node, node.labelState, node.labelParams) } } function createLabel(context, currentNode, settings, params) { var textData = currentNode.data[context.labelField]; currentNode.label = textData ? String(textData) : null; textData = currentNode.customLabel || currentNode.label; if (textData) { currentNode.text = context.renderer.text(textData).attr(settings.attr).css(settings.css).append(context.group); context.setTrackerData(currentNode, currentNode.text); currentNode.textWidth = params.unitWidth * textData.length } } var emptyRect = [0, 0, 0, 0]; function calculateRects(context, root) { var i, nodes = root.nodes, items = [], rects = [], sum = 0, ii = items.length = rects.length = nodes.length; for (i = 0; i < ii; ++i) { sum += nodes[i].value; items[i] = { value: nodes[i].value, i: i } } if (sum > 0) { context.algorithm({ items: items.slice(), sum: sum, rect: root.innerRect.slice(), isRotated: 1 & nodes[0].level, directions: context.directions }) } for (i = 0; i < ii; ++i) { rects[i] = items[i].rect || emptyRect } root.rects = rects } function processTiling(context, node) { var headerHeight, rect = node.parent.rects[node.index], rectOffsets = context.rectOffsets; if (node.isNode()) { setRectAttrs(node.tile.outer, buildTileRect(rect, node.parent.innerRect, rectOffsets.headerEdge, rectOffsets.headerInner)); rect = marginateRect(rect, context.groupPadding); headerHeight = Math.min(context.headerHeight, rect[3] - rect[1]); node.rect = [rect[0], rect[1], rect[2], rect[1] + headerHeight]; setRectAttrs(node.tile.inner, marginateRect(node.rect, rectOffsets.headerEdge)); rect[1] += headerHeight; node.innerRect = rect; calculateRects(context, node) } else { node.rect = rect; setRectAttrs(node.tile, buildTileRect(rect, node.parent.innerRect, rectOffsets.tileEdge, rectOffsets.tileInner)) } } function marginateRect(rect, margin) { return [rect[0] + margin, rect[1] + margin, rect[2] - margin, rect[3] - margin] } function buildTileRect(rect, outer, edgeOffset, innerOffset) { return [rect[0] + (rect[0] === outer[0] ? edgeOffset : +innerOffset), rect[1] + (rect[1] === outer[1] ? edgeOffset : +innerOffset), rect[2] - (rect[2] === outer[2] ? edgeOffset : -innerOffset), rect[3] - (rect[3] === outer[3] ? edgeOffset : -innerOffset)] } function setRectAttrs(element, rect) { element.attr({ x: rect[0], y: rect[1], width: _max(rect[2] - rect[0], 0), height: _max(rect[3] - rect[1], 0) }) } function processLabelsLayout(context, node) { if (node.text && node.labelState.visible) { layoutTextNode(node, node.labelParams) } } function layoutTextNode(node, params) { var rect = node.rect, hOffset = params.hOffset, effectiveWidth = rect[2] - rect[0] - params.paddingLeftRight, fitByHeight = params.height + params.paddingTopBottom < rect[3] - rect[1], fitByWidth = node.textWidth < effectiveWidth; if ("ellipsis" === params.resolveLabelOverflow && fitByHeight) { node.text.applyEllipsis(effectiveWidth); if (!fitByWidth) { fitByWidth = node.text.getBBox().width < effectiveWidth } } node.text.attr({ x: params.rtlEnabled ? rect[2] - hOffset : rect[0] + hOffset, y: rect[1] + params.vOffset, visibility: fitByHeight && fitByWidth ? "visible" : "hidden" }) } var ThemeManager = __webpack_require__( /*! ../core/base_theme_manager */ 550).BaseThemeManager.inherit({ _themeSection: "treeMap", _fontFields: ["tile.label.font", "group.label.font", "loadingIndicator.font", "title.font", "title.subtitle.font", "tooltip.font"] }); __webpack_require__( /*! ../../core/component_registrator */ 57)("dxTreeMap", dxTreeMap); module.exports = dxTreeMap; dxTreeMap.addPlugin(__webpack_require__( /*! ../core/data_source */ 561).plugin) }, /*!***********************************!*\ !*** ./js/viz/tree_map/common.js ***! \***********************************/ function(module, exports, __webpack_require__) { var _patchFontOptions = __webpack_require__( /*! ../core/utils */ 509).patchFontOptions; function empty() {} exports.empty = empty; function createChainExecutor() { var chain = []; executeChain.add = function(item) { chain.push(item) }; return executeChain; function executeChain() { var i, ii = chain.length; for (i = 0; i < ii; ++i) { chain[i].apply(this, arguments) } } } exports.expand = function(target, name, expander) { var current = target[name]; if (current.add) { current.add(expander) } else { if (current === empty) { current = expander } else { current = createChainExecutor(); current.add(target[name]); current.add(expander) } } target[name] = current }; exports.buildRectAppearance = function(option) { var border = option.border || {}; return { fill: option.color, opacity: option.opacity, stroke: border.color, "stroke-width": border.width, "stroke-opacity": border.opacity, hatching: option.hatching } }; exports.buildTextAppearance = function(options, filter) { return { attr: options["stroke-width"] ? { stroke: options.stroke, "stroke-width": options["stroke-width"], "stroke-opacity": options["stroke-opacity"], filter: filter } : {}, css: _patchFontOptions(options.font) } } }, /*!*********************************!*\ !*** ./js/viz/tree_map/node.js ***! \*********************************/ function(module, exports, __webpack_require__) { var _extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend; function Node() {} _extend(Node.prototype, { value: 0, isNode: function() { return !!(this.nodes && this.level < this.ctx.maxLevel) }, isActive: function() { var ctx = this.ctx; return this.level >= ctx.minLevel && this.level <= ctx.maxLevel }, updateStyles: function() { var that = this, isNode = Number(that.isNode()); that.state = that._buildState(that.ctx.settings[isNode].state, !isNode && that.color && { fill: that.color }) }, _buildState: function(state, extra) { var base = _extend({}, state); return extra ? _extend(base, extra) : base }, updateLabelStyle: function() { var settings = this.ctx.settings[Number(this.isNode())]; this.labelState = settings.labelState; this.labelParams = settings.labelParams }, _getState: function() { return this.state }, applyState: function() { updateTile[Number(this.isNode())](this.tile, this._getState()) } }); var updateTile = [updateLeaf, updateGroup]; function updateLeaf(content, attrs) { content.smartAttr(attrs) } function updateGroup(content, attrs) { content.outer.attr({ stroke: attrs.stroke, "stroke-width": attrs["stroke-width"], "stroke-opacity": attrs["stroke-opacity"] }); content.inner.smartAttr({ fill: attrs.fill, opacity: attrs.opacity, hatching: attrs.hatching }) } module.exports = Node }, /*!***********************************!*\ !*** ./js/viz/tree_map/tiling.js ***! \***********************************/ function(module, exports, __webpack_require__) { var defaultAlgorithm, _isFunction = __webpack_require__( /*! ../../core/utils/common */ 14).isFunction, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _round = Math.round, algorithms = {}; exports.getAlgorithm = function(value) { return algorithms[_normalizeEnum(value)] || _isFunction(value) && value || defaultAlgorithm }; exports.addAlgorithm = function(name, callback) { algorithms[name] = callback }; exports.setDefaultAlgorithm = function(name) { defaultAlgorithm = algorithms[name] }; var directionToIndexOffsets = {}; directionToIndexOffsets[-1] = [2, 0]; directionToIndexOffsets[1] = [0, 2]; var getStaticSideIndex = function(rect) { return rect[2] - rect[0] < rect[3] - rect[1] ? 0 : 1 }; exports.getStaticSideIndex = getStaticSideIndex; exports.buildSidesData = function(rect, directions, _staticSideIndex) { var staticSideIndex = void 0 !== _staticSideIndex ? _staticSideIndex : getStaticSideIndex(rect), variedSideIndex = 1 - staticSideIndex, staticSideDirection = directions[staticSideIndex], variedSideDirection = directions[variedSideIndex], staticSideIndexOffsets = directionToIndexOffsets[staticSideDirection], variedSideIndexOffsets = directionToIndexOffsets[variedSideDirection]; return { staticSide: rect[2 + staticSideIndex] - rect[staticSideIndex], variedSide: rect[2 + variedSideIndex] - rect[variedSideIndex], static1: staticSideIndex + staticSideIndexOffsets[0], static2: staticSideIndex + staticSideIndexOffsets[1], varied1: variedSideIndex + variedSideIndexOffsets[0], varied2: variedSideIndex + variedSideIndexOffsets[1], staticDir: staticSideDirection, variedDir: variedSideDirection } }; exports.calculateRectangles = function(nodes, head, totalRect, sidesData, rowData) { var i, ii, rect, delta, variedSidePart = [0, 0, 0, 0], static1 = sidesData.static1, static2 = sidesData.static2, position = totalRect[static1], dir = sidesData.staticDir, side = sidesData.staticSide, sum = rowData.sum; variedSidePart[sidesData.varied1] = totalRect[sidesData.varied1]; variedSidePart[sidesData.varied2] = totalRect[sidesData.varied1] + sidesData.variedDir * rowData.side; for (i = head, ii = head + rowData.count; i < ii; ++i) { rect = variedSidePart.slice(); rect[static1] = position; delta = _round(side * nodes[i].value / sum) || 0; sum -= nodes[i].value; side -= delta; position += dir * delta; rect[static2] = position; nodes[i].rect = rect } totalRect[sidesData.varied1] = variedSidePart[sidesData.varied2] } }, /*!***************************************!*\ !*** ./js/viz/tree_map/colorizing.js ***! \***************************************/ function(module, exports, __webpack_require__) { var defaultColorizerName, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _noop = __webpack_require__( /*! ../../core/utils/common */ 14).noop, colorizers = {}; function wrapLeafColorGetter(getter) { return function(node) { return !node.isNode() ? getter(node) : void 0 } } function wrapGroupColorGetter(getter) { return function(node) { var parent = !node.isNode() && node.parent; return parent ? parent._groupColor = parent._groupColor || getter(parent) : void 0 } } exports.getColorizer = function(options, themeManager, root) { var type = _normalizeEnum(options.type || defaultColorizerName), colorizer = colorizers[type] && colorizers[type](options, themeManager, root); return colorizer ? (options.colorizeGroups ? wrapGroupColorGetter : wrapLeafColorGetter)(colorizer) : _noop }; exports.addColorizer = function(name, colorizer) { colorizers[name] = colorizer }; exports.setDefaultColorizer = function(name) { defaultColorizerName = name }; function getValueAsColorCode(node) { return node.value } function createColorCodeGetter(colorCodeField) { return function(node) { return Number(node.data[colorCodeField]) } } exports.createColorCodeGetter = function(options) { return options.colorCodeField ? createColorCodeGetter(options.colorCodeField) : getValueAsColorCode } }, /*!**********************************************!*\ !*** ./js/viz/tree_map/tiling.squarified.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var _max = Math.max, _squarify = __webpack_require__( /*! ./tiling.squarified.base */ 640); function accumulate(total, current) { return _max(total, current) } function squarified(data) { return _squarify(data, accumulate, false) } __webpack_require__( /*! ./tiling */ 637).addAlgorithm("squarified", squarified); module.exports = squarified }, /*!***************************************************!*\ !*** ./js/viz/tree_map/tiling.squarified.base.js ***! \***************************************************/ function(module, exports, __webpack_require__) { var _max = Math.max, _round = Math.round, tiling = __webpack_require__( /*! ./tiling */ 637); function compare(a, b) { return b.value - a.value } function getAspectRatio(value) { return _max(value, 1 / value) } function findAppropriateCollection(nodes, head, context) { var nextAspectRatio, nextSum, i, j, totalAspectRatio, bestAspectRatio = 1 / 0, sum = 0, ii = nodes.length, coeff = context.areaToValue / context.staticSide; for (i = head; i < ii;) { nextSum = sum + nodes[i].value; totalAspectRatio = context.staticSide / coeff / nextSum; nextAspectRatio = 0; for (j = head; j <= i; ++j) { nextAspectRatio = context.accumulate(nextAspectRatio, getAspectRatio(totalAspectRatio * nodes[j].value / nextSum), j - head + 1) } if (nextAspectRatio < bestAspectRatio) { bestAspectRatio = nextAspectRatio; sum = nextSum; ++i } else { break } } return { sum: sum, count: i - head, side: _round(coeff * sum) } } function getArea(rect) { return (rect[2] - rect[0]) * (rect[3] - rect[1]) } function doStep(nodes, head, context) { var sidesData = tiling.buildSidesData(context.rect, context.directions, context.staticSideIndex), area = getArea(context.rect), rowData = area > 0 ? findAppropriateCollection(nodes, head, { areaToValue: area / context.sum, accumulate: context.accumulate, staticSide: sidesData.staticSide }) : { sum: 1, side: sidesData.variedSide, count: nodes.length - head }; tiling.calculateRectangles(nodes, head, context.rect, sidesData, rowData); context.sum -= rowData.sum; return head + rowData.count } module.exports = function(data, accumulate, isFixedStaticSide) { var i, items = data.items, ii = items.length, context = { sum: data.sum, rect: data.rect, directions: data.directions, accumulate: accumulate }; if (isFixedStaticSide) { context.staticSideIndex = tiling.getStaticSideIndex(context.rect) } items.sort(compare); for (i = 0; i < ii;) { i = doStep(items, i, context) } } }, /*!************************************************!*\ !*** ./js/viz/tree_map/colorizing.discrete.js ***! \************************************************/ function(module, exports, __webpack_require__) { function discreteColorizer(options, themeManager, root) { var palette = themeManager.createPalette(options.palette, { useHighlight: true }); return (options.colorizeGroups ? discreteGroupColorizer : discreteLeafColorizer)(palette, root) } function generateColors(palette, colors, count) { var i; for (i = colors.length; i < count; ++i) { colors.push(palette.getNextColor()) } } function discreteLeafColorizer(palette) { var colors = []; generateColors(palette, colors, 4); return function(node) { if (node.index >= colors.length) { generateColors(palette, colors, 2 * colors.length) } return colors[node.index] } } function prepareDiscreteGroupColors(palette, root) { var i, node, colors = {}, allNodes = root.nodes.slice(), ii = allNodes.length; for (i = 0; i < ii; ++i) { node = allNodes[i]; if (node.isNode()) { allNodes = allNodes.concat(node.nodes); ii = allNodes.length } else { if (!colors[node.parent._id]) { colors[node.parent._id] = palette.getNextColor() } } } return colors } function discreteGroupColorizer(palette, root) { var colors = prepareDiscreteGroupColors(palette, root); return function(node) { return colors[node._id] } } __webpack_require__( /*! ./colorizing */ 638).addColorizer("discrete", discreteColorizer); module.exports = discreteColorizer }, /*!*****************************************!*\ !*** ./js/viz/tree_map/tiling.strip.js ***! \*****************************************/ function(module, exports, __webpack_require__) { var _squarify = __webpack_require__( /*! ./tiling.squarified.base */ 640); function accumulate(total, current, count) { return ((count - 1) * total + current) / count } function strip(data) { return _squarify(data, accumulate, true) } __webpack_require__( /*! ./tiling */ 637).addAlgorithm("strip", strip); module.exports = strip }, /*!**************************************************!*\ !*** ./js/viz/tree_map/tiling.slice_and_dice.js ***! \**************************************************/ function(module, exports, __webpack_require__) { var tiling = __webpack_require__( /*! ./tiling */ 637); function sliceAndDice(data) { var items = data.items, sidesData = tiling.buildSidesData(data.rect, data.directions, data.isRotated ? 1 : 0); tiling.calculateRectangles(items, 0, data.rect, sidesData, { sum: data.sum, count: items.length, side: sidesData.variedSide }) } tiling.addAlgorithm("sliceanddice", sliceAndDice); module.exports = sliceAndDice }, /*!**********************************************************!*\ !*** ./js/viz/tree_map/tiling.rotated_slice_and_dice.js ***! \**********************************************************/ function(module, exports, __webpack_require__) { var tiling = __webpack_require__( /*! ./tiling */ 637), sliceAndDiceAlgorithm = tiling.getAlgorithm("sliceanddice"); function rotatedSliceAndDice(data) { data.isRotated = !data.isRotated; return sliceAndDiceAlgorithm.call(this, data) } tiling.addAlgorithm("rotatedsliceanddice", rotatedSliceAndDice) }, /*!************************************************!*\ !*** ./js/viz/tree_map/colorizing.gradient.js ***! \************************************************/ function(module, exports, __webpack_require__) { var _createColorCodeGetter = __webpack_require__( /*! ./colorizing */ 638).createColorCodeGetter, _min = Math.min, _max = Math.max; function createSimpleColorizer(getColor, range) { return function(node) { return getColor(node, range) } } function getRangeData(range) { return [Number(range[0]) || 0, range[1] - range[0] || 1] } function calculateRange(nodes, getValue) { var i, code, ii = nodes.length, codes = []; for (i = 0; i < ii; ++i) { code = getValue(nodes[i]); if (isFinite(code)) { codes.push(code) } } return getRangeData([_min.apply(null, codes), _max.apply(null, codes)]) } function createGuessingColorizer(getColor, getValue) { var ranges = {}; return function(node) { var parent = node.parent; return getColor(node, ranges[parent._id] || (ranges[parent._id] = calculateRange(parent.nodes, getValue))) } } function gradientColorizer(options, themeManager) { var palette = themeManager.createGradientPalette(options.palette), getValue = _createColorCodeGetter(options); return "range" in options ? createSimpleColorizer(getColor, getRangeData(options.range || [])) : createGuessingColorizer(getColor, getValue); function getColor(node, arg) { return palette.getColor((getValue(node) - arg[0]) / arg[1]) } } __webpack_require__( /*! ./colorizing */ 638).addColorizer("gradient", gradientColorizer); module.exports = gradientColorizer }, /*!*********************************************!*\ !*** ./js/viz/tree_map/colorizing.range.js ***! \*********************************************/ function(module, exports, __webpack_require__) { var _createColorCodeGetter = __webpack_require__( /*! ./colorizing */ 638).createColorCodeGetter; function getPaletteIndex(value, items) { var middle, start = 0, end = items.length - 1, index = -1; if (items[start] <= value && value <= items[end]) { if (value === items[end]) { index = end - 1 } else { while (end - start > 1) { middle = start + end >> 1; if (value < items[middle]) { end = middle } else { start = middle } } index = start } } return index } function rangeColorizer(options, themeManager) { var range = options.range || [], palette = themeManager.createDiscretePalette(options.palette, range.length - 1), getValue = _createColorCodeGetter(options); return function(node) { return palette.getColor(getPaletteIndex(getValue(node), range)) } } __webpack_require__( /*! ./colorizing */ 638).addColorizer("range", rangeColorizer); module.exports = rangeColorizer }, /*!********************************!*\ !*** ./js/viz/tree_map/api.js ***! \********************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, nodeProto = __webpack_require__( /*! ./node */ 636).prototype, _extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend; proto._eventsMap.onNodesInitialized = { name: "nodesInitialized" }; proto._eventsMap.onNodesRendering = { name: "nodesRendering" }; proto._createProxyType = function() { var nodes, that = this; Proxy.prototype = { constructor: Proxy, getParent: function() { return nodes[this._id].parent.proxy || null }, getChild: function(index) { var _nodes = nodes[this._id].nodes; return _nodes ? _nodes[index].proxy : null }, getChildrenCount: function() { var _nodes = nodes[this._id].nodes; return _nodes ? _nodes.length : 0 }, getAllChildren: function() { var i, _nodes = nodes[this._id].nodes, ii = _nodes && _nodes.length, list = []; for (i = 0; i < ii; ++i) { list.push(_nodes[i].proxy) } return list }, getAllNodes: function() { var list = []; collectNodes(nodes[this._id], list); return list }, isLeaf: function() { return !nodes[this._id].isNode() }, isActive: function() { return nodes[this._id].isActive() }, value: function(arg) { var result, node = nodes[this._id]; if (void 0 !== arg) { updateValue(node, arg > 0 ? Number(arg) : 0); change(node, ["TILING"]); result = this } else { result = node.value } return result }, label: function(arg) { var result, node = nodes[this._id]; if (void 0 !== arg) { node.customLabel = arg ? String(arg) : null; change(node, ["LABELS"]); result = this } else { result = node.customLabel || node.label } return result }, customize: function(settings) { var node = nodes[this._id]; if (settings) { node._custom = node._custom || {}; _extend(true, node._custom, settings); node._partialState = node._partialLabelState = null } change(node, ["TILES", "LABELS"]); return this }, resetCustomization: function() { var node = nodes[this._id]; node._custom = node._partialState = node._partialLabelState = null; change(node, ["TILES", "LABELS"]); return this } }; that._extendProxyType(Proxy.prototype); function Proxy(node) { var that = this; node.proxy = that; that._id = node._id; that.level = node.level; that.index = node.index; that.data = node.data } that._handlers.beginBuildNodes = function() { nodes = that._nodes; new Proxy(that._root) }; that._handlers.buildNode = function(node) { new Proxy(node) }; that._handlers.endBuildNodes = function() { that._eventTrigger("nodesInitialized", { root: that._root.proxy }) } }; function change(node, codes) { var ctx = node.ctx; ctx.suspend(); ctx.change(codes); ctx.resume() } function collectNodes(node, list) { var i, nodes = node.nodes, ii = nodes && nodes.length; for (i = 0; i < ii; ++i) { list.push(nodes[i].proxy); collectNodes(nodes[i], list) } } function updateValue(node, value) { var delta = value - node.value; while (node) { node.value += delta; node = node.parent } } proto._extendProxyType = __webpack_require__( /*! ./common */ 635).empty; var _resetNodes = proto._resetNodes; proto._resetNodes = function() { _resetNodes.call(this); this._eventTrigger("nodesRendering", { node: this._topNode.proxy }) }; var _updateStyles = nodeProto.updateStyles; nodeProto.updateStyles = function() { var that = this; _updateStyles.call(that); if (that._custom) { that._partialState = !that.ctx.forceReset && that._partialState || that.ctx.calculateState(that._custom); _extend(true, that.state, that._partialState) } }; var _updateLabelStyle = nodeProto.updateLabelStyle; nodeProto.updateLabelStyle = function() { var that = this, custom = that._custom; _updateLabelStyle.call(that); if (custom && custom.label) { that._partialLabelState = !that.ctx.forceReset && that._partialLabelState || calculatePartialLabelState(that, custom.label); that.labelState = _extend(true, {}, that.labelState, that._partialLabelState) } }; function calculatePartialLabelState(node, settings) { var state = node.ctx.calculateLabelState(settings); if ("visible" in settings) { state.visible = !!settings.visible } return state } proto.getRootNode = function() { return this._root.proxy }; proto.resetNodes = function() { var context = this._context; context.suspend(); context.change(["NODES_CREATE"]); context.resume(); return this } }, /*!**********************************!*\ !*** ./js/viz/tree_map/hover.js ***! \**********************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, nodeProto = __webpack_require__( /*! ./node */ 636).prototype, common = __webpack_require__( /*! ./common */ 635), _parseScalar = __webpack_require__( /*! ../core/utils */ 509).parseScalar, _buildRectAppearance = common.buildRectAppearance, STATE_CODE = 1; __webpack_require__( /*! ./api */ 647); __webpack_require__( /*! ./states */ 649); proto._eventsMap.onHoverChanged = { name: "hoverChanged" }; common.expand(proto._handlers, "calculateAdditionalStates", function(states, options) { states[1] = options.hoverStyle ? _buildRectAppearance(options.hoverStyle) : {} }); __webpack_require__( /*! ./tree_map.base */ 634).addChange({ code: "HOVER_ENABLED", handler: function() { var hoverEnabled = _parseScalar(this._getOption("hoverEnabled", true), true); if (!hoverEnabled) { this.clearHover() } this._hoverEnabled = hoverEnabled }, isThemeDependent: true, isOptionChange: true, option: "hoverEnabled" }); nodeProto.statesMap[1] = 1; nodeProto.additionalStates.push(1); common.expand(proto, "_extendProxyType", function(proto) { var that = this; proto.setHover = function() { that._hoverNode(this._id) }; proto.isHovered = function() { return that._hoverIndex === this._id } }); common.expand(proto, "_onNodesCreated", function() { this._hoverIndex = -1 }); common.expand(proto, "_changeGroupSettings", function() { var that = this; that._groupHoverEnabled = _parseScalar(that._getOption("group").hoverEnabled, true); if (!that._groupHoverEnabled) { that.clearHover() } }); proto._applyHoverState = function(index, state) { setNodeStateRecursive(this._nodes[index], STATE_CODE, state); this._eventTrigger("hoverChanged", { node: this._nodes[index].proxy }) }; function setNodeStateRecursive(node, code, state) { var i, nodes = node.isNode() && node.nodes, ii = nodes && nodes.length; node.setState(code, state); for (i = 0; i < ii; ++i) { setNodeStateRecursive(nodes[i], code, state) } } proto._hoverNode = function(index) { var that = this, currentIndex = that._hoverIndex; if (that._hoverEnabled && currentIndex !== index) { if (!that._groupHoverEnabled && index >= 0 && that._nodes[index].isNode()) { that.clearHover(); return } that._context.suspend(); that._hoverIndex = -1; if (currentIndex >= 0) { that._applyHoverState(currentIndex, false) } that._hoverIndex = index; if (index >= 0) { that._applyHoverState(index, true) } that._context.resume() } }; proto.clearHover = function() { this._hoverNode(-1) } }, /*!***********************************!*\ !*** ./js/viz/tree_map/states.js ***! \***********************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, nodeProto = __webpack_require__( /*! ./node */ 636).prototype, handlers = proto._handlers, _calculateState = handlers.calculateState, _buildState = nodeProto._buildState, _extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend; handlers.calculateState = function(options) { var states = { 0: _calculateState(options) }; handlers.calculateAdditionalStates(states, options); return states }; handlers.calculateAdditionalStates = __webpack_require__( /*! ./common */ 635).empty; nodeProto.code = 0; nodeProto.statesMap = { 0: 0 }; nodeProto.additionalStates = []; nodeProto._buildState = function(state, extra) { var states = { 0: _buildState(state[0], extra) }; if (this.additionalStates.length) { buildAdditionalStates(states, states[0], state, this.additionalStates) } return states }; nodeProto._getState = function() { return this.state[this.statesMap[this.code]] }; nodeProto.setState = function(code, state) { if (state) { this.code |= code } else { this.code &= ~code } this.ctx.change(["TILES"]) }; function buildAdditionalStates(states, base, source, list) { var i, ii = list.length; for (i = 0; i < ii; ++i) { states[list[i]] = _extend({}, base, source[list[i]]) } } }, /*!**************************************!*\ !*** ./js/viz/tree_map/selection.js ***! \**************************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, nodeProto = __webpack_require__( /*! ./node */ 636).prototype, common = __webpack_require__( /*! ./common */ 635), _buildRectAppearance = common.buildRectAppearance, _normalizeEnum = __webpack_require__( /*! ../core/utils */ 509).normalizeEnum, _inArray = __webpack_require__( /*! ../../core/utils/array */ 26).inArray, MODE_NONE = 0, MODE_SINGLE = 1, MODE_MULTIPLE = 2, STATE_CODE = 2; __webpack_require__( /*! ./api */ 647); __webpack_require__( /*! ./states */ 649); proto._eventsMap.onSelectionChanged = { name: "selectionChanged" }; common.expand(proto._handlers, "calculateAdditionalStates", function(states, options) { states[2] = options.selectionStyle ? _buildRectAppearance(options.selectionStyle) : {} }); nodeProto.statesMap[2] = nodeProto.statesMap[3] = STATE_CODE; nodeProto.additionalStates.push(2); common.expand(proto, "_onNodesCreated", function() { this._selectionList.length = 0 }); common.expand(proto, "_extendProxyType", function(proto) { var that = this; proto.select = function(state) { that._selectNode(this._id, !!state) }; proto.isSelected = function() { return _inArray(this._id, that._selectionList) >= 0 }; that._selectionList = [] }); __webpack_require__( /*! ./tree_map.base */ 634).addChange({ code: "SELECTION_MODE", handler: function() { var mode, tmp, that = this, option = _normalizeEnum(that._getOption("selectionMode", true)), selectionList = that._selectionList; mode = "none" === option ? MODE_NONE : "multiple" === option ? MODE_MULTIPLE : MODE_SINGLE; if (mode === MODE_SINGLE && selectionList.length > 1) { tmp = selectionList.pop(); that.clearSelection(); selectionList.push(tmp) } else { if (mode === MODE_NONE) { that.clearSelection() } } that._selectionMode = mode }, isThemeDependent: true, isOptionChange: true, option: "selectionMode" }); common.expand(proto, "_applyTilesAppearance", function() { if (this._selectionList.length) { bringSelectedTilesToForeground(this._nodes, this._selectionList) } }); function bringSelectedTilesToForeground(nodes, selectionList) { var i, node, ii = selectionList.length; for (i = 0; i < ii; ++i) { node = nodes[selectionList[i]]; tileToFront[Number(node.isNode())](node.tile) } } var tileToFront = [leafToFront, groupToFront]; function leafToFront(content) { content.toForeground() } function groupToFront(content) { content.outer.toForeground(); content.inner.toForeground() } proto._applySelectionState = function(index, state) { var node = this._nodes[index]; node.setState(STATE_CODE, state); this._eventTrigger("selectionChanged", { node: node.proxy }) }; proto._selectNode = function(index, state) { var selectionList, k, tmp, that = this; if (that._selectionMode !== MODE_NONE) { that._context.suspend(); selectionList = that._selectionList; k = _inArray(index, selectionList); if (state && k === -1) { if (that._selectionMode === MODE_SINGLE) { if (selectionList.length) { tmp = selectionList.pop(); that._applySelectionState(tmp, false) } } selectionList.push(index); that._applySelectionState(index, true) } else { if (!state && k >= 0) { selectionList.splice(k, 1); that._applySelectionState(index, false) } } that._context.resume() } }; proto.clearSelection = function() { var i, that = this, selectionList = that._selectionList, ii = selectionList.length; if (that._selectionMode !== MODE_NONE) { that._context.suspend(); for (i = 0; i < ii; ++i) { that._applySelectionState(selectionList[i], false) } selectionList.length = 0; that._context.resume() } } }, /*!************************************!*\ !*** ./js/viz/tree_map/tooltip.js ***! \************************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, common = __webpack_require__( /*! ./common */ 635); __webpack_require__( /*! ./api */ 647); common.expand(proto, "_extendProxyType", function(proto) { var that = this; proto.showTooltip = function(coords) { that._showTooltip(this._id, coords) } }); common.expand(proto, "_onNodesCreated", function() { if (this._tooltipIndex >= 0) { this._tooltip.hide() } this._tooltipIndex = -1 }); common.expand(proto, "_onTilingPerformed", function() { if (this._tooltipIndex >= 0) { this._moveTooltip(this._nodes[this._tooltipIndex]) } }); function getCoords(rect, renderer) { var offset = renderer.getRootOffset(); return [(rect[0] + rect[2]) / 2 + offset.left, (rect[1] + rect[3]) / 2 + offset.top] } proto._showTooltip = function(index, coords) { var node, state, that = this, tooltip = that._tooltip; if (tooltip.isEnabled()) { node = that._nodes[index]; state = that._tooltipIndex === index || tooltip.show({ value: node.value, valueText: tooltip.formatValue(node.value), node: node.proxy }, { x: 0, y: 0, offset: 0 }, { node: node.proxy }); if (state) { that._moveTooltip(node, coords) } else { tooltip.hide() } that._tooltipIndex = state ? index : -1 } }; proto._moveTooltip = function(node, coords) { var xy = coords || node.rect && getCoords(node.rect, this._renderer) || [-1e3, -1e3]; this._tooltip.move(xy[0], xy[1], 0) }; proto.hideTooltip = function() { if (this._tooltipIndex >= 0) { this._tooltipIndex = -1; this._tooltip.hide() } }; __webpack_require__( /*! ./tree_map.base */ 634).addPlugin(__webpack_require__( /*! ../core/tooltip */ 559).plugin) }, /*!************************************!*\ !*** ./js/viz/tree_map/tracker.js ***! \************************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, common = __webpack_require__( /*! ./common */ 635), extend = __webpack_require__( /*! ../../core/utils/extend */ 11).extend, _eventData = __webpack_require__( /*! ../../events/utils */ 71).eventData, _parseScalar = __webpack_require__( /*! ../core/utils */ 509).parseScalar, clickEventName = __webpack_require__( /*! ../../events/click */ 75).name, downPointerEventName = __webpack_require__( /*! ../../events/pointer */ 76).down, movePointerEventName = __webpack_require__( /*! ../../events/pointer */ 76).move, $ = __webpack_require__( /*! ../../core/renderer */ 9), $doc = $(document), DATA_KEY_BASE = "__treemap_data_", dataKeyModifier = 0; __webpack_require__( /*! ./api */ 647); __webpack_require__( /*! ./hover */ 648); __webpack_require__( /*! ./tooltip */ 651); proto._eventsMap.onClick = { name: "click" }; common.expand(proto, "_initCore", function() { var that = this, dataKey = DATA_KEY_BASE + dataKeyModifier++; that._tracker = new Tracker({ widget: that, root: that._renderer.root, eventTrigger: that._eventTrigger, getData: function(e) { var target = e.target; return ("tspan" === target.tagName ? target.parentNode : target)[dataKey] }, getProxy: function(index) { return that._nodes[index].proxy }, getCoords: function(e) { var data = _eventData(e), offset = that._renderer.getRootOffset(); return [data.x - offset.left, data.y - offset.top] } }); that._handlers.setTrackerData = function(node, element) { element.data(dataKey, node._id) }; exports._TESTS_dataKey = dataKey }); common.expand(proto, "_disposeCore", function() { this._tracker.dispose() }); __webpack_require__( /*! ./tree_map.base */ 634).addChange({ code: "INTERACT_WITH_GROUP", handler: function() { this._tracker.setOptions({ interactWithGroup: _parseScalar(this._getOption("interactWithGroup", true), false) }) }, isThemeDependent: true, isOptionChange: true, option: "interactWithGroup" }); function Tracker(parameters) { this._options = {}; this._initHandlers(parameters, this._options) } Tracker.prototype = { constructor: Tracker, _initHandlers: function(parameters, options) { parameters.getNode = function(id) { var proxy = parameters.getProxy(id); return options.interactWithGroup && proxy.isLeaf() && proxy.getParent().isActive() ? proxy.getParent() : proxy }; parameters.root.on(clickEventName, clickHandler); parameters.root.on(downPointerEventName, downHandler); $doc.on(downPointerEventName, downHandler); $doc.on(movePointerEventName, moveHandler); this._disposeHandlers = function() { parameters.root.off(clickEventName, clickHandler); parameters.root.off(downPointerEventName, downHandler); $doc.off(downPointerEventName, downHandler); $doc.off(movePointerEventName, moveHandler) }; function clickHandler(e) { processClick(e, parameters) } var isRootDown = false; function downHandler(e) { if (isRootDown) { isRootDown = false } else { if (void 0 !== parameters.getData(e)) { e.preventDefault(); isRootDown = true } moveHandler(e) } } function moveHandler(e) { processHover(e, parameters); processTooltip(e, parameters) } }, dispose: function() { this._disposeHandlers() }, setOptions: function(options) { extend(this._options, options) } }; function processClick(e, params) { var id = params.getData(e); if (id >= 0) { params.eventTrigger("click", { node: params.getNode(id), coords: params.getCoords(e), jQueryEvent: e }) } } function processHover(e, params) { var id = params.getData(e); if (id >= 0) { params.getNode(id).setHover() } else { params.widget.clearHover() } } function processTooltip(e, params) { var coords, id = params.getData(e); if (id >= 0) { coords = _eventData(e); params.getNode(id).showTooltip([coords.x, coords.y]) } else { params.widget.hideTooltip() } } }, /*!**************************************!*\ !*** ./js/viz/tree_map/drilldown.js ***! \**************************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype, _expand = __webpack_require__( /*! ./common */ 635).expand; __webpack_require__( /*! ./api */ 647); proto._eventsMap.onDrill = { name: "drill" }; _expand(proto, "_extendProxyType", function(proto) { var that = this; proto.drillDown = function() { that._drillToNode(this._id) } }); _expand(proto, "_onNodesCreated", function() { this._drilldownIndex = -1 }); proto._drillToNode = function(index) { var node, that = this; if (that._drilldownIndex !== index) { node = that._nodes[index] || that._root; if (node.nodes) { that._drilldownIndex = index; that._topNode = node; that._context.suspend(); that._context.change(["MAX_DEPTH", "NODES_RESET"]); that._context.resume(); that._eventTrigger("drill", { node: node.proxy }) } } }; proto.resetDrillDown = function() { this._drillToNode(-1); return this }; proto.drillUp = function() { this._drillToNode(this._topNode.parent._id || -1); return this }; proto.getCurrentNode = function() { return this._topNode.proxy } }, /*!**********************************************!*\ !*** ./js/viz/tree_map/plain_data_source.js ***! \**********************************************/ function(module, exports, __webpack_require__) { var proto = __webpack_require__( /*! ./tree_map.base */ 634).prototype; proto._optionChangesMap.idField = proto._optionChangesMap.parentField = "NODES_CREATE"; proto._processDataSourceItems = function(items) { var i, currentItem, parentId, tmpItems, item, struct = {}, idField = this._getOption("idField", true), parentField = this._getOption("parentField", true), rootNodes = []; if (!idField || !parentField || 0 === items.length) { return { items: items, isPlain: true } } for (i = 0; i < items.length; i++) { currentItem = items[i]; parentId = currentItem[parentField]; if (!!parentId) { struct[parentId] = struct[parentId] || { items: [] }; tmpItems = struct[parentId].items } else { tmpItems = rootNodes } tmpItems.push(currentItem) } treeFiller({ struct: struct, idField: idField }, rootNodes); for (item in struct) { struct[item] && rootNodes.push(struct[item]) } return { items: rootNodes, isPlain: true } }; function treeFiller(context, items) { var currentItem, i, id, struct = context.struct; for (i = 0; i < items.length; i++) { currentItem = items[i]; id = currentItem[context.idField]; if (struct[id]) { currentItem.items = struct[id].items; struct[id] = null; treeFiller(context, currentItem.items) } } } }, /*!*************************!*\ !*** ./js/viz/utils.js ***! \*************************/ function(module, exports, __webpack_require__) { exports.refreshPaths = __webpack_require__( /*! ./core/renderers/renderer */ 518).refreshPaths }, , , , /*!******************************!*\ !*** ./js/bundles/dx.viz.js ***! \******************************/ function(module, exports, __webpack_require__) { __webpack_require__( /*! ./modules/parts/viz */ 506) } ]);